algo.py 12 KB

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