algo.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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 parse_meminfo(untrusted_meminfo):
  36. untrusted_dict = {}
  37. #split meminfo contents into lines
  38. untrusted_lines = string.split(untrusted_meminfo,"\n")
  39. for untrusted_lines_iterator in untrusted_lines:
  40. #split a single meminfo line into words
  41. untrusted_words = string.split(untrusted_lines_iterator)
  42. if len(untrusted_words) >= 2:
  43. untrusted_dict[string.rstrip(untrusted_words[0], ":")] = untrusted_words[1]
  44. return untrusted_dict
  45. def is_meminfo_suspicious(domain, untrusted_meminfo):
  46. log.debug('is_meminfo_suspicious('
  47. 'domain={!r}, untrusted_meminfo={!r})'.format(
  48. domain, untrusted_meminfo))
  49. ret = False
  50. #check whether the required keys exist and are not negative
  51. try:
  52. for i in ('MemTotal', 'MemFree', 'Buffers', 'Cached', 'SwapTotal', 'SwapFree'):
  53. val = int(untrusted_meminfo[i])*1024
  54. if (val < 0):
  55. ret = True
  56. untrusted_meminfo[i] = val
  57. except:
  58. ret = True
  59. if not ret and untrusted_meminfo['SwapTotal'] < untrusted_meminfo['SwapFree']:
  60. ret = True
  61. if not ret and untrusted_meminfo['MemTotal'] < untrusted_meminfo['MemFree'] + untrusted_meminfo['Cached'] + untrusted_meminfo['Buffers']:
  62. ret = True
  63. #we could also impose some limits on all the above values
  64. #but it has little purpose - all the domain can gain by passing e.g.
  65. #very large SwapTotal is that it will be assigned all free Xen memory
  66. #it can be achieved with legal values, too, and it will not allow to
  67. #starve existing domains, by design
  68. if ret:
  69. log.warning('suspicious meminfo for domain {!r}'
  70. ' memory_actual={!r} untrusted_meminfo={!r}'.format(domain.id,
  71. domain.memory_actual, untrusted_meminfo))
  72. return ret
  73. #called when a domain updates its 'meminfo' xenstore key
  74. def refresh_meminfo_for_domain(domain, untrusted_xenstore_key):
  75. untrusted_meminfo = parse_meminfo(untrusted_xenstore_key)
  76. if untrusted_meminfo is None:
  77. domain.meminfo = None
  78. return
  79. #sanitize start
  80. if is_meminfo_suspicious(domain, untrusted_meminfo):
  81. #sanitize end
  82. domain.meminfo = None
  83. domain.mem_used = None
  84. else:
  85. #sanitized, can assign
  86. domain.meminfo = untrusted_meminfo
  87. domain.mem_used = domain.meminfo['MemTotal'] - domain.meminfo['MemFree'] - domain.meminfo['Cached'] - domain.meminfo['Buffers'] + domain.meminfo['SwapTotal'] - domain.meminfo['SwapFree']
  88. def prefmem(domain):
  89. #dom0 is special, as it must have large cache, for vbds. Thus, give it a special boost
  90. if domain.id == '0':
  91. return min(domain.mem_used*CACHE_FACTOR + 350*1024*1024, domain.memory_maximum)
  92. return max(min(domain.mem_used*CACHE_FACTOR, domain.memory_maximum), MIN_PREFMEM)
  93. def memory_needed(domain):
  94. #do not change
  95. #in balance(), "distribute total_available_memory proportionally to mempref" relies on this exact formula
  96. ret = prefmem(domain) - domain.memory_actual
  97. return ret
  98. #prepare list of (domain, memory_target) pairs that need to be passed
  99. #to "xm memset" equivalent in order to obtain "memsize" of memory
  100. #return empty list when the request cannot be satisfied
  101. def balloon(memsize, domain_dictionary):
  102. log.debug('balloon(memsize={!r}, domain_dictionary={!r})'.format(
  103. memsize, domain_dictionary))
  104. REQ_SAFETY_NET_FACTOR = 1.05
  105. donors = list()
  106. request = list()
  107. available = 0
  108. for i in domain_dictionary.keys():
  109. if domain_dictionary[i].meminfo is None:
  110. continue
  111. if domain_dictionary[i].no_progress:
  112. continue
  113. need = memory_needed(domain_dictionary[i])
  114. if need < 0:
  115. log.info('balloon: dom {} has actual memory {}'.format(i,
  116. domain_dictionary[i].memory_actual))
  117. donors.append((i,-need))
  118. available-=need
  119. log.info('req={} avail={} donors={!r}'.format(memsize, available, donors))
  120. if available<memsize:
  121. return ()
  122. scale = 1.0*memsize/available
  123. for donors_iter in donors:
  124. id, mem = donors_iter
  125. memborrowed = mem*scale*REQ_SAFETY_NET_FACTOR
  126. log.info('borrow {} from {}'.format(memborrowed, id))
  127. memtarget = int(domain_dictionary[id].memory_actual - memborrowed)
  128. request.append((id, memtarget))
  129. return request
  130. # REQ_SAFETY_NET_FACTOR is a bit greater that 1. So that if the domain yields a bit less than requested, due
  131. # to e.g. rounding errors, we will not get stuck. The surplus will return to the VM during "balance" call.
  132. #redistribute positive "total_available_memory" of memory between domains, proportionally to prefmem
  133. def balance_when_enough_memory(domain_dictionary,
  134. xen_free_memory, total_mem_pref, total_available_memory):
  135. log.info('balance_when_enough_memory(xen_free_memory={!r}, '
  136. 'total_mem_pref={!r}, total_available_memory={!r})'.format(
  137. xen_free_memory, total_mem_pref, total_available_memory))
  138. target_memory = {}
  139. # memory not assigned because of static max
  140. left_memory = 0
  141. acceptors_count = 0
  142. for i in domain_dictionary.keys():
  143. if domain_dictionary[i].meminfo is None:
  144. continue
  145. if domain_dictionary[i].no_progress:
  146. continue
  147. #distribute total_available_memory proportionally to mempref
  148. scale = 1.0*prefmem(domain_dictionary[i])/total_mem_pref
  149. target_nonint = prefmem(domain_dictionary[i]) + scale*total_available_memory
  150. #prevent rounding errors
  151. target = int(0.999*target_nonint)
  152. #do not try to give more memory than static max
  153. if target > domain_dictionary[i].memory_maximum:
  154. left_memory += target-domain_dictionary[i].memory_maximum
  155. target = domain_dictionary[i].memory_maximum
  156. else:
  157. # count domains which can accept more memory
  158. acceptors_count += 1
  159. target_memory[i] = target
  160. # distribute left memory across all acceptors
  161. while left_memory > 0 and acceptors_count > 0:
  162. log.info('left_memory={} acceptors_count={}'.format(
  163. left_memory, acceptors_count))
  164. new_left_memory = 0
  165. new_acceptors_count = acceptors_count
  166. for i in target_memory.keys():
  167. target = target_memory[i]
  168. if target < domain_dictionary[i].memory_maximum:
  169. memory_bonus = int(0.999*(left_memory/acceptors_count))
  170. if target+memory_bonus >= domain_dictionary[i].memory_maximum:
  171. new_left_memory += target+memory_bonus - domain_dictionary[i].memory_maximum
  172. target = domain_dictionary[i].memory_maximum
  173. new_acceptors_count -= 1
  174. else:
  175. target += memory_bonus
  176. target_memory[i] = target
  177. left_memory = new_left_memory
  178. acceptors_count = new_acceptors_count
  179. # split target_memory dictionary to donors and acceptors
  180. # this is needed to first get memory from donors and only then give it to acceptors
  181. donors_rq = list()
  182. acceptors_rq = list()
  183. for i in target_memory.keys():
  184. target = target_memory[i]
  185. if (target < domain_dictionary[i].memory_actual):
  186. donors_rq.append((i, target))
  187. else:
  188. acceptors_rq.append((i, target))
  189. # print 'balance(enough): xen_free_memory=', xen_free_memory, 'requests:', donors_rq + acceptors_rq
  190. return donors_rq + acceptors_rq
  191. #when not enough mem to make everyone be above prefmem, make donors be at prefmem, and
  192. #redistribute anything left between acceptors
  193. def balance_when_low_on_memory(domain_dictionary,
  194. xen_free_memory, total_mem_pref_acceptors, donors, acceptors):
  195. log.debug('balance_when_low_on_memory(xen_free_memory={!r}, '
  196. 'total_mem_pref_acceptors={!r}, donors={!r}, acceptors={!r})'.format(
  197. xen_free_memory, total_mem_pref_acceptors, donors, acceptors))
  198. donors_rq = list()
  199. acceptors_rq = list()
  200. squeezed_mem = xen_free_memory
  201. for i in donors:
  202. avail = -memory_needed(domain_dictionary[i])
  203. if avail < 10*1024*1024:
  204. #probably we have already tried making it exactly at prefmem, give up
  205. continue
  206. squeezed_mem -= avail
  207. donors_rq.append((i, prefmem(domain_dictionary[i])))
  208. #the below can happen if initially xen free memory is below 50M
  209. if squeezed_mem < 0:
  210. return donors_rq
  211. for i in acceptors:
  212. scale = 1.0*prefmem(domain_dictionary[i])/total_mem_pref_acceptors
  213. target_nonint = domain_dictionary[i].memory_actual + scale*squeezed_mem
  214. #do not try to give more memory than static max
  215. target = min(int(0.999*target_nonint), domain_dictionary[i].memory_maximum)
  216. acceptors_rq.append((i, target))
  217. # print 'balance(low): xen_free_memory=', xen_free_memory, 'requests:', donors_rq + acceptors_rq
  218. return donors_rq + acceptors_rq
  219. #redistribute memory across domains
  220. #called when one of domains update its 'meminfo' xenstore key
  221. #return the list of (domain, memory_target) pairs to be passed to
  222. #"xm memset" equivalent
  223. def balance(xen_free_memory, domain_dictionary):
  224. log.debug('balance(xen_free_memory={!r}, domain_dictionary={!r})'.format(
  225. xen_free_memory, domain_dictionary))
  226. #sum of all memory requirements - in other words, the difference between
  227. #memory required to be added to domains (acceptors) to make them be at their
  228. #preferred memory, and memory that can be taken from domains (donors) that
  229. #can provide memory. So, it can be negative when plenty of memory.
  230. total_memory_needed = 0
  231. #sum of memory preferences of all domains
  232. total_mem_pref = 0
  233. #sum of memory preferences of all domains that require more memory
  234. total_mem_pref_acceptors = 0
  235. donors = list() # domains that can yield memory
  236. acceptors = list() # domains that require more memory
  237. #pass 1: compute the above "total" values
  238. for i in domain_dictionary.keys():
  239. if domain_dictionary[i].meminfo is None:
  240. continue
  241. if domain_dictionary[i].no_progress:
  242. continue
  243. need = memory_needed(domain_dictionary[i])
  244. # print 'domain' , i, 'act/pref', domain_dictionary[i].memory_actual, prefmem(domain_dictionary[i]), 'need=', need
  245. if need < 0 or domain_dictionary[i].memory_actual >= domain_dictionary[i].memory_maximum:
  246. donors.append(i)
  247. else:
  248. acceptors.append(i)
  249. total_mem_pref_acceptors += prefmem(domain_dictionary[i])
  250. total_memory_needed += need
  251. total_mem_pref += prefmem(domain_dictionary[i])
  252. total_available_memory = xen_free_memory - total_memory_needed
  253. if total_available_memory > 0:
  254. return balance_when_enough_memory(domain_dictionary, xen_free_memory, total_mem_pref, total_available_memory)
  255. else:
  256. return balance_when_low_on_memory(domain_dictionary, xen_free_memory, total_mem_pref_acceptors, donors, acceptors)