__init__.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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 os
  27. import string
  28. import time
  29. import xen.lowlevel.xc
  30. import xen.lowlevel.xs
  31. import qubes
  32. import qubes.qmemman.algo
  33. no_progress_msg="VM refused to give back requested memory"
  34. slow_memset_react_msg="VM didn't give back all requested memory"
  35. class DomainState:
  36. def __init__(self, id):
  37. self.meminfo = None #dictionary of memory info read from client
  38. self.memory_actual = None #the current memory size
  39. self.memory_maximum = None #the maximum memory size
  40. self.mem_used = None #used memory, computed based on meminfo
  41. self.id = id #domain id
  42. self.last_target = 0 #the last memset target
  43. self.no_progress = False #no react to memset
  44. self.slow_memset_react = False #slow react to memset (after few tries still above target)
  45. class SystemState(object):
  46. def __init__(self):
  47. self.log = logging.getLogger('qmemman.systemstate')
  48. self.log.debug('SystemState()')
  49. self.domdict = {}
  50. self.xc = xen.lowlevel.xc.xc()
  51. self.xs = xen.lowlevel.xs.xs()
  52. self.BALOON_DELAY = 0.1
  53. self.XEN_FREE_MEM_LEFT = 50*1024*1024
  54. self.XEN_FREE_MEM_MIN = 25*1024*1024
  55. self.ALL_PHYS_MEM = self.xc.physinfo()['total_memory']*1024
  56. def add_domain(self, id):
  57. self.log.debug('add_domain(id={!r})'.format(id))
  58. self.domdict[id] = DomainState(id)
  59. def del_domain(self, id):
  60. self.log.debug('del_domain(id={!r})'.format(id))
  61. self.domdict.pop(id)
  62. def get_free_xen_memory(self):
  63. return self.xc.physinfo()['free_memory']*1024
  64. # hosts = self.xend_session.session.xenapi.host.get_all()
  65. # host_record = self.xend_session.session.xenapi.host.get_record(hosts[0])
  66. # host_metrics_record = self.xend_session.session.xenapi.host_metrics.get_record(host_record["metrics"])
  67. # ret = host_metrics_record["memory_free"]
  68. # return long(ret)
  69. #refresh information on memory assigned to all domains
  70. def refresh_memactual(self):
  71. for domain in self.xc.domain_getinfo():
  72. id = str(domain['domid'])
  73. if self.domdict.has_key(id):
  74. self.domdict[id].memory_actual = domain['mem_kb']*1024
  75. self.domdict[id].memory_maximum = self.xs.read('', '/local/domain/%s/memory/static-max' % str(id))
  76. if self.domdict[id].memory_maximum:
  77. self.domdict[id].memory_maximum = int(self.domdict[id].memory_maximum)*1024
  78. else:
  79. self.domdict[id].memory_maximum = self.ALL_PHYS_MEM
  80. # the previous line used to be
  81. # self.domdict[id].memory_maximum = domain['maxmem_kb']*1024
  82. # but domain['maxmem_kb'] changes in self.mem_set as well, and this results in
  83. # the memory never increasing
  84. # in fact, the only possible case of nonexisting memory/static-max is dom0
  85. # see #307
  86. def clear_outdated_error_markers(self):
  87. # Clear outdated errors
  88. for i in self.domdict.keys():
  89. if self.domdict[i].slow_memset_react and \
  90. self.domdict[i].memory_actual <= self.domdict[i].last_target + self.XEN_FREE_MEM_LEFT/4:
  91. dom_name = self.xs.read('', '/local/domain/%s/name' % str(i))
  92. if dom_name is not None:
  93. try:
  94. qubes.Qubes()[str(dom_name)].fire_event(
  95. 'status:no-error', 'no-error',
  96. slow_memset_react_msg)
  97. except LookupError:
  98. pass
  99. self.domdict[i].slow_memset_react = False
  100. if self.domdict[i].no_progress and \
  101. self.domdict[i].memory_actual <= self.domdict[i].last_target + self.XEN_FREE_MEM_LEFT/4:
  102. dom_name = self.xs.read('', '/local/domain/%s/name' % str(i))
  103. if dom_name is not None:
  104. try:
  105. qubes.Qubes()[str(dom_name)].fire_event(
  106. 'status:no-error', 'no-error',
  107. no_progress_msg)
  108. except LookupError:
  109. pass
  110. self.domdict[i].no_progress = False
  111. #the below works (and is fast), but then 'xm list' shows unchanged memory value
  112. def mem_set(self, id, val):
  113. self.log.info('mem-set domain {} to {}'.format(id, val))
  114. self.domdict[id].last_target = val
  115. #can happen in the middle of domain shutdown
  116. #apparently xc.lowlevel throws exceptions too
  117. try:
  118. self.xc.domain_setmaxmem(int(id), int(val/1024) + 1024) # LIBXL_MAXMEM_CONSTANT=1024
  119. self.xc.domain_set_target_mem(int(id), int(val/1024))
  120. except:
  121. pass
  122. self.xs.write('', '/local/domain/' + id + '/memory/target', str(int(val/1024)))
  123. # this is called at the end of ballooning, when we have Xen free mem already
  124. # make sure that past mem_set will not decrease Xen free mem
  125. def inhibit_balloon_up(self):
  126. self.log.debug('inhibit_balloon_up()')
  127. for i in self.domdict.keys():
  128. dom = self.domdict[i]
  129. if dom.memory_actual is not None and dom.memory_actual + 200*1024 < dom.last_target:
  130. self.log.info(
  131. 'Preventing balloon up to {}'.format(dom.last_target))
  132. self.mem_set(i, dom.memory_actual)
  133. #perform memory ballooning, across all domains, to add "memsize" to Xen free memory
  134. def do_balloon(self, memsize):
  135. self.log.info('do_balloon(memsize={!r})'.format(memsize))
  136. MAX_TRIES = 20
  137. niter = 0
  138. prev_memory_actual = None
  139. for i in self.domdict.keys():
  140. self.domdict[i].no_progress = False
  141. while True:
  142. self.log.debug('niter={:2d}/{:2d}'.format(niter, MAX_TRIES))
  143. self.refresh_memactual()
  144. xenfree = self.get_free_xen_memory()
  145. self.log.info('xenfree={!r}'.format(xenfree))
  146. if xenfree >= memsize + self.XEN_FREE_MEM_MIN:
  147. self.inhibit_balloon_up()
  148. return True
  149. if prev_memory_actual is not None:
  150. for i in prev_memory_actual.keys():
  151. if prev_memory_actual[i] == self.domdict[i].memory_actual:
  152. #domain not responding to memset requests, remove it from donors
  153. self.domdict[i].no_progress = True
  154. self.log.info('domain {} stuck at {}'.format(i, self.domdict[i].memory_actual))
  155. memset_reqs = qubes.qmemman.algo.balloon(memsize + self.XEN_FREE_MEM_LEFT - xenfree, self.domdict)
  156. self.log.info('memset_reqs={!r}'.format(memset_reqs))
  157. if niter > MAX_TRIES or len(memset_reqs) == 0:
  158. return False
  159. prev_memory_actual = {}
  160. for i in memset_reqs:
  161. dom, mem = i
  162. self.mem_set(dom, mem)
  163. prev_memory_actual[dom] = self.domdict[dom].memory_actual
  164. self.log.debug('sleeping for {} s'.format(self.BALOON_DELAY))
  165. time.sleep(self.BALOON_DELAY)
  166. niter = niter + 1
  167. def refresh_meminfo(self, domid, untrusted_meminfo_key):
  168. self.log.debug(
  169. 'refresh_meminfo(domid={}, untrusted_meminfo_key={!r})'.format(
  170. domid, untrusted_meminfo_key))
  171. qubes.qmemman.algo.refresh_meminfo_for_domain(
  172. self.domdict[domid], untrusted_meminfo_key)
  173. self.do_balance()
  174. #is the computed balance request big enough ?
  175. #so that we do not trash with small adjustments
  176. def is_balance_req_significant(self, memset_reqs, xenfree):
  177. self.log.debug(
  178. 'is_balance_req_significant(memset_reqs={}, xenfree={})'.format(
  179. memset_reqs, xenfree))
  180. total_memory_transfer = 0
  181. MIN_TOTAL_MEMORY_TRANSFER = 150*1024*1024
  182. MIN_MEM_CHANGE_WHEN_UNDER_PREF = 15*1024*1024
  183. # If xenfree to low, return immediately
  184. if self.XEN_FREE_MEM_LEFT - xenfree > MIN_MEM_CHANGE_WHEN_UNDER_PREF:
  185. self.log.debug('xenfree is too low, returning')
  186. return True
  187. for rq in memset_reqs:
  188. dom, mem = rq
  189. last_target = self.domdict[dom].last_target
  190. memory_change = mem - last_target
  191. total_memory_transfer += abs(memory_change)
  192. pref = qubes.qmemman.algo.prefmem(self.domdict[dom])
  193. if last_target > 0 and last_target < pref and memory_change > MIN_MEM_CHANGE_WHEN_UNDER_PREF:
  194. self.log.info(
  195. 'dom {} is below pref, allowing balance'.format(dom))
  196. return True
  197. ret = total_memory_transfer + abs(xenfree - self.XEN_FREE_MEM_LEFT) > MIN_TOTAL_MEMORY_TRANSFER
  198. self.log.debug('is_balance_req_significant return {}'.format(ret))
  199. return ret
  200. def print_stats(self, xenfree, memset_reqs):
  201. for i in self.domdict.keys():
  202. if self.domdict[i].meminfo is not None:
  203. self.log.info('stat: dom {!r} act={} pref={}'.format(i,
  204. self.domdict[i].memory_actual,
  205. qubes.qmemman.algo.prefmem(self.domdict[i])))
  206. self.log.info('stat: xenfree={} memset_reqs={}'.format(xenfree, memset_reqs))
  207. def do_balance(self):
  208. self.log.debug('do_balance()')
  209. if os.path.isfile('/var/run/qubes/do-not-membalance'):
  210. self.log.debug('do-not-membalance file preset, returning')
  211. return
  212. self.refresh_memactual()
  213. self.clear_outdated_error_markers()
  214. xenfree = self.get_free_xen_memory()
  215. memset_reqs = qubes.qmemman.algo.balance(xenfree - self.XEN_FREE_MEM_LEFT, self.domdict)
  216. if not self.is_balance_req_significant(memset_reqs, xenfree):
  217. return
  218. self.print_stats(xenfree, memset_reqs)
  219. prev_memactual = {}
  220. for i in self.domdict.keys():
  221. prev_memactual[i] = self.domdict[i].memory_actual
  222. for rq in memset_reqs:
  223. dom, mem = rq
  224. # Force to always have at least 0.9*self.XEN_FREE_MEM_LEFT (some
  225. # margin for rounding errors). Before giving memory to
  226. # domain, ensure that others have gived it back.
  227. # If not - wait a little.
  228. ntries = 5
  229. while self.get_free_xen_memory() - (mem - self.domdict[dom].memory_actual) < 0.9*self.XEN_FREE_MEM_LEFT:
  230. self.log.debug('do_balance dom={!r} sleeping ntries={}'.format(
  231. dom, ntries))
  232. time.sleep(self.BALOON_DELAY)
  233. ntries -= 1
  234. if ntries <= 0:
  235. # Waiting haven't helped; Find which domain get stuck and
  236. # abort balance (after distributing what we have)
  237. self.refresh_memactual()
  238. for rq2 in memset_reqs:
  239. dom2, mem2 = rq2
  240. if dom2 == dom:
  241. # All donors have been procesed
  242. break
  243. # allow some small margin
  244. if self.domdict[dom2].memory_actual > self.domdict[dom2].last_target + self.XEN_FREE_MEM_LEFT/4:
  245. # VM didn't react to memory request at all, remove from donors
  246. if prev_memactual[dom2] == self.domdict[dom2].memory_actual:
  247. self.log.warning(
  248. 'dom {!r} didnt react to memory request'
  249. ' (holds {}, requested balloon down to {})'
  250. .format(dom2,
  251. self.domdict[dom2].memory_actual,
  252. mem2))
  253. self.domdict[dom2].no_progress = True
  254. dom_name = self.xs.read('', '/local/domain/%s/name' % str(dom2))
  255. if dom_name is not None:
  256. try:
  257. qubes.Qubes()[str(dom_name)].fire_event(
  258. 'status:error', 'error',
  259. no_progress_msg)
  260. except LookupError:
  261. pass
  262. else:
  263. self.log.warning('dom {!r} still hold more'
  264. ' memory than have assigned ({} > {})'
  265. .format(dom2,
  266. self.domdict[dom2].memory_actual,
  267. mem2))
  268. self.domdict[dom2].slow_memset_react = True
  269. dom_name = self.xs.read('', '/local/domain/%s/name' % str(dom2))
  270. if dom_name is not None:
  271. try:
  272. qubes.Qubes()[str(dom_name)].fire_event(
  273. 'status:error', 'error',
  274. slow_memset_react_msg)
  275. except LookupError:
  276. pass
  277. self.mem_set(dom, self.get_free_xen_memory() + self.domdict[dom].memory_actual - self.XEN_FREE_MEM_LEFT)
  278. return
  279. self.mem_set(dom, mem)
  280. # for i in self.domdict.keys():
  281. # print 'domain ', i, ' meminfo=', self.domdict[i].meminfo, 'actual mem', self.domdict[i].memory_actual
  282. # print 'domain ', i, 'actual mem', self.domdict[i].memory_actual
  283. # print 'xen free mem', self.get_free_xen_memory()