algo.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. # pylint: skip-file
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2010 Rafal Wojtczuk <rafal@invisiblethingslab.com>
  6. # Copyright (C) 2013 Marek Marczykowski <marmarek@invisiblethingslab.com>
  7. #
  8. # This library is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU Lesser General Public
  10. # License as published by the Free Software Foundation; either
  11. # version 2.1 of the License, or (at your option) any later version.
  12. #
  13. # This library is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. # Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public
  19. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  20. #
  21. import logging
  22. import string
  23. # This are only defaults - can be overridden by QMemmanServer with values from
  24. # config file
  25. CACHE_FACTOR = 1.3
  26. MIN_PREFMEM = 200 * 1024 * 1024
  27. DOM0_MEM_BOOST = 350 * 1024 * 1024
  28. log = logging.getLogger('qmemman.daemon.algo')
  29. # untrusted meminfo size is taken from xenstore key, thus its size is limited
  30. # so splits do not require excessive memory
  31. def sanitize_and_parse_meminfo(untrusted_meminfo):
  32. if not untrusted_meminfo:
  33. return None
  34. # new syntax - just one int
  35. try:
  36. if int(untrusted_meminfo) >= 0:
  37. return int(untrusted_meminfo) * 1024
  38. except ValueError:
  39. pass
  40. untrusted_meminfo = untrusted_meminfo.decode('ascii', errors='strict')
  41. # not new syntax - try the old one
  42. untrusted_dict = {}
  43. # split meminfo contents into lines
  44. untrusted_lines = untrusted_meminfo.split("\n")
  45. for untrusted_lines_iterator in untrusted_lines:
  46. # split a single meminfo line into words
  47. untrusted_words = untrusted_lines_iterator.split()
  48. if len(untrusted_words) >= 2:
  49. untrusted_dict[untrusted_words[0].rstrip(":")] = \
  50. untrusted_words[1]
  51. # sanitize start
  52. if not is_meminfo_suspicious(untrusted_dict):
  53. # sanitize end
  54. meminfo = untrusted_dict
  55. return (meminfo['MemTotal'] -
  56. meminfo['MemFree'] - meminfo['Cached'] - meminfo['Buffers'] +
  57. meminfo['SwapTotal'] - meminfo['SwapFree']) * 1024
  58. return None
  59. def is_meminfo_suspicious(untrusted_meminfo):
  60. log.debug('is_meminfo_suspicious('
  61. 'untrusted_meminfo={!r})'.format(untrusted_meminfo))
  62. ret = False
  63. # check whether the required keys exist and are not negative
  64. try:
  65. for i in ('MemTotal', 'MemFree', 'Buffers', 'Cached',
  66. 'SwapTotal', 'SwapFree'):
  67. val = int(untrusted_meminfo[i])
  68. if val < 0:
  69. ret = True
  70. untrusted_meminfo[i] = val
  71. except:
  72. ret = True
  73. if untrusted_meminfo['SwapTotal'] < untrusted_meminfo['SwapFree']:
  74. ret = True
  75. if untrusted_meminfo['MemTotal'] < \
  76. untrusted_meminfo['MemFree'] + \
  77. untrusted_meminfo['Cached'] + untrusted_meminfo[
  78. 'Buffers']:
  79. ret = True
  80. # we could also impose some limits on all the above values
  81. # but it has little purpose - all the domain can gain by passing e.g.
  82. # very large SwapTotal is that it will be assigned all free Xen memory
  83. # it can be achieved with legal values, too, and it will not allow to
  84. # starve existing domains, by design
  85. if ret:
  86. log.warning('suspicious meminfo untrusted_meminfo={!r}'.format(
  87. untrusted_meminfo))
  88. return ret
  89. # called when a domain updates its 'meminfo' xenstore key
  90. def refresh_meminfo_for_domain(domain, untrusted_xenstore_key):
  91. domain.mem_used = sanitize_and_parse_meminfo(untrusted_xenstore_key)
  92. def prefmem(domain):
  93. # dom0 is special, as it must have large cache, for vbds. Thus, give it
  94. # a special boost
  95. if domain.id == '0':
  96. return min(domain.mem_used * CACHE_FACTOR + DOM0_MEM_BOOST,
  97. domain.memory_maximum)
  98. return max(min(domain.mem_used * CACHE_FACTOR, domain.memory_maximum),
  99. MIN_PREFMEM)
  100. def memory_needed(domain):
  101. # do not change
  102. # in balance(), "distribute total_available_memory proportionally to
  103. # mempref" relies on this exact formula
  104. ret = prefmem(domain) - domain.memory_actual
  105. return ret
  106. # prepare list of (domain, memory_target) pairs that need to be passed
  107. # to "xm memset" equivalent in order to obtain "memsize" of memory
  108. # return empty list when the request cannot be satisfied
  109. def balloon(memsize, domain_dictionary):
  110. log.debug('balloon(memsize={!r}, domain_dictionary={!r})'.format(
  111. memsize, domain_dictionary))
  112. REQ_SAFETY_NET_FACTOR = 1.05
  113. donors = list()
  114. request = list()
  115. available = 0
  116. for i in domain_dictionary.keys():
  117. if domain_dictionary[i].mem_used is None:
  118. continue
  119. if domain_dictionary[i].no_progress:
  120. continue
  121. need = memory_needed(domain_dictionary[i])
  122. if need < 0:
  123. log.info('balloon: dom {} has actual memory {}'.format(i,
  124. domain_dictionary[i].memory_actual))
  125. donors.append((i, -need))
  126. available -= need
  127. log.info('req={} avail={} donors={!r}'.format(memsize, available, donors))
  128. if available < memsize:
  129. return ()
  130. scale = 1.0 * memsize / available
  131. for donors_iter in donors:
  132. dom_id, mem = donors_iter
  133. memborrowed = mem * scale * REQ_SAFETY_NET_FACTOR
  134. log.info('borrow {} from {}'.format(memborrowed, dom_id))
  135. memtarget = int(domain_dictionary[dom_id].memory_actual - memborrowed)
  136. request.append((dom_id, memtarget))
  137. return request
  138. # REQ_SAFETY_NET_FACTOR is a bit greater that 1. So that if the domain
  139. # yields a bit less than requested, due to e.g. rounding errors, we will not
  140. # get stuck. The surplus will return to the VM during "balance" call.
  141. # redistribute positive "total_available_memory" of memory between domains,
  142. # proportionally to prefmem
  143. def balance_when_enough_memory(domain_dictionary,
  144. xen_free_memory, total_mem_pref, total_available_memory):
  145. log.info('balance_when_enough_memory(xen_free_memory={!r}, '
  146. 'total_mem_pref={!r}, total_available_memory={!r})'.format(
  147. xen_free_memory, total_mem_pref, total_available_memory))
  148. target_memory = {}
  149. # memory not assigned because of static max
  150. left_memory = 0
  151. acceptors_count = 0
  152. for i in domain_dictionary.keys():
  153. if domain_dictionary[i].mem_used is None:
  154. continue
  155. if domain_dictionary[i].no_progress:
  156. continue
  157. # distribute total_available_memory proportionally to mempref
  158. scale = 1.0 * prefmem(domain_dictionary[i]) / total_mem_pref
  159. target_nonint = prefmem(
  160. domain_dictionary[i]) + scale * total_available_memory
  161. # prevent rounding errors
  162. target = int(0.999 * target_nonint)
  163. # do not try to give more memory than static max
  164. if target > domain_dictionary[i].memory_maximum:
  165. left_memory += target - domain_dictionary[i].memory_maximum
  166. target = domain_dictionary[i].memory_maximum
  167. else:
  168. # count domains which can accept more memory
  169. acceptors_count += 1
  170. target_memory[i] = target
  171. # distribute left memory across all acceptors
  172. while left_memory > 0 and acceptors_count > 0:
  173. log.info('left_memory={} acceptors_count={}'.format(
  174. left_memory, acceptors_count))
  175. new_left_memory = 0
  176. new_acceptors_count = acceptors_count
  177. for i in target_memory.keys():
  178. target = target_memory[i]
  179. if target < domain_dictionary[i].memory_maximum:
  180. memory_bonus = int(0.999 * (left_memory / acceptors_count))
  181. if target + memory_bonus >= domain_dictionary[i].memory_maximum:
  182. new_left_memory += target + memory_bonus - \
  183. domain_dictionary[i].memory_maximum
  184. target = domain_dictionary[i].memory_maximum
  185. new_acceptors_count -= 1
  186. else:
  187. target += memory_bonus
  188. target_memory[i] = target
  189. left_memory = new_left_memory
  190. acceptors_count = new_acceptors_count
  191. # split target_memory dictionary to donors and acceptors
  192. # this is needed to first get memory from donors and only then give it
  193. # to acceptors
  194. donors_rq = list()
  195. acceptors_rq = list()
  196. for i in target_memory.keys():
  197. target = target_memory[i]
  198. if target < domain_dictionary[i].memory_actual:
  199. donors_rq.append((i, target))
  200. else:
  201. acceptors_rq.append((i, target))
  202. # print 'balance(enough): xen_free_memory=', xen_free_memory, \
  203. # 'requests:', donors_rq + acceptors_rq
  204. return donors_rq + acceptors_rq
  205. # when not enough mem to make everyone be above prefmem, make donors be at
  206. # prefmem, and redistribute anything left between acceptors
  207. def balance_when_low_on_memory(domain_dictionary,
  208. xen_free_memory, total_mem_pref_acceptors, donors, acceptors):
  209. log.info('balance_when_low_on_memory(xen_free_memory={!r}, '
  210. 'total_mem_pref_acceptors={!r}, donors={!r}, acceptors={!r})'.format(
  211. xen_free_memory, total_mem_pref_acceptors, donors, acceptors))
  212. donors_rq = list()
  213. acceptors_rq = list()
  214. squeezed_mem = xen_free_memory
  215. for i in donors:
  216. avail = -memory_needed(domain_dictionary[i])
  217. if avail < 10 * 1024 * 1024:
  218. # probably we have already tried making it exactly at prefmem,
  219. # give up
  220. continue
  221. squeezed_mem -= avail
  222. donors_rq.append((i, prefmem(domain_dictionary[i])))
  223. # the below can happen if initially xen free memory is below 50M
  224. if squeezed_mem < 0:
  225. return donors_rq
  226. for i in acceptors:
  227. scale = 1.0 * prefmem(domain_dictionary[i]) / total_mem_pref_acceptors
  228. target_nonint = \
  229. domain_dictionary[i].memory_actual + scale * squeezed_mem
  230. # do not try to give more memory than static max
  231. target = \
  232. min(int(0.999 * target_nonint), domain_dictionary[i].memory_maximum)
  233. acceptors_rq.append((i, target))
  234. # print 'balance(low): xen_free_memory=', xen_free_memory, 'requests:',
  235. # donors_rq + acceptors_rq
  236. return donors_rq + acceptors_rq
  237. # redistribute memory across domains
  238. # called when one of domains update its 'meminfo' xenstore key
  239. # return the list of (domain, memory_target) pairs to be passed to
  240. # "xm memset" equivalent
  241. def balance(xen_free_memory, domain_dictionary):
  242. log.debug('balance(xen_free_memory={!r}, domain_dictionary={!r})'.format(
  243. xen_free_memory, domain_dictionary))
  244. # sum of all memory requirements - in other words, the difference between
  245. # memory required to be added to domains (acceptors) to make them be
  246. # at their preferred memory, and memory that can be taken from domains
  247. # (donors) that can provide memory. So, it can be negative when plenty
  248. # of memory.
  249. total_memory_needed = 0
  250. # sum of memory preferences of all domains
  251. total_mem_pref = 0
  252. # sum of memory preferences of all domains that require more memory
  253. total_mem_pref_acceptors = 0
  254. donors = list() # domains that can yield memory
  255. acceptors = list() # domains that require more memory
  256. # pass 1: compute the above "total" values
  257. for i in domain_dictionary.keys():
  258. if domain_dictionary[i].mem_used is None:
  259. continue
  260. if domain_dictionary[i].no_progress:
  261. continue
  262. need = memory_needed(domain_dictionary[i])
  263. # print 'domain' , i, 'act/pref', \
  264. # domain_dictionary[i].memory_actual, prefmem(domain_dictionary[i]), \
  265. # 'need=', need
  266. if need < 0 or domain_dictionary[i].memory_actual >= \
  267. domain_dictionary[i].memory_maximum:
  268. donors.append(i)
  269. else:
  270. acceptors.append(i)
  271. total_mem_pref_acceptors += prefmem(domain_dictionary[i])
  272. total_memory_needed += need
  273. total_mem_pref += prefmem(domain_dictionary[i])
  274. total_available_memory = xen_free_memory - total_memory_needed
  275. if total_available_memory > 0:
  276. return balance_when_enough_memory(domain_dictionary, xen_free_memory,
  277. total_mem_pref, total_available_memory)
  278. else:
  279. return balance_when_low_on_memory(domain_dictionary, xen_free_memory,
  280. total_mem_pref_acceptors, donors, acceptors)