qubes.py 27 KB

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