qmemman_server.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. #
  8. # This program is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU General Public License
  10. # as published by the Free Software Foundation; either version 2
  11. # of the License, or (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with this program; if not, write to the Free Software
  20. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  21. #
  22. #
  23. import SocketServer
  24. import thread
  25. import time
  26. import xen.lowlevel.xs
  27. import sys
  28. import os
  29. import socket
  30. from qmemman import SystemState
  31. import qmemman_algo
  32. from ConfigParser import SafeConfigParser
  33. from optparse import OptionParser
  34. from qubesutils import parse_size
  35. import logging
  36. import logging.handlers
  37. config_path = '/etc/qubes/qmemman.conf'
  38. SOCK_PATH='/var/run/qubes/qmemman.sock'
  39. LOG_PATH='/var/log/qubes/qmemman.log'
  40. system_state = SystemState()
  41. global_lock = thread.allocate_lock()
  42. def only_in_first_list(l1, l2):
  43. ret=[]
  44. for i in l1:
  45. if not i in l2:
  46. ret.append(i)
  47. return ret
  48. def get_domain_meminfo_key(domain_id):
  49. return '/local/domain/'+domain_id+'/memory/meminfo'
  50. class WatchType:
  51. def __init__(self, fn, param):
  52. self.fn = fn
  53. self.param = param
  54. class XS_Watcher:
  55. def __init__(self):
  56. self.log = logging.getLogger('qmemman.daemon.xswatcher')
  57. self.log.debug('XS_Watcher()')
  58. self.handle = xen.lowlevel.xs.xs()
  59. self.handle.watch('@introduceDomain', WatchType(XS_Watcher.domain_list_changed, None))
  60. self.handle.watch('@releaseDomain', WatchType(XS_Watcher.domain_list_changed, None))
  61. self.watch_token_dict = {}
  62. def domain_list_changed(self, param):
  63. self.log.debug('domain_list_changed(param={!r})'.format(param))
  64. curr = self.handle.ls('', '/local/domain')
  65. self.log.debug('curr={!r}'.format(curr))
  66. if curr == None:
  67. return
  68. self.log.debug('acquiring global_lock')
  69. global_lock.acquire()
  70. self.log.debug('global_lock acquired')
  71. for i in only_in_first_list(curr, self.watch_token_dict.keys()):
  72. #new domain has been created
  73. watch = WatchType(XS_Watcher.meminfo_changed, i)
  74. self.watch_token_dict[i] = watch
  75. self.handle.watch(get_domain_meminfo_key(i), watch)
  76. system_state.add_domain(i)
  77. for i in only_in_first_list(self.watch_token_dict.keys(), curr):
  78. #domain destroyed
  79. self.handle.unwatch(get_domain_meminfo_key(i), self.watch_token_dict[i])
  80. self.watch_token_dict.pop(i)
  81. system_state.del_domain(i)
  82. global_lock.release()
  83. self.log.debug('global_lock released')
  84. system_state.do_balance()
  85. def meminfo_changed(self, domain_id):
  86. self.log.debug('meminfo_changed(domain_id={!r})'.format(domain_id))
  87. untrusted_meminfo_key = self.handle.read('', get_domain_meminfo_key(domain_id))
  88. if untrusted_meminfo_key == None or untrusted_meminfo_key == '':
  89. return
  90. self.log.debug('acquiring global_lock')
  91. global_lock.acquire()
  92. self.log.debug('global_lock acquired')
  93. system_state.refresh_meminfo(domain_id, untrusted_meminfo_key)
  94. global_lock.release()
  95. self.log.debug('global_lock released')
  96. def watch_loop(self):
  97. self.log.debug('watch_loop()')
  98. while True:
  99. result = self.handle.read_watch()
  100. self.log.debug('watch_loop result={!r}'.format(result))
  101. token = result[1]
  102. token.fn(self, token.param)
  103. class QMemmanReqHandler(SocketServer.BaseRequestHandler):
  104. """
  105. The RequestHandler class for our server.
  106. It is instantiated once per connection to the server, and must
  107. override the handle() method to implement communication to the
  108. client.
  109. """
  110. def handle(self):
  111. self.log = logging.getLogger('qmemman.daemon.reqhandler')
  112. got_lock = False
  113. # self.request is the TCP socket connected to the client
  114. while True:
  115. self.data = self.request.recv(1024).strip()
  116. self.log.debug('data={!r}'.format(self.data))
  117. if len(self.data) == 0:
  118. self.log.info('EOF')
  119. if got_lock:
  120. global_lock.release()
  121. self.log.debug('global_lock released')
  122. return
  123. # XXX something is wrong here: return without release?
  124. if got_lock:
  125. self.log.warning('Second request over qmemman.sock?')
  126. return
  127. self.log.debug('acquiring global_lock')
  128. global_lock.acquire()
  129. self.log.debug('global_lock acquired')
  130. got_lock = True
  131. if system_state.do_balloon(int(self.data)):
  132. resp = "OK\n"
  133. else:
  134. resp = "FAIL\n"
  135. self.log.debug('resp={!r}'.format(resp))
  136. self.request.send(resp)
  137. # XXX no release of lock?
  138. def start_server(server):
  139. server.serve_forever()
  140. class QMemmanServer:
  141. @staticmethod
  142. def main():
  143. # setup logging
  144. ha_syslog = logging.handlers.SysLogHandler('/dev/log')
  145. ha_syslog.setFormatter(
  146. logging.Formatter('%(name)s[%(process)d]: %(message)s'))
  147. logging.root.addHandler(ha_syslog)
  148. # leave log for backwards compatibility
  149. ha_file = logging.FileHandler(LOG_PATH)
  150. ha_file.setFormatter(
  151. logging.Formatter('%(asctime)s %(name)s[%(process)d]: %(message)s'))
  152. logging.root.addHandler(ha_file)
  153. log = logging.getLogger('qmemman.daemon')
  154. usage = "usage: %prog [options]"
  155. parser = OptionParser(usage)
  156. parser.add_option("-c", "--config", action="store", dest="config", default=config_path)
  157. (options, args) = parser.parse_args()
  158. # close io
  159. sys.stdin.close()
  160. sys.stdout.close()
  161. sys.stderr.close()
  162. config = SafeConfigParser({
  163. 'vm-min-mem': str(qmemman_algo.MIN_PREFMEM),
  164. 'dom0-mem-boost': str(qmemman_algo.DOM0_MEM_BOOST),
  165. 'cache-margin-factor': str(qmemman_algo.CACHE_FACTOR)
  166. })
  167. config.read(options.config)
  168. if config.has_section('global'):
  169. qmemman_algo.MIN_PREFMEM = parse_size(config.get('global', 'vm-min-mem'))
  170. qmemman_algo.DOM0_MEM_BOOST = parse_size(config.get('global', 'dom0-mem-boost'))
  171. qmemman_algo.CACHE_FACTOR = config.getfloat('global', 'cache-margin-factor')
  172. log.info('MIN_PREFMEM={qmemman_algo.MIN_PREFMEM}'
  173. ' DOM0_MEM_BOOST={qmemman_algo.DOM0_MEM_BOOST}'
  174. ' CACHE_FACTOR={qmemman_algo.CACHE_FACTOR}'.format(
  175. qmemman_algo=qmemman_algo))
  176. try:
  177. os.unlink(SOCK_PATH)
  178. except:
  179. pass
  180. log.debug('instantiating server')
  181. os.umask(0)
  182. server = SocketServer.UnixStreamServer(SOCK_PATH, QMemmanReqHandler)
  183. os.umask(077)
  184. # notify systemd
  185. nofity_socket = os.getenv('NOTIFY_SOCKET')
  186. if nofity_socket:
  187. log.debug('notifying systemd')
  188. s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
  189. if nofity_socket.startswith('@'):
  190. nofity_socket = '\0%s' % nofity_socket[1:]
  191. s.connect(nofity_socket)
  192. s.sendall("READY=1")
  193. s.close()
  194. thread.start_new_thread(start_server, tuple([server]))
  195. XS_Watcher().watch_loop()