qmemman.py 11 KB

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