qmemman.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. #!/usr/bin/python2
  2. # -*- coding: utf-8 -*-
  3. #
  4. # The Qubes OS Project, http://www.qubes-os.org
  5. #
  6. # Copyright (C) 2010 Rafal Wojtczuk <rafal@invisiblethingslab.com>
  7. # Copyright (C) 2013 Marek Marczykowski <marmarek@invisiblethingslab.com>
  8. #
  9. # This program is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU General Public License
  11. # as published by the Free Software Foundation; either version 2
  12. # of the License, or (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License
  20. # along with this program; if not, write to the Free Software
  21. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  22. #
  23. #
  24. import xen.lowlevel.xc
  25. import xen.lowlevel.xs
  26. import string
  27. import time
  28. import qmemman_algo
  29. import os
  30. from notify import notify_error_qubes_manager, clear_error_qubes_manager
  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.meminfo = None #dictionary of memory info read from client
  36. self.memory_actual = None #the current memory size
  37. self.memory_maximum = None #the maximum memory size
  38. self.mem_used = None #used memory, computed based on meminfo
  39. self.id = id #domain id
  40. self.last_target = 0 #the last memset target
  41. self.no_progress = False #no react to memset
  42. self.slow_memset_react = False #slow react to memset (after few tries still above target)
  43. class SystemState:
  44. def __init__(self):
  45. self.domdict = {}
  46. self.xc = xen.lowlevel.xc.xc()
  47. self.xs = xen.lowlevel.xs.xs()
  48. self.BALOON_DELAY = 0.1
  49. self.XEN_FREE_MEM_LEFT = 50*1024*1024
  50. self.XEN_FREE_MEM_MIN = 25*1024*1024
  51. self.ALL_PHYS_MEM = self.xc.physinfo()['total_memory']*1024
  52. def add_domain(self, id):
  53. self.domdict[id] = DomainState(id)
  54. def del_domain(self, id):
  55. self.domdict.pop(id)
  56. def get_free_xen_memory(self):
  57. return self.xc.physinfo()['free_memory']*1024
  58. # hosts = self.xend_session.session.xenapi.host.get_all()
  59. # host_record = self.xend_session.session.xenapi.host.get_record(hosts[0])
  60. # host_metrics_record = self.xend_session.session.xenapi.host_metrics.get_record(host_record["metrics"])
  61. # ret = host_metrics_record["memory_free"]
  62. # return long(ret)
  63. #refresh information on memory assigned to all domains
  64. def refresh_memactual(self):
  65. for domain in self.xc.domain_getinfo():
  66. id = str(domain['domid'])
  67. if self.domdict.has_key(id):
  68. self.domdict[id].memory_actual = domain['mem_kb']*1024
  69. self.domdict[id].memory_maximum = self.xs.read('', '/local/domain/%s/memory/static-max' % str(id))
  70. if self.domdict[id].memory_maximum:
  71. self.domdict[id].memory_maximum = int(self.domdict[id].memory_maximum)*1024
  72. else:
  73. self.domdict[id].memory_maximum = self.ALL_PHYS_MEM
  74. # the previous line used to be
  75. # self.domdict[id].memory_maximum = domain['maxmem_kb']*1024
  76. # but domain['maxmem_kb'] changes in self.mem_set as well, and this results in
  77. # the memory never increasing
  78. # in fact, the only possible case of nonexisting memory/static-max is dom0
  79. # see #307
  80. def clear_outdated_error_markers(self):
  81. # Clear outdated errors
  82. for i in self.domdict.keys():
  83. if self.domdict[i].slow_memset_react and \
  84. self.domdict[i].memory_actual <= self.domdict[i].last_target + self.XEN_FREE_MEM_LEFT/4:
  85. dom_name = self.xs.read('', '/local/domain/%s/name' % str(i))
  86. if dom_name is not None:
  87. clear_error_qubes_manager(dom_name, slow_memset_react_msg)
  88. self.domdict[i].slow_memset_react = False
  89. if self.domdict[i].no_progress 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. clear_error_qubes_manager(dom_name, no_progress_msg)
  94. self.domdict[i].no_progress = False
  95. #the below works (and is fast), but then 'xm list' shows unchanged memory value
  96. def mem_set(self, id, val):
  97. print 'mem-set domain', id, 'to', val
  98. self.domdict[id].last_target = val
  99. #can happen in the middle of domain shutdown
  100. #apparently xc.lowlevel throws exceptions too
  101. try:
  102. self.xc.domain_setmaxmem(int(id), int(val/1024) + 1024) # LIBXL_MAXMEM_CONSTANT=1024
  103. self.xc.domain_set_target_mem(int(id), int(val/1024))
  104. except:
  105. pass
  106. self.xs.write('', '/local/domain/' + id + '/memory/target', str(int(val/1024)))
  107. # this is called at the end of ballooning, when we have Xen free mem already
  108. # make sure that past mem_set will not decrease Xen free mem
  109. def inhibit_balloon_up(self):
  110. for i in self.domdict.keys():
  111. dom = self.domdict[i]
  112. if dom.memory_actual is not None and dom.memory_actual + 200*1024 < dom.last_target:
  113. print "Preventing balloon up to", dom.last_target
  114. self.mem_set(i, dom.memory_actual)
  115. #perform memory ballooning, across all domains, to add "memsize" to Xen free memory
  116. def do_balloon(self, memsize):
  117. MAX_TRIES = 20
  118. niter = 0
  119. prev_memory_actual = None
  120. for i in self.domdict.keys():
  121. self.domdict[i].no_progress = False
  122. print "do_balloon start"
  123. while True:
  124. self.refresh_memactual()
  125. xenfree = self.get_free_xen_memory()
  126. print 'got xenfree=', xenfree
  127. if xenfree >= memsize + self.XEN_FREE_MEM_MIN:
  128. self.inhibit_balloon_up()
  129. return True
  130. if prev_memory_actual is not None:
  131. for i in prev_memory_actual.keys():
  132. if prev_memory_actual[i] == self.domdict[i].memory_actual:
  133. #domain not responding to memset requests, remove it from donors
  134. self.domdict[i].no_progress = True
  135. print 'domain', i, 'stuck at', self.domdict[i].memory_actual
  136. memset_reqs = qmemman_algo.balloon(memsize + self.XEN_FREE_MEM_LEFT - xenfree, self.domdict)
  137. print 'requests:', memset_reqs
  138. if niter > MAX_TRIES or len(memset_reqs) == 0:
  139. return False
  140. prev_memory_actual = {}
  141. for i in memset_reqs:
  142. dom, mem = i
  143. self.mem_set(dom, mem)
  144. prev_memory_actual[dom] = self.domdict[dom].memory_actual
  145. time.sleep(self.BALOON_DELAY)
  146. niter = niter + 1
  147. def refresh_meminfo(self, domid, untrusted_meminfo_key):
  148. qmemman_algo.refresh_meminfo_for_domain(self.domdict[domid], untrusted_meminfo_key)
  149. self.do_balance()
  150. #is the computed balance request big enough ?
  151. #so that we do not trash with small adjustments
  152. def is_balance_req_significant(self, memset_reqs, xenfree):
  153. total_memory_transfer = 0
  154. MIN_TOTAL_MEMORY_TRANSFER = 150*1024*1024
  155. MIN_MEM_CHANGE_WHEN_UNDER_PREF = 15*1024*1024
  156. # If xenfree to low, return immediately
  157. if self.XEN_FREE_MEM_LEFT - xenfree > MIN_MEM_CHANGE_WHEN_UNDER_PREF:
  158. return True
  159. for rq in memset_reqs:
  160. dom, mem = rq
  161. last_target = self.domdict[dom].last_target
  162. memory_change = mem - last_target
  163. total_memory_transfer += abs(memory_change)
  164. pref = qmemman_algo.prefmem(self.domdict[dom])
  165. if last_target > 0 and last_target < pref and memory_change > MIN_MEM_CHANGE_WHEN_UNDER_PREF:
  166. print 'dom', dom, 'is below pref, allowing balance'
  167. return True
  168. return total_memory_transfer + abs(xenfree - self.XEN_FREE_MEM_LEFT) > MIN_TOTAL_MEMORY_TRANSFER
  169. def print_stats(self, xenfree, memset_reqs):
  170. for i in self.domdict.keys():
  171. if self.domdict[i].meminfo is not None:
  172. print 'dom' , i, 'act/pref', self.domdict[i].memory_actual, qmemman_algo.prefmem(self.domdict[i])
  173. print 'xenfree=', xenfree, 'balance req:', memset_reqs
  174. def do_balance(self):
  175. if os.path.isfile('/var/run/qubes/do-not-membalance'):
  176. return
  177. self.refresh_memactual()
  178. self.clear_outdated_error_markers()
  179. xenfree = self.get_free_xen_memory()
  180. memset_reqs = qmemman_algo.balance(xenfree - self.XEN_FREE_MEM_LEFT, self.domdict)
  181. if not self.is_balance_req_significant(memset_reqs, xenfree):
  182. return
  183. self.print_stats(xenfree, memset_reqs)
  184. prev_memactual = {}
  185. for i in self.domdict.keys():
  186. prev_memactual[i] = self.domdict[i].memory_actual
  187. for rq in memset_reqs:
  188. dom, mem = rq
  189. # Force to always have at least 0.9*self.XEN_FREE_MEM_LEFT (some
  190. # margin for rounding errors). Before giving memory to
  191. # domain, ensure that others have gived it back.
  192. # If not - wait a little.
  193. ntries = 5
  194. while self.get_free_xen_memory() - (mem - self.domdict[dom].memory_actual) < 0.9*self.XEN_FREE_MEM_LEFT:
  195. time.sleep(self.BALOON_DELAY)
  196. ntries -= 1
  197. if ntries <= 0:
  198. # Waiting haven't helped; Find which domain get stuck and
  199. # abort balance (after distributing what we have)
  200. self.refresh_memactual()
  201. for rq2 in memset_reqs:
  202. dom2, mem2 = rq2
  203. if dom2 == dom:
  204. # All donors have been procesed
  205. break
  206. # allow some small margin
  207. if self.domdict[dom2].memory_actual > self.domdict[dom2].last_target + self.XEN_FREE_MEM_LEFT/4:
  208. # VM didn't react to memory request at all, remove from donors
  209. if prev_memactual[dom2] == self.domdict[dom2].memory_actual:
  210. print 'dom %s didnt react to memory request (holds %d, requested balloon down to %d)' % (dom2, self.domdict[dom2].memory_actual, mem2)
  211. self.domdict[dom2].no_progress = True
  212. dom_name = self.xs.read('', '/local/domain/%s/name' % str(dom2))
  213. if dom_name is not None:
  214. notify_error_qubes_manager(str(dom_name), no_progress_msg)
  215. else:
  216. print 'dom %s still hold more memory than have assigned (%d > %d)' % (dom2, self.domdict[dom2].memory_actual, mem2)
  217. self.domdict[dom2].slow_memset_react = True
  218. dom_name = self.xs.read('', '/local/domain/%s/name' % str(dom2))
  219. if dom_name is not None:
  220. notify_error_qubes_manager(str(dom_name), slow_memset_react_msg)
  221. self.mem_set(dom, self.get_free_xen_memory() + self.domdict[dom].memory_actual - self.XEN_FREE_MEM_LEFT)
  222. return
  223. self.mem_set(dom, mem)
  224. # for i in self.domdict.keys():
  225. # print 'domain ', i, ' meminfo=', self.domdict[i].meminfo, 'actual mem', self.domdict[i].memory_actual
  226. # print 'domain ', i, 'actual mem', self.domdict[i].memory_actual
  227. # print 'xen free mem', self.get_free_xen_memory()