qmemmand.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. #
  7. # This library is free software; you can redistribute it and/or
  8. # modify it under the terms of the GNU Lesser General Public
  9. # License as published by the Free Software Foundation; either
  10. # version 2.1 of the License, or (at your option) any later version.
  11. #
  12. # This library is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. # Lesser General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public
  18. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  19. #
  20. #
  21. import configparser
  22. import socketserver
  23. import logging
  24. import logging.handlers
  25. import os
  26. import socket
  27. import sys
  28. import threading
  29. import xen.lowlevel.xs
  30. import qubes.qmemman
  31. import qubes.qmemman.algo
  32. import qubes.utils
  33. SOCK_PATH = '/var/run/qubes/qmemman.sock'
  34. system_state = qubes.qmemman.SystemState()
  35. global_lock = threading.Lock()
  36. # If XS_Watcher will
  37. # handle meminfo event before @introduceDomain, it will use
  38. # incomplete domain list for that and may redistribute memory
  39. # allocated to some VM, but not yet used (see #1389).
  40. # To fix that, system_state should be updated (refresh domain
  41. # list) before processing other changes, every time some process requested
  42. # memory for a new VM, before releasing the lock. Then XS_Watcher will check
  43. # this flag before processing other event.
  44. force_refresh_domain_list = False
  45. def only_in_first_list(l1, l2):
  46. ret = []
  47. for i in l1:
  48. if not i in l2:
  49. ret.append(i)
  50. return ret
  51. def get_domain_meminfo_key(domain_id):
  52. return '/local/domain/'+domain_id+'/memory/meminfo'
  53. class WatchType(object):
  54. def __init__(self, fn, param):
  55. self.fn = fn
  56. self.param = param
  57. class XS_Watcher(object):
  58. def __init__(self):
  59. self.log = logging.getLogger('qmemman.daemon.xswatcher')
  60. self.log.debug('XS_Watcher()')
  61. self.handle = xen.lowlevel.xs.xs()
  62. self.handle.watch('@introduceDomain', WatchType(
  63. XS_Watcher.domain_list_changed, False))
  64. self.handle.watch('@releaseDomain', WatchType(
  65. XS_Watcher.domain_list_changed, False))
  66. self.watch_token_dict = {}
  67. def domain_list_changed(self, refresh_only=False):
  68. """
  69. Check if any domain was created/destroyed. If it was, update
  70. appropriate list. Then redistribute memory.
  71. :param refresh_only If True, only refresh domain list, do not
  72. redistribute memory. In this mode, caller must already hold
  73. global_lock.
  74. """
  75. self.log.debug('domain_list_changed(only_refresh={!r})'.format(
  76. refresh_only))
  77. got_lock = False
  78. if not refresh_only:
  79. self.log.debug('acquiring global_lock')
  80. global_lock.acquire()
  81. got_lock = True
  82. self.log.debug('global_lock acquired')
  83. try:
  84. curr = self.handle.ls('', '/local/domain')
  85. if curr is None:
  86. return
  87. # check if domain is really there, it may happen that some empty
  88. # directories are left in xenstore
  89. curr = list(filter(
  90. lambda x:
  91. self.handle.read('',
  92. '/local/domain/{}/domid'.format(x)
  93. ) is not None,
  94. curr
  95. ))
  96. self.log.debug('curr={!r}'.format(curr))
  97. for i in only_in_first_list(curr, self.watch_token_dict.keys()):
  98. # new domain has been created
  99. watch = WatchType(XS_Watcher.meminfo_changed, i)
  100. self.watch_token_dict[i] = watch
  101. self.handle.watch(get_domain_meminfo_key(i), watch)
  102. system_state.add_domain(i)
  103. for i in only_in_first_list(self.watch_token_dict.keys(), curr):
  104. # domain destroyed
  105. self.handle.unwatch(get_domain_meminfo_key(i), self.watch_token_dict[i])
  106. self.watch_token_dict.pop(i)
  107. system_state.del_domain(i)
  108. except:
  109. self.log.exception('Updating domain list failed')
  110. finally:
  111. if got_lock:
  112. global_lock.release()
  113. self.log.debug('global_lock released')
  114. if not refresh_only:
  115. try:
  116. system_state.do_balance()
  117. except:
  118. self.log.exception('do_balance() failed')
  119. def meminfo_changed(self, domain_id):
  120. self.log.debug('meminfo_changed(domain_id={!r})'.format(domain_id))
  121. untrusted_meminfo_key = self.handle.read(
  122. '', get_domain_meminfo_key(domain_id))
  123. if untrusted_meminfo_key == None or untrusted_meminfo_key == b'':
  124. return
  125. self.log.debug('acquiring global_lock')
  126. global_lock.acquire()
  127. self.log.debug('global_lock acquired')
  128. try:
  129. global force_refresh_domain_list
  130. if force_refresh_domain_list:
  131. self.domain_list_changed(refresh_only=True)
  132. force_refresh_domain_list = False
  133. if domain_id not in self.watch_token_dict:
  134. # domain just destroyed
  135. return
  136. system_state.refresh_meminfo(domain_id, untrusted_meminfo_key)
  137. except:
  138. self.log.exception('Updating meminfo for %d failed', domain_id)
  139. finally:
  140. global_lock.release()
  141. self.log.debug('global_lock released')
  142. def watch_loop(self):
  143. self.log.debug('watch_loop()')
  144. while True:
  145. result = self.handle.read_watch()
  146. self.log.debug('watch_loop result={!r}'.format(result))
  147. token = result[1]
  148. token.fn(self, token.param)
  149. class QMemmanReqHandler(socketserver.BaseRequestHandler):
  150. """
  151. The RequestHandler class for our server.
  152. It is instantiated once per connection to the server, and must
  153. override the handle() method to implement communication to the
  154. client.
  155. """
  156. def handle(self):
  157. self.log = logging.getLogger('qmemman.daemon.reqhandler')
  158. got_lock = False
  159. try:
  160. # self.request is the TCP socket connected to the client
  161. while True:
  162. self.data = self.request.recv(1024).strip()
  163. self.log.debug('data={!r}'.format(self.data))
  164. if len(self.data) == 0:
  165. self.log.info('client disconnected, resuming membalance')
  166. if got_lock:
  167. global force_refresh_domain_list
  168. force_refresh_domain_list = True
  169. return
  170. # XXX something is wrong here: return without release?
  171. if got_lock:
  172. self.log.warning('Second request over qmemman.sock?')
  173. return
  174. self.log.debug('acquiring global_lock')
  175. global_lock.acquire()
  176. self.log.debug('global_lock acquired')
  177. got_lock = True
  178. if system_state.do_balloon(int(self.data.decode('ascii'))):
  179. resp = b"OK\n"
  180. else:
  181. resp = b"FAIL\n"
  182. self.log.debug('resp={!r}'.format(resp))
  183. self.request.send(resp)
  184. except BaseException as e:
  185. self.log.exception(
  186. "exception while handling request: {!r}".format(e))
  187. finally:
  188. if got_lock:
  189. global_lock.release()
  190. self.log.debug('global_lock released')
  191. parser = qubes.tools.QubesArgumentParser(want_app=False)
  192. parser.add_argument('--config', '-c', metavar='FILE',
  193. action='store', default='/etc/qubes/qmemman.conf',
  194. help='qmemman config file')
  195. parser.add_argument('--foreground',
  196. action='store_true', default=False,
  197. help='do not close stdio')
  198. def main():
  199. args = parser.parse_args()
  200. # setup logging
  201. ha_syslog = logging.handlers.SysLogHandler('/dev/log')
  202. ha_syslog.setFormatter(
  203. logging.Formatter('%(name)s[%(process)d]: %(message)s'))
  204. logging.root.addHandler(ha_syslog)
  205. if args.foreground:
  206. ha_stderr = logging.StreamHandler(sys.stderr)
  207. ha_file.setFormatter(
  208. logging.Formatter('%(asctime)s %(name)s[%(process)d]: %(message)s'))
  209. logging.root.addHandler(ha_stderr)
  210. sys.stdin.close()
  211. log = logging.getLogger('qmemman.daemon')
  212. config = configparser.SafeConfigParser({
  213. 'vm-min-mem': str(qubes.qmemman.algo.MIN_PREFMEM),
  214. 'dom0-mem-boost': str(qubes.qmemman.algo.DOM0_MEM_BOOST),
  215. 'cache-margin-factor': str(qubes.qmemman.algo.CACHE_FACTOR)
  216. })
  217. config.read(args.config)
  218. if config.has_section('global'):
  219. qubes.qmemman.algo.MIN_PREFMEM = \
  220. qubes.utils.parse_size(config.get('global', 'vm-min-mem'))
  221. qubes.qmemman.algo.DOM0_MEM_BOOST = \
  222. qubes.utils.parse_size(config.get('global', 'dom0-mem-boost'))
  223. qubes.qmemman.algo.CACHE_FACTOR = \
  224. config.getfloat('global', 'cache-margin-factor')
  225. loglevel = config.getint('global', 'log-level')
  226. logging.root.setLevel(loglevel)
  227. log.info('MIN_PREFMEM={algo.MIN_PREFMEM}'
  228. ' DOM0_MEM_BOOST={algo.DOM0_MEM_BOOST}'
  229. ' CACHE_FACTOR={algo.CACHE_FACTOR}'.format(
  230. algo=qubes.qmemman.algo))
  231. try:
  232. os.unlink(SOCK_PATH)
  233. except:
  234. pass
  235. log.debug('instantiating server')
  236. os.umask(0)
  237. # Initialize the connection to Xen and to XenStore
  238. system_state.init()
  239. server = socketserver.UnixStreamServer(SOCK_PATH, QMemmanReqHandler)
  240. os.umask(0o077)
  241. # notify systemd
  242. nofity_socket = os.getenv('NOTIFY_SOCKET')
  243. if nofity_socket:
  244. log.debug('notifying systemd')
  245. s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
  246. if nofity_socket.startswith('@'):
  247. nofity_socket = '\0%s' % nofity_socket[1:]
  248. s.connect(nofity_socket)
  249. s.sendall(b"READY=1")
  250. s.close()
  251. threading.Thread(target=server.serve_forever).start()
  252. XS_Watcher().watch_loop()