qubes.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. #!/usr/bin/python2
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2010 Joanna Rutkowska <joanna@invisiblethingslab.com>
  6. #
  7. # This program is free software; you can redistribute it and/or
  8. # modify it under the terms of the GNU General Public License
  9. # as published by the Free Software Foundation; either version 2
  10. # of the License, or (at your option) any later version.
  11. #
  12. # This program 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
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program; if not, write to the Free Software
  19. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  20. #
  21. #
  22. import sys
  23. import os
  24. import os.path
  25. import lxml.etree
  26. import xml.parsers.expat
  27. import fcntl
  28. import time
  29. import warnings
  30. import tempfile
  31. import grp
  32. # Do not use XenAPI or create/read any VM files
  33. # This is for testing only!
  34. dry_run = False
  35. #dry_run = True
  36. if not dry_run:
  37. import xen.lowlevel.xc
  38. import xen.lowlevel.xl
  39. import xen.lowlevel.xs
  40. qubes_base_dir = "/var/lib/qubes"
  41. system_path = {
  42. 'qubes_guid_path': '/usr/bin/qubes-guid',
  43. 'qrexec_daemon_path': '/usr/lib/qubes/qrexec-daemon',
  44. 'qrexec_client_path': '/usr/lib/qubes/qrexec-client',
  45. 'qubes_base_dir': qubes_base_dir,
  46. 'qubes_appvms_dir': qubes_base_dir + '/appvms',
  47. 'qubes_templates_dir': qubes_base_dir + '/vm-templates',
  48. 'qubes_servicevms_dir': qubes_base_dir + '/servicevms',
  49. 'qubes_store_filename': qubes_base_dir + '/qubes.xml',
  50. 'qubes_kernels_base_dir': qubes_base_dir + '/vm-kernels',
  51. 'qubes_icon_dir': '/usr/share/qubes/icons',
  52. 'config_template_pv': '/usr/share/qubes/vm-template.conf',
  53. 'qubes_pciback_cmd': '/usr/lib/qubes/unbind-pci-device.sh',
  54. 'prepare_volatile_img_cmd': '/usr/lib/qubes/prepare-volatile-img.sh',
  55. 'monitor_layout_notify_cmd': '/usr/bin/qubes-monitor-layout-notify',
  56. }
  57. vm_files = {
  58. 'root_img': 'root.img',
  59. 'rootcow_img': 'root-cow.img',
  60. 'volatile_img': 'volatile.img',
  61. 'clean_volatile_img': 'clean-volatile.img.tar',
  62. 'private_img': 'private.img',
  63. 'kernels_subdir': 'kernels',
  64. 'firewall_conf': 'firewall.xml',
  65. 'whitelisted_appmenus': 'whitelisted-appmenus.list',
  66. 'updates_stat_file': 'updates.stat',
  67. }
  68. defaults = {
  69. 'memory': 400,
  70. 'kernelopts': "",
  71. 'kernelopts_pcidevs': "iommu=soft swiotlb=4096",
  72. 'dom0_update_check_interval': 6*3600,
  73. # how long (in sec) to wait for VMs to shutdown,
  74. # before killing them (when used qvm-run with --wait option),
  75. 'shutdown_counter_max': 60,
  76. 'vm_default_netmask': "255.255.255.0",
  77. # Set later
  78. 'appvm_label': None,
  79. 'template_label': None,
  80. 'servicevm_label': None,
  81. }
  82. qubes_max_qid = 254
  83. qubes_max_netid = 254
  84. class QubesException (Exception):
  85. pass
  86. if not dry_run:
  87. xc = xen.lowlevel.xc.xc()
  88. xs = xen.lowlevel.xs.xs()
  89. xl_ctx = xen.lowlevel.xl.ctx()
  90. class QubesHost(object):
  91. def __init__(self):
  92. self.physinfo = xc.physinfo()
  93. self.xen_total_mem = long(self.physinfo['total_memory'])
  94. self.xen_no_cpus = self.physinfo['nr_cpus']
  95. # print "QubesHost: total_mem = {0}B".format (self.xen_total_mem)
  96. # print "QubesHost: free_mem = {0}".format (self.get_free_xen_memory())
  97. # print "QubesHost: total_cpus = {0}".format (self.xen_no_cpus)
  98. @property
  99. def memory_total(self):
  100. return self.xen_total_mem
  101. @property
  102. def no_cpus(self):
  103. return self.xen_no_cpus
  104. def get_free_xen_memory(self):
  105. ret = self.physinfo['free_memory']
  106. return long(ret)
  107. def measure_cpu_usage(self, previous=None, previous_time = None,
  108. wait_time=1):
  109. """measure cpu usage for all domains at once"""
  110. if previous is None:
  111. previous_time = time.time()
  112. previous = {}
  113. info = xc.domain_getinfo(0, qubes_max_qid)
  114. for vm in info:
  115. previous[vm['domid']] = {}
  116. previous[vm['domid']]['cpu_time'] = (
  117. vm['cpu_time'] / vm['online_vcpus'])
  118. previous[vm['domid']]['cpu_usage'] = 0
  119. time.sleep(wait_time)
  120. current_time = time.time()
  121. current = {}
  122. info = xc.domain_getinfo(0, qubes_max_qid)
  123. for vm in info:
  124. current[vm['domid']] = {}
  125. current[vm['domid']]['cpu_time'] = (
  126. vm['cpu_time'] / max(vm['online_vcpus'], 1))
  127. if vm['domid'] in previous.keys():
  128. current[vm['domid']]['cpu_usage'] = (
  129. float(current[vm['domid']]['cpu_time'] -
  130. previous[vm['domid']]['cpu_time']) /
  131. long(1000**3) / (current_time-previous_time) * 100)
  132. if current[vm['domid']]['cpu_usage'] < 0:
  133. # VM has been rebooted
  134. current[vm['domid']]['cpu_usage'] = 0
  135. else:
  136. current[vm['domid']]['cpu_usage'] = 0
  137. return (current_time, current)
  138. class QubesVmLabel(object):
  139. def __init__(self, index, color, name, icon = None):
  140. self.name = name
  141. self.index = index
  142. self.color = color
  143. self.icon = icon if icon is not None else name
  144. self.icon_path = os.path.join(
  145. system_path['qubes_icon_dir'], self.icon) + ".png"
  146. # Globally defined lables
  147. QubesVmLabels = {
  148. "red": QubesVmLabel(1, "0xcc0000", "red" ),
  149. "orange": QubesVmLabel(2, "0xf57900", "orange" ),
  150. "yellow": QubesVmLabel(3, "0xedd400", "yellow" ),
  151. "green": QubesVmLabel(4, "0x73d216", "green" ),
  152. "gray": QubesVmLabel(5, "0x555753", "gray" ),
  153. "blue": QubesVmLabel(6, "0x3465a4", "blue" ),
  154. "purple": QubesVmLabel(7, "0x75507b", "purple" ),
  155. "black": QubesVmLabel(8, "0x000000", "black" ),
  156. }
  157. QubesDispVmLabels = {
  158. "red": QubesVmLabel(1, "0xcc0000", "red", icon="dispvm-red" ),
  159. "orange": QubesVmLabel(2, "0xf57900", "orange", icon="dispvm-orange"),
  160. "yellow": QubesVmLabel(3, "0xedd400", "yellow", icon="dispvm-yellow"),
  161. "green": QubesVmLabel(4, "0x73d216", "green", icon="dispvm-green" ),
  162. "gray": QubesVmLabel(5, "0x555753", "gray", icon="dispvm-gray" ),
  163. "blue": QubesVmLabel(6, "0x3465a4", "blue", icon="dispvm-blue" ),
  164. "purple": QubesVmLabel(7, "0x75507b", "purple", icon="dispvm-purple"),
  165. "black": QubesVmLabel(8, "0x000000", "black", icon="dispvm-black" ),
  166. }
  167. defaults["appvm_label"] = QubesVmLabels["red"]
  168. defaults["template_label"] = QubesVmLabels["black"]
  169. defaults["servicevm_label"] = QubesVmLabels["red"]
  170. QubesVmClasses = {}
  171. def register_qubes_vm_class(vm_class):
  172. QubesVmClasses[vm_class.__name__] = vm_class
  173. # register class as local for this module - to make it easy to import from
  174. # other modules
  175. setattr(sys.modules[__name__], vm_class.__name__, vm_class)
  176. class QubesVmCollection(dict):
  177. """
  178. A collection of Qubes VMs indexed by Qubes id (qid)
  179. """
  180. def __init__(self, store_filename=system_path["qubes_store_filename"]):
  181. super(QubesVmCollection, self).__init__()
  182. self.default_netvm_qid = None
  183. self.default_fw_netvm_qid = None
  184. self.default_template_qid = None
  185. self.default_kernel = None
  186. self.updatevm_qid = None
  187. self.qubes_store_filename = store_filename
  188. self.clockvm_qid = None
  189. self.qubes_store_file = None
  190. def values(self):
  191. for qid in self.keys():
  192. yield self[qid]
  193. def items(self):
  194. for qid in self.keys():
  195. yield (qid, self[qid])
  196. def __iter__(self):
  197. for qid in sorted(super(QubesVmCollection, self).keys()):
  198. yield qid
  199. keys = __iter__
  200. def __setitem__(self, key, value):
  201. if key not in self:
  202. return super(QubesVmCollection, self).__setitem__(key, value)
  203. else:
  204. assert False, "Attempt to add VM with qid that already exists in the collection!"
  205. def add_new_vm(self, vm_type, **kwargs):
  206. if vm_type not in QubesVmClasses.keys():
  207. raise ValueError("Unknown VM type: %s" % vm_type)
  208. qid = self.get_new_unused_qid()
  209. vm = QubesVmClasses[vm_type](qid=qid, collection=self, **kwargs)
  210. if not self.verify_new_vm(vm):
  211. raise QubesException("Wrong VM description!")
  212. self[vm.qid] = vm
  213. # make first created NetVM the default one
  214. if self.default_fw_netvm_qid is None and vm.is_netvm():
  215. self.set_default_fw_netvm(vm)
  216. if self.default_netvm_qid is None and vm.is_proxyvm():
  217. self.set_default_netvm(vm)
  218. # make first created TemplateVM the default one
  219. if self.default_template_qid is None and vm.is_template():
  220. self.set_default_template(vm)
  221. # make first created ProxyVM the UpdateVM
  222. if self.updatevm_qid is None and vm.is_proxyvm():
  223. self.set_updatevm_vm(vm)
  224. # by default ClockVM is the first NetVM
  225. if self.clockvm_qid is None and vm.is_netvm():
  226. self.set_clockvm_vm(vm)
  227. return vm
  228. def add_new_appvm(self, name, template,
  229. dir_path = None, conf_file = None,
  230. private_img = None,
  231. label = None):
  232. warnings.warn("Call to deprecated function, use add_new_vm instead",
  233. DeprecationWarning, stacklevel=2)
  234. return self.add_new_vm("QubesAppVm", name=name, template=template,
  235. dir_path=dir_path, conf_file=conf_file,
  236. private_img=private_img,
  237. netvm = self.get_default_netvm(),
  238. kernel = self.get_default_kernel(),
  239. uses_default_kernel = True,
  240. label=label)
  241. def add_new_hvm(self, name, label = None):
  242. warnings.warn("Call to deprecated function, use add_new_vm instead",
  243. DeprecationWarning, stacklevel=2)
  244. return self.add_new_vm("QubesHVm", name=name, label=label)
  245. def add_new_disposablevm(self, name, template, dispid,
  246. label = None, netvm = None):
  247. warnings.warn("Call to deprecated function, use add_new_vm instead",
  248. DeprecationWarning, stacklevel=2)
  249. return self.add_new_vm("QubesDisposableVm", name=name, template=template,
  250. netvm = netvm,
  251. label=label, dispid=dispid)
  252. def add_new_templatevm(self, name,
  253. dir_path = None, conf_file = None,
  254. root_img = None, private_img = None,
  255. installed_by_rpm = True):
  256. warnings.warn("Call to deprecated function, use add_new_vm instead",
  257. DeprecationWarning, stacklevel=2)
  258. return self.add_new_vm("QubesTemplateVm", name=name,
  259. dir_path=dir_path, conf_file=conf_file,
  260. root_img=root_img, private_img=private_img,
  261. installed_by_rpm=installed_by_rpm,
  262. netvm = self.get_default_netvm(),
  263. kernel = self.get_default_kernel(),
  264. uses_default_kernel = True)
  265. def add_new_netvm(self, name, template,
  266. dir_path = None, conf_file = None,
  267. private_img = None, installed_by_rpm = False,
  268. label = None):
  269. warnings.warn("Call to deprecated function, use add_new_vm instead",
  270. DeprecationWarning, stacklevel=2)
  271. return self.add_new_vm("QubesNetVm", name=name, template=template,
  272. label=label,
  273. private_img=private_img, installed_by_rpm=installed_by_rpm,
  274. uses_default_kernel = True,
  275. dir_path=dir_path, conf_file=conf_file)
  276. def add_new_proxyvm(self, name, template,
  277. dir_path = None, conf_file = None,
  278. private_img = None, installed_by_rpm = False,
  279. label = None):
  280. warnings.warn("Call to deprecated function, use add_new_vm instead",
  281. DeprecationWarning, stacklevel=2)
  282. return self.add_new_vm("QubesProxyVm", name=name, template=template,
  283. label=label,
  284. private_img=private_img, installed_by_rpm=installed_by_rpm,
  285. dir_path=dir_path, conf_file=conf_file,
  286. uses_default_kernel = True,
  287. netvm = self.get_default_fw_netvm())
  288. def set_default_template(self, vm):
  289. assert vm.is_template(), "VM {0} is not a TemplateVM!".format(vm.name)
  290. self.default_template_qid = vm.qid
  291. def get_default_template(self):
  292. if self.default_template_qid is None:
  293. return None
  294. else:
  295. return self[self.default_template_qid]
  296. def set_default_netvm(self, vm):
  297. assert vm.is_netvm(), "VM {0} does not provide network!".format(vm.name)
  298. self.default_netvm_qid = vm.qid
  299. def get_default_netvm(self):
  300. if self.default_netvm_qid is None:
  301. return None
  302. else:
  303. return self[self.default_netvm_qid]
  304. def set_default_kernel(self, kernel):
  305. assert os.path.exists(
  306. os.path.join(system_path["qubes_kernels_base_dir"], kernel)), \
  307. "Kerel {0} not installed!".format(kernel)
  308. self.default_kernel = kernel
  309. def get_default_kernel(self):
  310. return self.default_kernel
  311. def set_default_fw_netvm(self, vm):
  312. assert vm.is_netvm(), "VM {0} does not provide network!".format(vm.name)
  313. self.default_fw_netvm_qid = vm.qid
  314. def get_default_fw_netvm(self):
  315. if self.default_fw_netvm_qid is None:
  316. return None
  317. else:
  318. return self[self.default_fw_netvm_qid]
  319. def set_updatevm_vm(self, vm):
  320. self.updatevm_qid = vm.qid
  321. def get_updatevm_vm(self):
  322. if self.updatevm_qid is None:
  323. return None
  324. else:
  325. return self[self.updatevm_qid]
  326. def set_clockvm_vm(self, vm):
  327. self.clockvm_qid = vm.qid
  328. def get_clockvm_vm(self):
  329. if self.clockvm_qid is None:
  330. return None
  331. else:
  332. return self[self.clockvm_qid]
  333. def get_vm_by_name(self, name):
  334. for vm in self.values():
  335. if (vm.name == name):
  336. return vm
  337. return None
  338. def get_qid_by_name(self, name):
  339. vm = self.get_vm_by_name(name)
  340. return vm.qid if vm is not None else None
  341. def get_vms_based_on(self, template_qid):
  342. vms = set([vm for vm in self.values()
  343. if (vm.template and vm.template.qid == template_qid)])
  344. return vms
  345. def get_vms_connected_to(self, netvm_qid):
  346. new_vms = [ netvm_qid ]
  347. dependend_vms_qid = []
  348. # Dependency resolving only makes sense on NetVM (or derivative)
  349. if not self[netvm_qid].is_netvm():
  350. return set([])
  351. while len(new_vms) > 0:
  352. cur_vm = new_vms.pop()
  353. for vm in self[cur_vm].connected_vms.values():
  354. if vm.qid not in dependend_vms_qid:
  355. dependend_vms_qid.append(vm.qid)
  356. if vm.is_netvm():
  357. new_vms.append(vm.qid)
  358. vms = [vm for vm in self.values() if vm.qid in dependend_vms_qid]
  359. return vms
  360. def verify_new_vm(self, new_vm):
  361. # Verify that qid is unique
  362. for vm in self.values():
  363. if vm.qid == new_vm.qid:
  364. print >> sys.stderr, "ERROR: The qid={0} is already used by VM '{1}'!".\
  365. format(vm.qid, vm.name)
  366. return False
  367. # Verify that name is unique
  368. for vm in self.values():
  369. if vm.name == new_vm.name:
  370. print >> sys.stderr, \
  371. "ERROR: The name={0} is already used by other VM with qid='{1}'!".\
  372. format(vm.name, vm.qid)
  373. return False
  374. return True
  375. def get_new_unused_qid(self):
  376. used_ids = set([vm.qid for vm in self.values()])
  377. for id in range (1, qubes_max_qid):
  378. if id not in used_ids:
  379. return id
  380. raise LookupError ("Cannot find unused qid!")
  381. def get_new_unused_netid(self):
  382. used_ids = set([vm.netid for vm in self.values() if vm.is_netvm()])
  383. for id in range (1, qubes_max_netid):
  384. if id not in used_ids:
  385. return id
  386. raise LookupError ("Cannot find unused netid!")
  387. def check_if_storage_exists(self):
  388. try:
  389. f = open (self.qubes_store_filename, 'r')
  390. except IOError:
  391. return False
  392. f.close()
  393. return True
  394. def create_empty_storage(self):
  395. self.qubes_store_file = open (self.qubes_store_filename, 'w')
  396. self.clear()
  397. self.save()
  398. def lock_db_for_reading(self):
  399. self.qubes_store_file = open (self.qubes_store_filename, 'r')
  400. fcntl.lockf (self.qubes_store_file, fcntl.LOCK_SH)
  401. def lock_db_for_writing(self):
  402. self.qubes_store_file = open (self.qubes_store_filename, 'r+')
  403. fcntl.lockf (self.qubes_store_file, fcntl.LOCK_EX)
  404. def unlock_db(self):
  405. # intentionally do not call explicit unlock to not unlock the file
  406. # before all buffers are flushed
  407. self.qubes_store_file.close()
  408. def save(self):
  409. root = lxml.etree.Element(
  410. "QubesVmCollection",
  411. default_template=str(self.default_template_qid) \
  412. if self.default_template_qid is not None else "None",
  413. default_netvm=str(self.default_netvm_qid) \
  414. if self.default_netvm_qid is not None else "None",
  415. default_fw_netvm=str(self.default_fw_netvm_qid) \
  416. if self.default_fw_netvm_qid is not None else "None",
  417. updatevm=str(self.updatevm_qid) \
  418. if self.updatevm_qid is not None else "None",
  419. clockvm=str(self.clockvm_qid) \
  420. if self.clockvm_qid is not None else "None",
  421. default_kernel=str(self.default_kernel) \
  422. if self.default_kernel is not None else "None",
  423. )
  424. for vm in self.values():
  425. element = vm.create_xml_element()
  426. if element is not None:
  427. root.append(element)
  428. tree = lxml.etree.ElementTree(root)
  429. try:
  430. new_store_file = tempfile.NamedTemporaryFile(prefix=self.qubes_store_filename, delete=False)
  431. # XXX: do not get lock on the new file, as in all use cases
  432. # unlock_db() is the next operation after save()
  433. tree.write(new_store_file, encoding="UTF-8", pretty_print=True)
  434. new_store_file.flush()
  435. os.chmod(new_store_file.name, 0660)
  436. os.chown(new_store_file.name, -1, grp.getgrnam('qubes').gr_gid)
  437. os.rename(new_store_file.name, self.qubes_store_filename)
  438. self.qubes_store_file.close()
  439. self.qubes_store_file = new_store_file
  440. except EnvironmentError as err:
  441. print("{0}: export error: {1}".format(
  442. os.path.basename(sys.argv[0]), err))
  443. return False
  444. return True
  445. def set_netvm_dependency(self, element):
  446. kwargs = {}
  447. attr_list = ("qid", "uses_default_netvm", "netvm_qid")
  448. for attribute in attr_list:
  449. kwargs[attribute] = element.get(attribute)
  450. vm = self[int(kwargs["qid"])]
  451. if "uses_default_netvm" not in kwargs:
  452. vm.uses_default_netvm = True
  453. else:
  454. vm.uses_default_netvm = (
  455. True if kwargs["uses_default_netvm"] == "True" else False)
  456. if vm.uses_default_netvm is True:
  457. if vm.is_proxyvm():
  458. netvm = self.get_default_fw_netvm()
  459. else:
  460. netvm = self.get_default_netvm()
  461. kwargs.pop("netvm_qid")
  462. else:
  463. if kwargs["netvm_qid"] == "none" or kwargs["netvm_qid"] is None:
  464. netvm = None
  465. kwargs.pop("netvm_qid")
  466. else:
  467. netvm_qid = int(kwargs.pop("netvm_qid"))
  468. if netvm_qid not in self:
  469. netvm = None
  470. else:
  471. netvm = self[netvm_qid]
  472. # directly set internal attr to not call setters...
  473. vm._netvm = netvm
  474. if netvm:
  475. netvm.connected_vms[vm.qid] = vm
  476. def load_globals(self, element):
  477. default_template = element.get("default_template")
  478. self.default_template_qid = int(default_template) \
  479. if default_template.lower() != "none" else None
  480. default_netvm = element.get("default_netvm")
  481. if default_netvm is not None:
  482. self.default_netvm_qid = int(default_netvm) \
  483. if default_netvm != "None" else None
  484. #assert self.default_netvm_qid is not None
  485. default_fw_netvm = element.get("default_fw_netvm")
  486. if default_fw_netvm is not None:
  487. self.default_fw_netvm_qid = int(default_fw_netvm) \
  488. if default_fw_netvm != "None" else None
  489. #assert self.default_netvm_qid is not None
  490. updatevm = element.get("updatevm")
  491. if updatevm is not None:
  492. self.updatevm_qid = int(updatevm) \
  493. if updatevm != "None" else None
  494. #assert self.default_netvm_qid is not None
  495. clockvm = element.get("clockvm")
  496. if clockvm is not None:
  497. self.clockvm_qid = int(clockvm) \
  498. if clockvm != "None" else None
  499. self.default_kernel = element.get("default_kernel")
  500. def load(self):
  501. self.clear()
  502. try:
  503. tree = lxml.etree.parse(self.qubes_store_file)
  504. except (EnvironmentError,
  505. xml.parsers.expat.ExpatError) as err:
  506. print("{0}: import error: {1}".format(
  507. os.path.basename(sys.argv[0]), err))
  508. return False
  509. self.load_globals(tree.getroot())
  510. for (vm_class_name, vm_class) in sorted(QubesVmClasses.items(),
  511. key=lambda _x: _x[1].load_order):
  512. vms_of_class = tree.findall(vm_class_name)
  513. # first non-template based, then template based
  514. sorted_vms_of_class = sorted(vms_of_class, key= \
  515. lambda x: str(x.get('template_qid')).lower() != "none")
  516. for element in sorted_vms_of_class:
  517. try:
  518. vm = vm_class(xml_element=element, collection=self)
  519. self[vm.qid] = vm
  520. except (ValueError, LookupError) as err:
  521. print("{0}: import error ({1}): {2}".format(
  522. os.path.basename(sys.argv[0]), vm_class_name, err))
  523. raise
  524. return False
  525. # After importing all VMs, set netvm references, in the same order
  526. for (vm_class_name, vm_class) in sorted(QubesVmClasses.items(),
  527. key=lambda _x: _x[1].load_order):
  528. for element in tree.findall(vm_class_name):
  529. try:
  530. self.set_netvm_dependency(element)
  531. except (ValueError, LookupError) as err:
  532. print("{0}: import error2 ({}): {}".format(
  533. os.path.basename(sys.argv[0]), vm_class_name, err))
  534. return False
  535. # if there was no clockvm entry in qubes.xml, try to determine default:
  536. # root of default NetVM chain
  537. if tree.getroot().get("clockvm") is None:
  538. if self.default_netvm_qid is not None:
  539. clockvm = self[self.default_netvm_qid]
  540. # Find root of netvm chain
  541. while clockvm.netvm is not None:
  542. clockvm = clockvm.netvm
  543. self.clockvm_qid = clockvm.qid
  544. # Disable ntpd in ClockVM - to not conflict with ntpdate (both are
  545. # using 123/udp port)
  546. if self.clockvm_qid is not None:
  547. self[self.clockvm_qid].services['ntpd'] = False
  548. # Add dom0 if wasn't present in qubes.xml
  549. if not 0 in self.keys():
  550. dom0vm = QubesAdminVm (collection=self)
  551. self[dom0vm.qid] = dom0vm
  552. return True
  553. def pop(self, qid):
  554. if self.default_netvm_qid == qid:
  555. self.default_netvm_qid = None
  556. if self.default_fw_netvm_qid == qid:
  557. self.default_fw_netvm_qid = None
  558. if self.clockvm_qid == qid:
  559. self.clockvm_qid = None
  560. if self.updatevm_qid == qid:
  561. self.updatevm_qid = None
  562. if self.default_template_qid == qid:
  563. self.default_template_qid = None
  564. return super(QubesVmCollection, self).pop(qid)
  565. class QubesDaemonPidfile(object):
  566. def __init__(self, name):
  567. self.name = name
  568. self.path = "/var/run/qubes/" + name + ".pid"
  569. def create_pidfile(self):
  570. f = open (self.path, 'w')
  571. f.write(str(os.getpid()))
  572. f.close()
  573. def pidfile_exists(self):
  574. return os.path.exists(self.path)
  575. def read_pid(self):
  576. f = open (self.path)
  577. pid = f.read ().strip()
  578. f.close()
  579. return int(pid)
  580. def pidfile_is_stale(self):
  581. if not self.pidfile_exists():
  582. return False
  583. # check if the pid file is valid...
  584. proc_path = "/proc/" + str(self.read_pid()) + "/cmdline"
  585. if not os.path.exists (proc_path):
  586. print >> sys.stderr, \
  587. "Path {0} doesn't exist, assuming stale pidfile.".\
  588. format(proc_path)
  589. return True
  590. return False # It's a good pidfile
  591. def remove_pidfile(self):
  592. os.remove (self.path)
  593. def __enter__ (self):
  594. # assumes the pidfile doesn't exist -- you should ensure it before opening the context
  595. self.create_pidfile()
  596. def __exit__ (self, exc_type, exc_val, exc_tb):
  597. self.remove_pidfile()
  598. return False
  599. modules_dir = os.path.join(os.path.dirname(__file__), 'modules')
  600. for module_file in sorted(os.listdir(modules_dir)):
  601. if not module_file.endswith(".py") or module_file == "__init__.py":
  602. continue
  603. __import__('qubes.modules.%s' % module_file[:-3])
  604. # vim:sw=4:et: