__init__.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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 os
  23. import string
  24. import time
  25. import functools
  26. import xen.lowlevel.xc
  27. import xen.lowlevel.xs
  28. import qubes.qmemman.algo
  29. no_progress_msg="VM refused to give back requested memory"
  30. slow_memset_react_msg="VM didn't give back all requested memory"
  31. class DomainState:
  32. def __init__(self, id):
  33. self.memory_current = 0 # the current memory size
  34. self.memory_actual = None # the current memory allocation (what VM
  35. # is using or can use at any time)
  36. self.memory_maximum = None #the maximum memory size
  37. self.mem_used = None #used memory, computed based on meminfo
  38. self.id = id #domain id
  39. self.last_target = 0 #the last memset target
  40. self.no_progress = False #no react to memset
  41. self.slow_memset_react = False #slow react to memset (after few tries still above target)
  42. def __repr__(self):
  43. return self.__dict__.__repr__()
  44. class SystemState(object):
  45. def __init__(self):
  46. self.log = logging.getLogger('qmemman.systemstate')
  47. self.log.debug('SystemState()')
  48. self.domdict = {}
  49. self.xc = xen.lowlevel.xc.xc()
  50. self.xs = xen.lowlevel.xs.xs()
  51. self.BALOON_DELAY = 0.1
  52. self.XEN_FREE_MEM_LEFT = 50*1024*1024
  53. self.XEN_FREE_MEM_MIN = 25*1024*1024
  54. # Overhead of per-page Xen structures, taken from OpenStack nova/virt/xenapi/driver.py
  55. # see https://wiki.openstack.org/wiki/XenServer/Overhead
  56. # we divide total and free physical memory by this to get "assignable" memory
  57. self.MEM_OVERHEAD_FACTOR = 1.0 / 1.00781
  58. try:
  59. self.ALL_PHYS_MEM = int(self.xc.physinfo()['total_memory']*1024 * self.MEM_OVERHEAD_FACTOR)
  60. except xen.lowlevel.xc.Error:
  61. self.ALL_PHYS_MEM = 0
  62. def add_domain(self, id):
  63. self.log.debug('add_domain(id={!r})'.format(id))
  64. self.domdict[id] = DomainState(id)
  65. # TODO: move to DomainState.__init__
  66. target_str = self.xs.read('', '/local/domain/' + id + '/memory/target')
  67. if target_str:
  68. self.domdict[id].last_target = int(target_str) * 1024
  69. def del_domain(self, id):
  70. self.log.debug('del_domain(id={!r})'.format(id))
  71. self.domdict.pop(id)
  72. def get_free_xen_memory(self):
  73. xen_free = int(self.xc.physinfo()['free_memory']*1024 *
  74. self.MEM_OVERHEAD_FACTOR)
  75. # now check for domains which have assigned more memory than really
  76. # used - do not count it as "free", because domain is free to use it
  77. # at any time
  78. # assumption: self.refresh_memactual was called before
  79. # (so domdict[id].memory_actual is up to date)
  80. assigned_but_unused = functools.reduce(
  81. lambda acc, dom: acc + max(0, dom.last_target-dom.memory_current),
  82. self.domdict.values(),
  83. 0
  84. )
  85. # If, at any time, Xen have less memory than XEN_FREE_MEM_MIN,
  86. # it is a failure of qmemman. Collect as much data as possible to
  87. # debug it
  88. if xen_free < self.XEN_FREE_MEM_MIN:
  89. self.log.error("Xen free = {!r} below acceptable value! "
  90. "assigned_but_unused={!r}, domdict={!r}".format(
  91. xen_free, assigned_but_unused, self.domdict))
  92. elif xen_free < assigned_but_unused+self.XEN_FREE_MEM_MIN:
  93. self.log.error("Xen free = {!r} too small for satisfy assignments! "
  94. "assigned_but_unused={!r}, domdict={!r}".format(
  95. xen_free, assigned_but_unused, self.domdict))
  96. return xen_free - assigned_but_unused
  97. #refresh information on memory assigned to all domains
  98. def refresh_memactual(self):
  99. for domain in self.xc.domain_getinfo():
  100. id = str(domain['domid'])
  101. if id in self.domdict:
  102. # real memory usage
  103. self.domdict[id].memory_current = domain['mem_kb']*1024
  104. # what VM is using or can use
  105. self.domdict[id].memory_actual = max(
  106. self.domdict[id].memory_current,
  107. self.domdict[id].last_target
  108. )
  109. self.domdict[id].memory_maximum = self.xs.read('', '/local/domain/%s/memory/static-max' % str(id))
  110. if self.domdict[id].memory_maximum:
  111. self.domdict[id].memory_maximum = int(self.domdict[id].memory_maximum)*1024
  112. else:
  113. self.domdict[id].memory_maximum = self.ALL_PHYS_MEM
  114. # the previous line used to be
  115. # self.domdict[id].memory_maximum = domain['maxmem_kb']*1024
  116. # but domain['maxmem_kb'] changes in self.mem_set as well, and this results in
  117. # the memory never increasing
  118. # in fact, the only possible case of nonexisting memory/static-max is dom0
  119. # see #307
  120. def clear_outdated_error_markers(self):
  121. # Clear outdated errors
  122. for i in self.domdict.keys():
  123. if self.domdict[i].slow_memset_react and \
  124. self.domdict[i].memory_actual <= self.domdict[i].last_target + self.XEN_FREE_MEM_LEFT/4:
  125. dom_name = self.xs.read('', '/local/domain/%s/name' % str(i))
  126. if dom_name is not None:
  127. # TODO: report it somewhere, qubesd or elsewhere
  128. pass
  129. self.domdict[i].slow_memset_react = False
  130. if self.domdict[i].no_progress and \
  131. self.domdict[i].memory_actual <= self.domdict[i].last_target + self.XEN_FREE_MEM_LEFT/4:
  132. dom_name = self.xs.read('', '/local/domain/%s/name' % str(i))
  133. if dom_name is not None:
  134. # TODO: report it somewhere, qubesd or elsewhere
  135. pass
  136. self.domdict[i].no_progress = False
  137. #the below works (and is fast), but then 'xm list' shows unchanged memory value
  138. def mem_set(self, id, val):
  139. self.log.info('mem-set domain {} to {}'.format(id, val))
  140. self.domdict[id].last_target = val
  141. #can happen in the middle of domain shutdown
  142. #apparently xc.lowlevel throws exceptions too
  143. try:
  144. self.xc.domain_setmaxmem(int(id), int(val/1024) + 1024) # LIBXL_MAXMEM_CONSTANT=1024
  145. self.xc.domain_set_target_mem(int(id), int(val/1024))
  146. except:
  147. pass
  148. self.xs.write('', '/local/domain/' + id + '/memory/target', str(int(val/1024)))
  149. # this is called at the end of ballooning, when we have Xen free mem already
  150. # make sure that past mem_set will not decrease Xen free mem
  151. def inhibit_balloon_up(self):
  152. self.log.debug('inhibit_balloon_up()')
  153. for i in self.domdict.keys():
  154. dom = self.domdict[i]
  155. if dom.memory_actual is not None and dom.memory_actual + 200*1024 < dom.last_target:
  156. self.log.info(
  157. 'Preventing balloon up to {}'.format(dom.last_target))
  158. self.mem_set(i, dom.memory_actual)
  159. #perform memory ballooning, across all domains, to add "memsize" to Xen free memory
  160. def do_balloon(self, memsize):
  161. self.log.info('do_balloon(memsize={!r})'.format(memsize))
  162. CHECK_PERIOD_S = 3
  163. CHECK_MB_S = 100
  164. niter = 0
  165. prev_memory_actual = None
  166. for i in self.domdict.keys():
  167. self.domdict[i].no_progress = False
  168. #: number of loop iterations for CHECK_PERIOD_S seconds
  169. check_period = max(1, int((CHECK_PERIOD_S + 0.0) / self.BALOON_DELAY))
  170. #: number of free memory bytes expected to get during CHECK_PERIOD_S
  171. #: seconds
  172. check_delta = CHECK_PERIOD_S * CHECK_MB_S * 1024 * 1024
  173. #: helper array for holding free memory size, CHECK_PERIOD_S seconds
  174. #: ago, at every loop iteration
  175. xenfree_ring = [0] * check_period
  176. while True:
  177. self.log.debug('niter={:2d}'.format(niter))
  178. self.refresh_memactual()
  179. xenfree = self.get_free_xen_memory()
  180. self.log.info('xenfree={!r}'.format(xenfree))
  181. if xenfree >= memsize + self.XEN_FREE_MEM_MIN:
  182. self.inhibit_balloon_up()
  183. return True
  184. # fail the request if over past CHECK_PERIOD_S seconds,
  185. # we got less than CHECK_MB_S MB/s on average
  186. ring_slot = niter % check_period
  187. if niter >= check_period and xenfree < xenfree_ring[ring_slot] + check_delta:
  188. return False
  189. xenfree_ring[ring_slot] = xenfree
  190. if prev_memory_actual is not None:
  191. for i in prev_memory_actual.keys():
  192. if prev_memory_actual[i] == self.domdict[i].memory_actual:
  193. #domain not responding to memset requests, remove it from donors
  194. self.domdict[i].no_progress = True
  195. self.log.info('domain {} stuck at {}'.format(i, self.domdict[i].memory_actual))
  196. memset_reqs = qubes.qmemman.algo.balloon(memsize + self.XEN_FREE_MEM_LEFT - xenfree, self.domdict)
  197. self.log.info('memset_reqs={!r}'.format(memset_reqs))
  198. if len(memset_reqs) == 0:
  199. return False
  200. prev_memory_actual = {}
  201. for i in memset_reqs:
  202. dom, mem = i
  203. self.mem_set(dom, mem)
  204. prev_memory_actual[dom] = self.domdict[dom].memory_actual
  205. self.log.debug('sleeping for {} s'.format(self.BALOON_DELAY))
  206. time.sleep(self.BALOON_DELAY)
  207. niter = niter + 1
  208. def refresh_meminfo(self, domid, untrusted_meminfo_key):
  209. self.log.debug(
  210. 'refresh_meminfo(domid={}, untrusted_meminfo_key={!r})'.format(
  211. domid, untrusted_meminfo_key))
  212. qubes.qmemman.algo.refresh_meminfo_for_domain(
  213. self.domdict[domid], untrusted_meminfo_key)
  214. self.do_balance()
  215. #is the computed balance request big enough ?
  216. #so that we do not trash with small adjustments
  217. def is_balance_req_significant(self, memset_reqs, xenfree):
  218. self.log.debug(
  219. 'is_balance_req_significant(memset_reqs={}, xenfree={})'.format(
  220. memset_reqs, xenfree))
  221. total_memory_transfer = 0
  222. MIN_TOTAL_MEMORY_TRANSFER = 150*1024*1024
  223. MIN_MEM_CHANGE_WHEN_UNDER_PREF = 15*1024*1024
  224. # If xenfree to low, return immediately
  225. if self.XEN_FREE_MEM_LEFT - xenfree > MIN_MEM_CHANGE_WHEN_UNDER_PREF:
  226. self.log.debug('xenfree is too low, returning')
  227. return True
  228. for rq in memset_reqs:
  229. dom, mem = rq
  230. last_target = self.domdict[dom].last_target
  231. memory_change = mem - last_target
  232. total_memory_transfer += abs(memory_change)
  233. pref = qubes.qmemman.algo.prefmem(self.domdict[dom])
  234. if last_target > 0 and last_target < pref and memory_change > MIN_MEM_CHANGE_WHEN_UNDER_PREF:
  235. self.log.info(
  236. 'dom {} is below pref, allowing balance'.format(dom))
  237. return True
  238. ret = total_memory_transfer + abs(xenfree - self.XEN_FREE_MEM_LEFT) > MIN_TOTAL_MEMORY_TRANSFER
  239. self.log.debug('is_balance_req_significant return {}'.format(ret))
  240. return ret
  241. def print_stats(self, xenfree, memset_reqs):
  242. for i in self.domdict.keys():
  243. if self.domdict[i].mem_used is not None:
  244. self.log.info('stat: dom {!r} act={} pref={}'.format(i,
  245. self.domdict[i].memory_actual,
  246. qubes.qmemman.algo.prefmem(self.domdict[i])))
  247. self.log.info('stat: xenfree={} memset_reqs={}'.format(xenfree, memset_reqs))
  248. def do_balance(self):
  249. self.log.debug('do_balance()')
  250. if os.path.isfile('/var/run/qubes/do-not-membalance'):
  251. self.log.debug('do-not-membalance file preset, returning')
  252. return
  253. self.refresh_memactual()
  254. self.clear_outdated_error_markers()
  255. xenfree = self.get_free_xen_memory()
  256. memset_reqs = qubes.qmemman.algo.balance(xenfree - self.XEN_FREE_MEM_LEFT, self.domdict)
  257. if not self.is_balance_req_significant(memset_reqs, xenfree):
  258. return
  259. self.print_stats(xenfree, memset_reqs)
  260. prev_memactual = {}
  261. for i in self.domdict.keys():
  262. prev_memactual[i] = self.domdict[i].memory_actual
  263. for rq in memset_reqs:
  264. dom, mem = rq
  265. # Force to always have at least 0.9*self.XEN_FREE_MEM_LEFT (some
  266. # margin for rounding errors). Before giving memory to
  267. # domain, ensure that others have gived it back.
  268. # If not - wait a little.
  269. ntries = 5
  270. while self.get_free_xen_memory() - (mem - self.domdict[dom].memory_actual) < 0.9*self.XEN_FREE_MEM_LEFT:
  271. self.log.debug('do_balance dom={!r} sleeping ntries={}'.format(
  272. dom, ntries))
  273. time.sleep(self.BALOON_DELAY)
  274. self.refresh_memactual()
  275. ntries -= 1
  276. if ntries <= 0:
  277. # Waiting haven't helped; Find which domain get stuck and
  278. # abort balance (after distributing what we have)
  279. for rq2 in memset_reqs:
  280. dom2, mem2 = rq2
  281. if dom2 == dom:
  282. # All donors have been procesed
  283. break
  284. # allow some small margin
  285. if self.domdict[dom2].memory_actual > self.domdict[dom2].last_target + self.XEN_FREE_MEM_LEFT/4:
  286. # VM didn't react to memory request at all, remove from donors
  287. if prev_memactual[dom2] == self.domdict[dom2].memory_actual:
  288. self.log.warning(
  289. 'dom {!r} didnt react to memory request'
  290. ' (holds {}, requested balloon down to {})'
  291. .format(dom2,
  292. self.domdict[dom2].memory_actual,
  293. mem2))
  294. self.domdict[dom2].no_progress = True
  295. dom_name = self.xs.read('', '/local/domain/%s/name' % str(dom2))
  296. if dom_name is not None:
  297. # TODO: report it somewhere, qubesd or elsewhere
  298. pass
  299. else:
  300. self.log.warning('dom {!r} still hold more'
  301. ' memory than have assigned ({} > {})'
  302. .format(dom2,
  303. self.domdict[dom2].memory_actual,
  304. mem2))
  305. self.domdict[dom2].slow_memset_react = True
  306. dom_name = self.xs.read('', '/local/domain/%s/name' % str(dom2))
  307. if dom_name is not None:
  308. # TODO: report it somewhere, qubesd or elsewhere
  309. pass
  310. self.mem_set(dom, self.get_free_xen_memory() + self.domdict[dom].memory_actual - self.XEN_FREE_MEM_LEFT)
  311. return
  312. self.mem_set(dom, mem)
  313. # for i in self.domdict.keys():
  314. # print 'domain ', i, ' meminfo=', self.domdict[i].mem_used, 'actual mem', self.domdict[i].memory_actual
  315. # print 'domain ', i, 'actual mem', self.domdict[i].memory_actual
  316. # print 'xen free mem', self.get_free_xen_memory()