algo.py 12 KB

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