__init__.py 17 KB

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