qmemman_algo.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. import string
  2. # This are only defaults - can be overriden by QMemmanServer with values from
  3. # config file
  4. CACHE_FACTOR = 1.3
  5. MIN_PREFMEM = 200*1024*1024
  6. DOM0_MEM_BOOST = 350*1024*1024
  7. #untrusted meminfo size is taken from xenstore key, thus its size is limited
  8. #so splits do not require excessive memory
  9. def parse_meminfo(untrusted_meminfo):
  10. untrusted_dict = {}
  11. #split meminfo contents into lines
  12. untrusted_lines = string.split(untrusted_meminfo,"\n")
  13. for untrusted_lines_iterator in untrusted_lines:
  14. #split a single meminfo line into words
  15. untrusted_words = string.split(untrusted_lines_iterator)
  16. if len(untrusted_words) >= 2:
  17. untrusted_dict[string.rstrip(untrusted_words[0], ":")] = untrusted_words[1]
  18. return untrusted_dict
  19. def is_meminfo_suspicious(domain, untrusted_meminfo):
  20. ret = False
  21. #check whether the required keys exist and are not negative
  22. try:
  23. for i in ('MemTotal', 'MemFree', 'Buffers', 'Cached', 'SwapTotal', 'SwapFree'):
  24. val = int(untrusted_meminfo[i])*1024
  25. if (val < 0):
  26. ret = True
  27. untrusted_meminfo[i] = val
  28. except:
  29. ret = True
  30. if not ret and untrusted_meminfo['SwapTotal'] < untrusted_meminfo['SwapFree']:
  31. ret = True
  32. if not ret and untrusted_meminfo['MemTotal'] < untrusted_meminfo['MemFree'] + untrusted_meminfo['Cached'] + untrusted_meminfo['Buffers']:
  33. ret = True
  34. #we could also impose some limits on all the above values
  35. #but it has little purpose - all the domain can gain by passing e.g.
  36. #very large SwapTotal is that it will be assigned all free Xen memory
  37. #it can be achieved with legal values, too, and it will not allow to
  38. #starve existing domains, by design
  39. if ret:
  40. print 'suspicious meminfo for domain', domain.id, 'mem actual', domain.memory_actual, untrusted_meminfo
  41. return ret
  42. #called when a domain updates its 'meminfo' xenstore key
  43. def refresh_meminfo_for_domain(domain, untrusted_xenstore_key):
  44. untrusted_meminfo = parse_meminfo(untrusted_xenstore_key)
  45. if untrusted_meminfo is None:
  46. domain.meminfo = None
  47. return
  48. #sanitize start
  49. if is_meminfo_suspicious(domain, untrusted_meminfo):
  50. #sanitize end
  51. domain.meminfo = None
  52. domain.mem_used = None
  53. else:
  54. #sanitized, can assign
  55. domain.meminfo = untrusted_meminfo
  56. domain.mem_used = domain.meminfo['MemTotal'] - domain.meminfo['MemFree'] - domain.meminfo['Cached'] - domain.meminfo['Buffers'] + domain.meminfo['SwapTotal'] - domain.meminfo['SwapFree']
  57. def prefmem(domain):
  58. #dom0 is special, as it must have large cache, for vbds. Thus, give it a special boost
  59. if domain.id == '0':
  60. return min(domain.mem_used*CACHE_FACTOR + 350*1024*1024, domain.memory_maximum)
  61. return max(min(domain.mem_used*CACHE_FACTOR, domain.memory_maximum), MIN_PREFMEM)
  62. def memory_needed(domain):
  63. #do not change
  64. #in balance(), "distribute total_available_memory proportionally to mempref" relies on this exact formula
  65. ret = prefmem(domain) - domain.memory_actual
  66. return ret
  67. #prepare list of (domain, memory_target) pairs that need to be passed
  68. #to "xm memset" equivalent in order to obtain "memsize" of memory
  69. #return empty list when the request cannot be satisfied
  70. def balloon(memsize, domain_dictionary):
  71. REQ_SAFETY_NET_FACTOR = 1.05
  72. donors = list()
  73. request = list()
  74. available = 0
  75. for i in domain_dictionary.keys():
  76. if domain_dictionary[i].meminfo is None:
  77. continue
  78. if domain_dictionary[i].no_progress:
  79. continue
  80. need = memory_needed(domain_dictionary[i])
  81. if need < 0:
  82. print 'balloon: dom' , i, 'has actual memory', domain_dictionary[i].memory_actual
  83. donors.append((i,-need))
  84. available-=need
  85. print 'req=', memsize, 'avail=', available, 'donors', donors
  86. if available<memsize:
  87. return ()
  88. scale = 1.0*memsize/available
  89. for donors_iter in donors:
  90. id, mem = donors_iter
  91. memborrowed = mem*scale*REQ_SAFETY_NET_FACTOR
  92. print 'borrow' , memborrowed, 'from', id
  93. memtarget = int(domain_dictionary[id].memory_actual - memborrowed)
  94. request.append((id, memtarget))
  95. return request
  96. # REQ_SAFETY_NET_FACTOR is a bit greater that 1. So that if the domain yields a bit less than requested, due
  97. # to e.g. rounding errors, we will not get stuck. The surplus will return to the VM during "balance" call.
  98. #redistribute positive "total_available_memory" of memory between domains, proportionally to prefmem
  99. def balance_when_enough_memory(domain_dictionary, xen_free_memory, total_mem_pref, total_available_memory):
  100. print 'balance_when_enough_memory(', xen_free_memory, total_mem_pref, total_available_memory, ')'
  101. target_memory = {}
  102. # memory not assigned because of static max
  103. left_memory = 0
  104. acceptors_count = 0
  105. for i in domain_dictionary.keys():
  106. if domain_dictionary[i].meminfo is None:
  107. continue
  108. if domain_dictionary[i].no_progress:
  109. continue
  110. #distribute total_available_memory proportionally to mempref
  111. scale = 1.0*prefmem(domain_dictionary[i])/total_mem_pref
  112. target_nonint = prefmem(domain_dictionary[i]) + scale*total_available_memory
  113. #prevent rounding errors
  114. target = int(0.999*target_nonint)
  115. #do not try to give more memory than static max
  116. if target > domain_dictionary[i].memory_maximum:
  117. left_memory += target-domain_dictionary[i].memory_maximum
  118. target = domain_dictionary[i].memory_maximum
  119. else:
  120. # count domains which can accept more memory
  121. acceptors_count += 1
  122. target_memory[i] = target
  123. # distribute left memory across all acceptors
  124. while left_memory > 0 and acceptors_count > 0:
  125. print ' left_memory:', left_memory, 'acceptors_count:', acceptors_count
  126. new_left_memory = 0
  127. new_acceptors_count = acceptors_count
  128. for i in target_memory.keys():
  129. target = target_memory[i]
  130. if target < domain_dictionary[i].memory_maximum:
  131. memory_bonus = int(0.999*(left_memory/acceptors_count))
  132. if target+memory_bonus >= domain_dictionary[i].memory_maximum:
  133. new_left_memory += target+memory_bonus - domain_dictionary[i].memory_maximum
  134. target = domain_dictionary[i].memory_maximum
  135. new_acceptors_count -= 1
  136. else:
  137. target += memory_bonus
  138. target_memory[i] = target
  139. left_memory = new_left_memory
  140. acceptors_count = new_acceptors_count
  141. # split target_memory dictionary to donors and acceptors
  142. # this is needed to first get memory from donors and only then give it to acceptors
  143. donors_rq = list()
  144. acceptors_rq = list()
  145. for i in target_memory.keys():
  146. target = target_memory[i]
  147. if (target < domain_dictionary[i].memory_actual):
  148. donors_rq.append((i, target))
  149. else:
  150. acceptors_rq.append((i, target))
  151. # print 'balance(enough): xen_free_memory=', xen_free_memory, 'requests:', donors_rq + acceptors_rq
  152. return donors_rq + acceptors_rq
  153. #when not enough mem to make everyone be above prefmem, make donors be at prefmem, and
  154. #redistribute anything left between acceptors
  155. def balance_when_low_on_memory(domain_dictionary, xen_free_memory, total_mem_pref_acceptors, donors, acceptors):
  156. donors_rq = list()
  157. acceptors_rq = list()
  158. squeezed_mem = xen_free_memory
  159. for i in donors:
  160. avail = -memory_needed(domain_dictionary[i])
  161. if avail < 10*1024*1024:
  162. #probably we have already tried making it exactly at prefmem, give up
  163. continue
  164. squeezed_mem -= avail
  165. donors_rq.append((i, prefmem(domain_dictionary[i])))
  166. #the below can happen if initially xen free memory is below 50M
  167. if squeezed_mem < 0:
  168. return donors_rq
  169. for i in acceptors:
  170. scale = 1.0*prefmem(domain_dictionary[i])/total_mem_pref_acceptors
  171. target_nonint = domain_dictionary[i].memory_actual + scale*squeezed_mem
  172. #do not try to give more memory than static max
  173. target = min(int(0.999*target_nonint), domain_dictionary[i].memory_maximum)
  174. acceptors_rq.append((i, target))
  175. # print 'balance(low): xen_free_memory=', xen_free_memory, 'requests:', donors_rq + acceptors_rq
  176. return donors_rq + acceptors_rq
  177. #redistribute memory across domains
  178. #called when one of domains update its 'meminfo' xenstore key
  179. #return the list of (domain, memory_target) pairs to be passed to
  180. #"xm memset" equivalent
  181. def balance(xen_free_memory, domain_dictionary):
  182. #sum of all memory requirements - in other words, the difference between
  183. #memory required to be added to domains (acceptors) to make them be at their
  184. #preferred memory, and memory that can be taken from domains (donors) that
  185. #can provide memory. So, it can be negative when plenty of memory.
  186. total_memory_needed = 0
  187. #sum of memory preferences of all domains
  188. total_mem_pref = 0
  189. #sum of memory preferences of all domains that require more memory
  190. total_mem_pref_acceptors = 0
  191. donors = list() # domains that can yield memory
  192. acceptors = list() # domains that require more memory
  193. #pass 1: compute the above "total" values
  194. for i in domain_dictionary.keys():
  195. if domain_dictionary[i].meminfo is None:
  196. continue
  197. if domain_dictionary[i].no_progress:
  198. continue
  199. need = memory_needed(domain_dictionary[i])
  200. # print 'domain' , i, 'act/pref', domain_dictionary[i].memory_actual, prefmem(domain_dictionary[i]), 'need=', need
  201. if need < 0 or domain_dictionary[i].memory_actual >= domain_dictionary[i].memory_maximum:
  202. donors.append(i)
  203. else:
  204. acceptors.append(i)
  205. total_mem_pref_acceptors += prefmem(domain_dictionary[i])
  206. total_memory_needed += need
  207. total_mem_pref += prefmem(domain_dictionary[i])
  208. total_available_memory = xen_free_memory - total_memory_needed
  209. if total_available_memory > 0:
  210. return balance_when_enough_memory(domain_dictionary, xen_free_memory, total_mem_pref, total_available_memory)
  211. else:
  212. return balance_when_low_on_memory(domain_dictionary, xen_free_memory, total_mem_pref_acceptors, donors, acceptors)