000QubesVm.py 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876
  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. # Copyright (C) 2013 Marek Marczykowski <marmarek@invisiblethingslab.com>
  8. #
  9. # This program is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU General Public License
  11. # as published by the Free Software Foundation; either version 2
  12. # of the License, or (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License
  20. # along with this program; if not, write to the Free Software
  21. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  22. #
  23. #
  24. import datetime
  25. import logging
  26. import lxml.etree
  27. import os
  28. import os.path
  29. import re
  30. import shutil
  31. import subprocess
  32. import sys
  33. import time
  34. import uuid
  35. import xml.parsers.expat
  36. from qubes import qmemman
  37. from qubes import qmemman_algo
  38. import libvirt
  39. import warnings
  40. from qubes.qubes import dry_run,vmm
  41. from qubes.qubes import register_qubes_vm_class
  42. from qubes.qubes import QubesVmCollection,QubesException,QubesHost,QubesVmLabels
  43. from qubes.qubes import defaults,system_path,vm_files,qubes_max_qid
  44. qmemman_present = False
  45. try:
  46. from qubes.qmemman_client import QMemmanClient
  47. qmemman_present = True
  48. except ImportError:
  49. pass
  50. import qubes.qubesutils
  51. xid_to_name_cache = {}
  52. class QubesVm(object):
  53. """
  54. A representation of one Qubes VM
  55. Only persistent information are stored here, while all the runtime
  56. information, e.g. Xen dom id, etc, are to be retrieved via Xen API
  57. Note that qid is not the same as Xen's domid!
  58. """
  59. # In which order load this VM type from qubes.xml
  60. load_order = 100
  61. # hooks for plugins (modules) which want to influence existing classes,
  62. # without introducing new ones
  63. hooks_clone_disk_files = []
  64. hooks_create_on_disk = []
  65. hooks_create_qubesdb_entries = []
  66. hooks_get_attrs_config = []
  67. hooks_get_clone_attrs = []
  68. hooks_get_config_params = []
  69. hooks_init = []
  70. hooks_label_setter = []
  71. hooks_netvm_setter = []
  72. hooks_post_rename = []
  73. hooks_pre_rename = []
  74. hooks_remove_from_disk = []
  75. hooks_start = []
  76. hooks_verify_files = []
  77. hooks_set_attr = []
  78. def get_attrs_config(self):
  79. """ Object attributes for serialization/deserialization
  80. inner dict keys:
  81. - order: initialization order (to keep dependency intact)
  82. attrs without order will be evaluated at the end
  83. - default: default value used when attr not given to object constructor
  84. - attr: set value to this attribute instead of parameter name
  85. - eval: (DEPRECATED) assign result of this expression instead of
  86. value directly; local variable 'value' contains
  87. attribute value (or default if it was not given)
  88. - func: callable used to parse the value retrieved from XML
  89. - save: use evaluation result as value for XML serialization; only attrs with 'save' key will be saved in XML
  90. - save_skip: if present and evaluates to true, attr will be omitted in XML
  91. - save_attr: save to this XML attribute instead of parameter name
  92. """
  93. attrs = {
  94. # __qid cannot be accessed by setattr, so must be set manually in __init__
  95. "qid": { "attr": "_qid", "order": 0 },
  96. "name": { "order": 1 },
  97. "uuid": { "order": 0, "eval": 'uuid.UUID(value) if value else None' },
  98. "dir_path": { "default": None, "order": 2 },
  99. "conf_file": {
  100. "func": lambda value: self.absolute_path(value, self.name +
  101. ".conf"),
  102. "order": 3 },
  103. ### order >= 10: have base attrs set
  104. "firewall_conf": {
  105. "func": self._absolute_path_gen(vm_files["firewall_conf"]),
  106. "order": 10 },
  107. "installed_by_rpm": { "default": False, 'order': 10 },
  108. "template": { "default": None, "attr": '_template', 'order': 10 },
  109. ### order >= 20: have template set
  110. "uses_default_netvm": { "default": True, 'order': 20 },
  111. "netvm": { "default": None, "attr": "_netvm", 'order': 20 },
  112. "label": { "attr": "_label", "default": defaults["appvm_label"], 'order': 20,
  113. 'xml_deserialize': lambda _x: QubesVmLabels[_x] },
  114. "memory": { "default": defaults["memory"], 'order': 20 },
  115. "maxmem": { "default": None, 'order': 25 },
  116. "pcidevs": {
  117. "default": '[]',
  118. "order": 25,
  119. "func": lambda value: [] if value in ["none", None] else
  120. eval(value) if value.find("[") >= 0 else
  121. eval("[" + value + "]") },
  122. # Internal VM (not shown in qubes-manager, doesn't create appmenus entries
  123. "internal": { "default": False, 'attr': '_internal' },
  124. "vcpus": { "default": None },
  125. "uses_default_kernel": { "default": True, 'order': 30 },
  126. "uses_default_kernelopts": { "default": True, 'order': 30 },
  127. "kernel": {
  128. "attr": "_kernel",
  129. "default": None,
  130. "order": 31,
  131. "func": lambda value: self._collection.get_default_kernel() if
  132. self.uses_default_kernel else value },
  133. "kernelopts": {
  134. "default": "",
  135. "order": 31,
  136. "func": lambda value: value if not self.uses_default_kernelopts\
  137. else defaults["kernelopts_pcidevs"] if len(self.pcidevs)>0 \
  138. else defaults["kernelopts"] },
  139. "mac": { "attr": "_mac", "default": None },
  140. "include_in_backups": { "default": True },
  141. "services": {
  142. "default": {},
  143. "func": lambda value: eval(str(value)) },
  144. "debug": { "default": False },
  145. "default_user": { "default": "user", "attr": "_default_user" },
  146. "qrexec_timeout": { "default": 60 },
  147. "autostart": { "default": False, "attr": "_autostart" },
  148. "backup_content" : { 'default': False },
  149. "backup_size" : {
  150. "default": 0,
  151. "func": int },
  152. "backup_path" : { 'default': "" },
  153. "backup_timestamp": {
  154. "func": lambda value:
  155. datetime.datetime.fromtimestamp(int(value)) if value
  156. else None },
  157. ##### Internal attributes - will be overriden in __init__ regardless of args
  158. "config_file_template": {
  159. "func": lambda x: system_path["config_template_pv"] },
  160. "icon_path": {
  161. "func": lambda x: os.path.join(self.dir_path, "icon.png") if
  162. self.dir_path is not None else None },
  163. # used to suppress side effects of clone_attrs
  164. "_do_not_reset_firewall": { "func": lambda x: False },
  165. "kernels_dir": {
  166. # for backward compatibility (or another rare case): kernel=None -> kernel in VM dir
  167. "func": lambda x: \
  168. os.path.join(system_path["qubes_kernels_base_dir"],
  169. self.kernel) if self.kernel is not None \
  170. else os.path.join(self.dir_path,
  171. vm_files["kernels_subdir"]) },
  172. "_start_guid_first": { "func": lambda x: False },
  173. }
  174. ### Mark attrs for XML inclusion
  175. # Simple string attrs
  176. for prop in ['qid', 'uuid', 'name', 'dir_path', 'memory', 'maxmem',
  177. 'pcidevs', 'vcpus', 'internal',\
  178. 'uses_default_kernel', 'kernel', 'uses_default_kernelopts',\
  179. 'kernelopts', 'services', 'installed_by_rpm',\
  180. 'uses_default_netvm', 'include_in_backups', 'debug',\
  181. 'qrexec_timeout', 'autostart',
  182. 'backup_content', 'backup_size', 'backup_path' ]:
  183. attrs[prop]['save'] = lambda prop=prop: str(getattr(self, prop))
  184. # Simple paths
  185. for prop in ['conf_file']:
  186. attrs[prop]['save'] = \
  187. lambda prop=prop: self.relative_path(getattr(self, prop))
  188. attrs[prop]['save_skip'] = \
  189. lambda prop=prop: getattr(self, prop) is None
  190. # Can happen only if VM created in offline mode
  191. attrs['maxmem']['save_skip'] = lambda: self.maxmem is None
  192. attrs['vcpus']['save_skip'] = lambda: self.vcpus is None
  193. attrs['uuid']['save_skip'] = lambda: self.uuid is None
  194. attrs['mac']['save'] = lambda: str(self._mac)
  195. attrs['mac']['save_skip'] = lambda: self._mac is None
  196. attrs['default_user']['save'] = lambda: str(self._default_user)
  197. attrs['backup_timestamp']['save'] = \
  198. lambda: self.backup_timestamp.strftime("%s")
  199. attrs['backup_timestamp']['save_skip'] = \
  200. lambda: self.backup_timestamp is None
  201. attrs['netvm']['save'] = \
  202. lambda: str(self.netvm.qid) if self.netvm is not None else "none"
  203. attrs['netvm']['save_attr'] = "netvm_qid"
  204. attrs['template']['save'] = \
  205. lambda: str(self.template.qid) if self.template else "none"
  206. attrs['template']['save_attr'] = "template_qid"
  207. attrs['label']['save'] = lambda: self.label.name
  208. # fire hooks
  209. for hook in self.hooks_get_attrs_config:
  210. attrs = hook(self, attrs)
  211. return attrs
  212. def post_set_attr(self, attr, newvalue, oldvalue):
  213. for hook in self.hooks_set_attr:
  214. hook(self, attr, newvalue, oldvalue)
  215. def __basic_parse_xml_attr(self, value):
  216. if value is None:
  217. return None
  218. if value.lower() == "none":
  219. return None
  220. if value.lower() == "true":
  221. return True
  222. if value.lower() == "false":
  223. return False
  224. if value.isdigit():
  225. return int(value)
  226. return value
  227. def __init__(self, **kwargs):
  228. self._collection = None
  229. if 'collection' in kwargs:
  230. self._collection = kwargs['collection']
  231. else:
  232. raise ValueError("No collection given to QubesVM constructor")
  233. # Special case for template b/c it is given in "template_qid" property
  234. if "xml_element" in kwargs and kwargs["xml_element"].get("template_qid"):
  235. template_qid = kwargs["xml_element"].get("template_qid")
  236. if template_qid.lower() != "none":
  237. if int(template_qid) in self._collection:
  238. kwargs["template"] = self._collection[int(template_qid)]
  239. else:
  240. raise ValueError("Unknown template with QID %s" % template_qid)
  241. attrs = self.get_attrs_config()
  242. for attr_name in sorted(attrs, key=lambda _x: attrs[_x]['order'] if 'order' in attrs[_x] else 1000):
  243. attr_config = attrs[attr_name]
  244. attr = attr_name
  245. if 'attr' in attr_config:
  246. attr = attr_config['attr']
  247. value = None
  248. if attr_name in kwargs:
  249. value = kwargs[attr_name]
  250. elif 'xml_element' in kwargs and kwargs['xml_element'].get(attr_name) is not None:
  251. if 'xml_deserialize' in attr_config and callable(attr_config['xml_deserialize']):
  252. value = attr_config['xml_deserialize'](kwargs['xml_element'].get(attr_name))
  253. else:
  254. value = self.__basic_parse_xml_attr(kwargs['xml_element'].get(attr_name))
  255. else:
  256. if 'default' in attr_config:
  257. value = attr_config['default']
  258. if 'func' in attr_config:
  259. setattr(self, attr, attr_config['func'](value))
  260. elif 'eval' in attr_config:
  261. setattr(self, attr, eval(attr_config['eval']))
  262. else:
  263. #print "setting %s to %s" % (attr, value)
  264. setattr(self, attr, value)
  265. #Init private attrs
  266. self.__qid = self._qid
  267. self._libvirt_domain = None
  268. self._qdb_connection = None
  269. assert self.__qid < qubes_max_qid, "VM id out of bounds!"
  270. assert self.name is not None
  271. if not self.verify_name(self.name):
  272. msg = ("'%s' is invalid VM name (invalid characters, over 31 chars long, "
  273. "or one of 'none', 'true', 'false')") % self.name
  274. if 'xml_element' in kwargs:
  275. print >>sys.stderr, "WARNING: %s" % msg
  276. else:
  277. raise QubesException(msg)
  278. if self.netvm is not None:
  279. self.netvm.connected_vms[self.qid] = self
  280. # Not in generic way to not create QubesHost() to frequently
  281. if self.maxmem is None and not vmm.offline_mode:
  282. qubes_host = QubesHost()
  283. total_mem_mb = qubes_host.memory_total/1024
  284. self.maxmem = total_mem_mb/2
  285. # Linux specific cap: max memory can't scale beyond 10.79*init_mem
  286. if self.maxmem > self.memory * 10:
  287. self.maxmem = self.memory * 10
  288. # By default allow use all VCPUs
  289. if self.vcpus is None and not vmm.offline_mode:
  290. qubes_host = QubesHost()
  291. self.vcpus = qubes_host.no_cpus
  292. # Always set if meminfo-writer should be active or not
  293. if 'meminfo-writer' not in self.services:
  294. self.services['meminfo-writer'] = not (len(self.pcidevs) > 0)
  295. # Additionally force meminfo-writer disabled when VM have PCI devices
  296. if len(self.pcidevs) > 0:
  297. self.services['meminfo-writer'] = False
  298. # Initialize VM image storage class
  299. self.storage = defaults["storage_class"](self)
  300. if hasattr(self, 'kernels_dir'):
  301. self.storage.modules_img = os.path.join(self.kernels_dir,
  302. "modules.img")
  303. self.storage.modules_img_rw = self.kernel is None
  304. # Some additional checks for template based VM
  305. if self.template is not None:
  306. if not self.template.is_template():
  307. print >> sys.stderr, "ERROR: template_qid={0} doesn't point to a valid TemplateVM".\
  308. format(self.template.qid)
  309. return
  310. self.template.appvms[self.qid] = self
  311. else:
  312. assert self.root_img is not None, "Missing root_img for standalone VM!"
  313. self.log = logging.getLogger('qubes.vm.{}'.format(self.qid))
  314. self.log.debug('instantiated name={!r} class={}'.format(
  315. self.name, self.__class__.__name__))
  316. # fire hooks
  317. for hook in self.hooks_init:
  318. hook(self)
  319. def __repr__(self):
  320. return '<{} at {:#0x} qid={!r} name={!r}>'.format(
  321. self.__class__.__name__,
  322. id(self),
  323. self.qid,
  324. self.name)
  325. def absolute_path(self, arg, default):
  326. if arg is not None and os.path.isabs(arg):
  327. return arg
  328. else:
  329. return os.path.join(self.dir_path, (arg if arg is not None else default))
  330. def _absolute_path_gen(self, default):
  331. return lambda value: self.absolute_path(value, default)
  332. def relative_path(self, arg):
  333. return arg.replace(self.dir_path + '/', '')
  334. @property
  335. def qid(self):
  336. return self.__qid
  337. @property
  338. def label(self):
  339. return self._label
  340. @label.setter
  341. def label(self, new_label):
  342. self._label = new_label
  343. if self.icon_path:
  344. try:
  345. os.remove(self.icon_path)
  346. except:
  347. pass
  348. if hasattr(os, "symlink"):
  349. os.symlink (new_label.icon_path, self.icon_path)
  350. # FIXME: some os-independent wrapper?
  351. subprocess.call(['sudo', 'xdg-icon-resource', 'forceupdate'])
  352. else:
  353. shutil.copy(new_label.icon_path, self.icon_path)
  354. # fire hooks
  355. for hook in self.hooks_label_setter:
  356. hook(self, new_label)
  357. @property
  358. def netvm(self):
  359. return self._netvm
  360. # Don't know how properly call setter from base class, so workaround it...
  361. @netvm.setter
  362. def netvm(self, new_netvm):
  363. self._set_netvm(new_netvm)
  364. # fire hooks
  365. for hook in self.hooks_netvm_setter:
  366. hook(self, new_netvm)
  367. def _set_netvm(self, new_netvm):
  368. self.log.debug('netvm = {!r}'.format(new_netvm))
  369. if self.is_running() and new_netvm is not None and not new_netvm.is_running():
  370. raise QubesException("Cannot dynamically attach to stopped NetVM")
  371. if self.netvm is not None:
  372. self.netvm.connected_vms.pop(self.qid)
  373. if self.is_running():
  374. self.detach_network()
  375. if hasattr(self.netvm, 'post_vm_net_detach'):
  376. self.netvm.post_vm_net_detach(self)
  377. if new_netvm is None:
  378. if not self._do_not_reset_firewall:
  379. # Set also firewall to block all traffic as discussed in #370
  380. if os.path.exists(self.firewall_conf):
  381. shutil.copy(self.firewall_conf, os.path.join(system_path["qubes_base_dir"],
  382. "backup", "%s-firewall-%s.xml" % (self.name,
  383. time.strftime('%Y-%m-%d-%H:%M:%S'))))
  384. self.write_firewall_conf({'allow': False, 'allowDns': False,
  385. 'allowIcmp': False, 'allowYumProxy': False, 'rules': []})
  386. else:
  387. new_netvm.connected_vms[self.qid]=self
  388. self._netvm = new_netvm
  389. if new_netvm is None:
  390. return
  391. if self.is_running():
  392. # refresh IP, DNS etc
  393. self.create_qubesdb_entries()
  394. self.attach_network()
  395. if hasattr(self.netvm, 'post_vm_net_attach'):
  396. self.netvm.post_vm_net_attach(self)
  397. @property
  398. def ip(self):
  399. if self.netvm is not None:
  400. return self.netvm.get_ip_for_vm(self.qid)
  401. else:
  402. return None
  403. @property
  404. def netmask(self):
  405. if self.netvm is not None:
  406. return self.netvm.netmask
  407. else:
  408. return None
  409. @property
  410. def gateway(self):
  411. # This is gateway IP for _other_ VMs, so make sense only in NetVMs
  412. return None
  413. @property
  414. def secondary_dns(self):
  415. if self.netvm is not None:
  416. return self.netvm.secondary_dns
  417. else:
  418. return None
  419. @property
  420. def vif(self):
  421. if self.xid < 0:
  422. return None
  423. if self.netvm is None:
  424. return None
  425. return "vif{0}.+".format(self.xid)
  426. @property
  427. def mac(self):
  428. if self._mac is not None:
  429. return self._mac
  430. else:
  431. return "00:16:3E:5E:6C:{qid:02X}".format(qid=self.qid)
  432. @mac.setter
  433. def mac(self, new_mac):
  434. self._mac = new_mac
  435. @property
  436. def kernel(self):
  437. return self._kernel
  438. @kernel.setter
  439. def kernel(self, new_value):
  440. if new_value is not None:
  441. if not os.path.exists(os.path.join(system_path[
  442. 'qubes_kernels_base_dir'], new_value)):
  443. raise QubesException("Kernel '%s' not installed" % new_value)
  444. for f in ('vmlinuz', 'modules.img'):
  445. if not os.path.exists(os.path.join(
  446. system_path['qubes_kernels_base_dir'], new_value, f)):
  447. raise QubesException(
  448. "Kernel '%s' not properly installed: missing %s "
  449. "file" % (new_value, f))
  450. self._kernel = new_value
  451. @property
  452. def updateable(self):
  453. return self.template is None
  454. # Leaved for compatibility
  455. def is_updateable(self):
  456. return self.updateable
  457. @property
  458. def default_user(self):
  459. if self.template is not None:
  460. return self.template.default_user
  461. else:
  462. return self._default_user
  463. @default_user.setter
  464. def default_user(self, value):
  465. self._default_user = value
  466. def is_networked(self):
  467. if self.is_netvm():
  468. return True
  469. if self.netvm is not None:
  470. return True
  471. else:
  472. return False
  473. def verify_name(self, name):
  474. if not isinstance(self.__basic_parse_xml_attr(name), str):
  475. return False
  476. if len(name) > 31:
  477. return False
  478. return re.match(r"^[a-zA-Z][a-zA-Z0-9_-]*$", name) is not None
  479. def pre_rename(self, new_name):
  480. # fire hooks
  481. for hook in self.hooks_pre_rename:
  482. hook(self, new_name)
  483. def set_name(self, name):
  484. self.log.debug('name = {!r}'.format(name))
  485. if self.is_running():
  486. raise QubesException("Cannot change name of running VM!")
  487. if not self.verify_name(name):
  488. raise QubesException("Invalid characters in VM name")
  489. if self.installed_by_rpm:
  490. raise QubesException("Cannot rename VM installed by RPM -- first clone VM and then use yum to remove package.")
  491. self.pre_rename(name)
  492. if self.libvirt_domain:
  493. self.libvirt_domain.undefine()
  494. if self._qdb_connection:
  495. self._qdb_connection.close()
  496. self._qdb_connection = None
  497. new_conf = os.path.join(self.dir_path, name + '.conf')
  498. if os.path.exists(self.conf_file):
  499. os.rename(self.conf_file, new_conf)
  500. old_dirpath = self.dir_path
  501. self.storage.rename(self.name, name)
  502. new_dirpath = self.storage.vmdir
  503. self.dir_path = new_dirpath
  504. old_name = self.name
  505. self.name = name
  506. if self.conf_file is not None:
  507. self.conf_file = new_conf.replace(old_dirpath, new_dirpath)
  508. if self.icon_path is not None:
  509. self.icon_path = self.icon_path.replace(old_dirpath, new_dirpath)
  510. if hasattr(self, 'kernels_dir') and self.kernels_dir is not None:
  511. self.kernels_dir = self.kernels_dir.replace(old_dirpath, new_dirpath)
  512. self._update_libvirt_domain()
  513. self.post_rename(old_name)
  514. def post_rename(self, old_name):
  515. # fire hooks
  516. for hook in self.hooks_post_rename:
  517. hook(self, old_name)
  518. @property
  519. def internal(self):
  520. return self._internal
  521. @internal.setter
  522. def internal(self, value):
  523. oldvalue = self._internal
  524. self._internal = value
  525. self.post_set_attr('internal', value, oldvalue)
  526. @property
  527. def autostart(self):
  528. return self._autostart
  529. @autostart.setter
  530. def autostart(self, value):
  531. if value:
  532. retcode = subprocess.call(["sudo", "ln", "-sf",
  533. "/usr/lib/systemd/system/qubes-vm@.service",
  534. "/etc/systemd/system/multi-user.target.wants/qubes-vm@%s.service" % self.name])
  535. else:
  536. retcode = subprocess.call(["sudo", "systemctl", "disable", "qubes-vm@%s.service" % self.name])
  537. if retcode != 0:
  538. raise QubesException("Failed to set autostart for VM via systemctl")
  539. self._autostart = bool(value)
  540. @classmethod
  541. def is_template_compatible(cls, template):
  542. """Check if given VM can be a template for this VM"""
  543. # FIXME: check if the value is instance of QubesTemplateVM, not the VM
  544. # type. The problem is while this file is loaded, QubesTemplateVM is
  545. # not defined yet.
  546. if template and (not template.is_template() or template.type != "TemplateVM"):
  547. return False
  548. return True
  549. @property
  550. def template(self):
  551. return self._template
  552. @template.setter
  553. def template(self, value):
  554. if self._template is None and value is not None:
  555. raise QubesException("Cannot set template for standalone VM")
  556. if value and not self.is_template_compatible(value):
  557. raise QubesException("Incompatible template type %s with VM of type %s" % (value.type, self.type))
  558. self._template = value
  559. def is_template(self):
  560. return False
  561. def is_appvm(self):
  562. return False
  563. def is_netvm(self):
  564. return False
  565. def is_proxyvm(self):
  566. return False
  567. def is_disposablevm(self):
  568. return False
  569. @property
  570. def qdb(self):
  571. if self._qdb_connection is None:
  572. from qubes.qdb import QubesDB
  573. self._qdb_connection = QubesDB(self.name)
  574. return self._qdb_connection
  575. @property
  576. def xid(self):
  577. try:
  578. return self.libvirt_domain.ID()
  579. except libvirt.libvirtError:
  580. if vmm.libvirt_conn.virConnGetLastError()[0] == libvirt.VIR_ERR_NO_DOMAIN:
  581. return -1
  582. else:
  583. raise
  584. def get_xid(self):
  585. # obsoleted
  586. return self.xid
  587. def _update_libvirt_domain(self):
  588. domain_config = self.create_config_file()
  589. self._libvirt_domain = vmm.libvirt_conn.defineXML(domain_config)
  590. self.uuid = uuid.UUID(bytes=self._libvirt_domain.UUID())
  591. @property
  592. def libvirt_domain(self):
  593. if self._libvirt_domain is None:
  594. if self.uuid is not None:
  595. self._libvirt_domain = vmm.libvirt_conn.lookupByUUID(self.uuid.bytes)
  596. else:
  597. self._libvirt_domain = vmm.libvirt_conn.lookupByName(self.name)
  598. self.uuid = uuid.UUID(bytes=self._libvirt_domain.UUID())
  599. return self._libvirt_domain
  600. def get_uuid(self):
  601. # obsoleted
  602. return self.uuid
  603. def refresh(self):
  604. self._libvirt_domain = None
  605. self._qdb_connection = None
  606. def get_mem(self):
  607. if dry_run:
  608. return 666
  609. try:
  610. if not self.libvirt_domain.isActive():
  611. return 0
  612. return self.libvirt_domain.info()[1]
  613. except libvirt.libvirtError:
  614. if vmm.libvirt_conn.virConnGetLastError()[0] == libvirt.VIR_ERR_NO_DOMAIN:
  615. return 0
  616. else:
  617. raise
  618. def get_cputime(self):
  619. if dry_run:
  620. return 666
  621. try:
  622. if not self.libvirt_domain.isActive():
  623. return 0
  624. return self.libvirt_domain.info()[4]
  625. except libvirt.libvirtError:
  626. if vmm.libvirt_conn.virConnGetLastError()[0] == libvirt.VIR_ERR_NO_DOMAIN:
  627. return 0
  628. else:
  629. raise
  630. def get_mem_static_max(self):
  631. if dry_run:
  632. return 666
  633. try:
  634. return self.libvirt_domain.maxMemory()
  635. except libvirt.libvirtError:
  636. if vmm.libvirt_conn.virConnGetLastError()[0] == libvirt.VIR_ERR_NO_DOMAIN:
  637. return 0
  638. else:
  639. raise
  640. def get_prefmem(self):
  641. # TODO: qmemman is still xen specific
  642. untrusted_meminfo_key = vmm.xs.read('',
  643. '/local/domain/%s/memory/meminfo'
  644. % self.xid)
  645. if untrusted_meminfo_key is None or untrusted_meminfo_key == '':
  646. return 0
  647. domain = qmemman.DomainState(self.xid)
  648. qmemman_algo.refresh_meminfo_for_domain(domain, untrusted_meminfo_key)
  649. domain.memory_maximum = self.get_mem_static_max()*1024
  650. return qmemman_algo.prefmem(domain)/1024
  651. def get_per_cpu_time(self):
  652. if dry_run:
  653. import random
  654. return random.random() * 100
  655. try:
  656. if self.libvirt_domain.isActive():
  657. return self.libvirt_domain.getCPUStats(
  658. libvirt.VIR_NODE_CPU_STATS_ALL_CPUS, 0)[0]['cpu_time']/10**9
  659. else:
  660. return 0
  661. except libvirt.libvirtError:
  662. if vmm.libvirt_conn.virConnGetLastError()[0] == libvirt.VIR_ERR_NO_DOMAIN:
  663. return 0
  664. else:
  665. raise
  666. def get_disk_utilization_root_img(self):
  667. return qubes.qubesutils.get_disk_usage(self.root_img)
  668. def get_root_img_sz(self):
  669. if not os.path.exists(self.root_img):
  670. return 0
  671. return os.path.getsize(self.root_img)
  672. def get_power_state(self):
  673. if dry_run:
  674. return "NA"
  675. try:
  676. libvirt_domain = self.libvirt_domain
  677. if libvirt_domain.isActive():
  678. if libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PAUSED:
  679. return "Paused"
  680. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_CRASHED:
  681. return "Crashed"
  682. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_SHUTDOWN:
  683. return "Halting"
  684. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_SHUTOFF:
  685. return "Dying"
  686. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PMSUSPENDED:
  687. return "Suspended"
  688. else:
  689. if not self.is_fully_usable():
  690. return "Transient"
  691. else:
  692. return "Running"
  693. else:
  694. return 'Halted'
  695. except libvirt.libvirtError:
  696. if vmm.libvirt_conn.virConnGetLastError()[0] == libvirt.VIR_ERR_NO_DOMAIN:
  697. return "NA"
  698. else:
  699. raise
  700. def is_guid_running(self):
  701. xid = self.xid
  702. if xid < 0:
  703. return False
  704. if not os.path.exists('/var/run/qubes/guid-running.%d' % xid):
  705. return False
  706. return True
  707. def is_qrexec_running(self):
  708. if self.xid < 0:
  709. return False
  710. return os.path.exists('/var/run/qubes/qrexec.%s' % self.name)
  711. def is_fully_usable(self):
  712. # Running gui-daemon implies also VM running
  713. if not self.is_guid_running():
  714. return False
  715. if not self.is_qrexec_running():
  716. return False
  717. return True
  718. def is_running(self):
  719. try:
  720. if self.libvirt_domain.isActive():
  721. return True
  722. else:
  723. return False
  724. except libvirt.libvirtError:
  725. if vmm.libvirt_conn.virConnGetLastError()[0] == libvirt.VIR_ERR_NO_DOMAIN:
  726. return False
  727. else:
  728. raise
  729. def is_paused(self):
  730. try:
  731. if self.libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PAUSED:
  732. return True
  733. else:
  734. return False
  735. except libvirt.libvirtError:
  736. if vmm.libvirt_conn.virConnGetLastError()[0] == libvirt.VIR_ERR_NO_DOMAIN:
  737. return False
  738. else:
  739. raise
  740. def get_start_time(self):
  741. if not self.is_running():
  742. return None
  743. # TODO
  744. uuid = self.uuid
  745. start_time = vmm.xs.read('', "/vm/%s/start_time" % str(uuid))
  746. if start_time != '':
  747. return datetime.datetime.fromtimestamp(float(start_time))
  748. else:
  749. return None
  750. def is_outdated(self):
  751. # Makes sense only on VM based on template
  752. if self.template is None:
  753. return False
  754. if not self.is_running():
  755. return False
  756. if not hasattr(self.template, 'rootcow_img'):
  757. return False
  758. rootimg_inode = os.stat(self.template.root_img)
  759. try:
  760. rootcow_inode = os.stat(self.template.rootcow_img)
  761. except OSError:
  762. # The only case when rootcow_img doesn't exists is in the middle of
  763. # commit_changes, so VM is outdated right now
  764. return True
  765. current_dmdev = "/dev/mapper/snapshot-{0:x}:{1}-{2:x}:{3}".format(
  766. rootimg_inode[2], rootimg_inode[1],
  767. rootcow_inode[2], rootcow_inode[1])
  768. # FIXME
  769. # 51712 (0xCA00) is xvda
  770. # backend node name not available through xenapi :(
  771. used_dmdev = vmm.xs.read('', "/local/domain/0/backend/vbd/{0}/51712/node".format(self.xid))
  772. return used_dmdev != current_dmdev
  773. @property
  774. def private_img(self):
  775. return self.storage.private_img
  776. @property
  777. def root_img(self):
  778. return self.storage.root_img
  779. @property
  780. def volatile_img(self):
  781. return self.storage.volatile_img
  782. def get_disk_utilization(self):
  783. return qubes.qubesutils.get_disk_usage(self.dir_path)
  784. def get_disk_utilization_private_img(self):
  785. return qubes.qubesutils.get_disk_usage(self.private_img)
  786. def get_private_img_sz(self):
  787. return self.storage.get_private_img_sz()
  788. def resize_private_img(self, size):
  789. assert size >= self.get_private_img_sz(), "Cannot shrink private.img"
  790. # resize the image
  791. self.storage.resize_private_img(size)
  792. # and then the filesystem
  793. retcode = 0
  794. if self.is_running():
  795. retcode = self.run("while [ \"`blockdev --getsize64 /dev/xvdb`\" -lt {0} ]; do ".format(size) +
  796. "head /dev/xvdb > /dev/null; sleep 0.2; done; resize2fs /dev/xvdb", user="root", wait=True)
  797. if retcode != 0:
  798. raise QubesException("resize2fs failed")
  799. # FIXME: should be outside of QubesVM?
  800. def get_timezone(self):
  801. # fc18
  802. if os.path.islink('/etc/localtime'):
  803. return '/'.join(os.readlink('/etc/localtime').split('/')[-2:])
  804. # <=fc17
  805. elif os.path.exists('/etc/sysconfig/clock'):
  806. clock_config = open('/etc/sysconfig/clock', "r")
  807. clock_config_lines = clock_config.readlines()
  808. clock_config.close()
  809. zone_re = re.compile(r'^ZONE="(.*)"')
  810. for line in clock_config_lines:
  811. line_match = zone_re.match(line)
  812. if line_match:
  813. return line_match.group(1)
  814. else:
  815. # last resort way, some applications makes /etc/localtime
  816. # hardlink instead of symlink...
  817. tz_info = os.stat('/etc/localtime')
  818. if not tz_info:
  819. return None
  820. if tz_info.st_nlink > 1:
  821. p = subprocess.Popen(['find', '/usr/share/zoneinfo',
  822. '-inum', str(tz_info.st_ino)],
  823. stdout=subprocess.PIPE)
  824. tz_path = p.communicate()[0].strip()
  825. return tz_path.replace('/usr/share/zoneinfo/', '')
  826. return None
  827. def cleanup_vifs(self):
  828. """
  829. Xend does not remove vif when backend domain is down, so we must do it
  830. manually
  831. """
  832. # FIXME: remove this?
  833. if not self.is_running():
  834. return
  835. dev_basepath = '/local/domain/%d/device/vif' % self.xid
  836. for dev in vmm.xs.ls('', dev_basepath):
  837. # check if backend domain is alive
  838. backend_xid = int(vmm.xs.read('', '%s/%s/backend-id' % (dev_basepath, dev)))
  839. if backend_xid in vmm.libvirt_conn.listDomainsID():
  840. # check if device is still active
  841. if vmm.xs.read('', '%s/%s/state' % (dev_basepath, dev)) == '4':
  842. continue
  843. # remove dead device
  844. vmm.xs.rm('', '%s/%s' % (dev_basepath, dev))
  845. def create_qubesdb_entries(self):
  846. if dry_run:
  847. return
  848. self.qdb.write("/name", self.name)
  849. self.qdb.write("/qubes-vm-type", self.type)
  850. self.qdb.write("/qubes-vm-updateable", str(self.updateable))
  851. if self.is_netvm():
  852. self.qdb.write("/qubes-netvm-gateway", self.gateway)
  853. self.qdb.write("/qubes-netvm-secondary-dns", self.secondary_dns)
  854. self.qdb.write("/qubes-netvm-netmask", self.netmask)
  855. self.qdb.write("/qubes-netvm-network", self.network)
  856. if self.netvm is not None:
  857. self.qdb.write("/qubes-ip", self.ip)
  858. self.qdb.write("/qubes-netmask", self.netvm.netmask)
  859. self.qdb.write("/qubes-gateway", self.netvm.gateway)
  860. self.qdb.write("/qubes-secondary-dns", self.netvm.secondary_dns)
  861. tzname = self.get_timezone()
  862. if tzname:
  863. self.qdb.write("/qubes-timezone", tzname)
  864. for srv in self.services.keys():
  865. # convert True/False to "1"/"0"
  866. self.qdb.write("/qubes-service/{0}".format(srv),
  867. str(int(self.services[srv])))
  868. self.qdb.write("/qubes-block-devices", '')
  869. self.qdb.write("/qubes-usb-devices", '')
  870. self.qdb.write("/qubes-debug-mode", str(int(self.debug)))
  871. # TODO: Currently the whole qmemman is quite Xen-specific, so stay with
  872. # xenstore for it until decided otherwise
  873. if qmemman_present:
  874. vmm.xs.set_permissions('', '/local/domain/{0}/memory'.format(self.xid),
  875. [{ 'dom': self.xid }])
  876. # fire hooks
  877. for hook in self.hooks_create_qubesdb_entries:
  878. hook(self)
  879. def _format_net_dev(self, ip, mac, backend):
  880. template = " <interface type='ethernet'>\n" \
  881. " <mac address='{mac}'/>\n" \
  882. " <ip address='{ip}'/>\n" \
  883. " <script path='vif-route-qubes'/>\n" \
  884. " <backenddomain name='{backend}'/>\n" \
  885. " </interface>\n"
  886. return template.format(ip=ip, mac=mac, backend=backend)
  887. def _format_pci_dev(self, address):
  888. template = " <hostdev type='pci' managed='yes'>\n" \
  889. " <source>\n" \
  890. " <address bus='0x{bus}' slot='0x{slot}' function='0x{fun}'/>\n" \
  891. " </source>\n" \
  892. " </hostdev>\n"
  893. dev_match = re.match('([0-9a-f]+):([0-9a-f]+)\.([0-9a-f]+)', address)
  894. if not dev_match:
  895. raise QubesException("Invalid PCI device address: %s" % address)
  896. return template.format(
  897. bus=dev_match.group(1),
  898. slot=dev_match.group(2),
  899. fun=dev_match.group(3))
  900. def get_config_params(self):
  901. args = {}
  902. args['name'] = self.name
  903. if hasattr(self, 'kernels_dir'):
  904. args['kerneldir'] = self.kernels_dir
  905. args['uuidnode'] = "<uuid>%s</uuid>" % str(self.uuid) if self.uuid else ""
  906. args['vmdir'] = self.dir_path
  907. args['pcidevs'] = ''.join(map(self._format_pci_dev, self.pcidevs))
  908. args['mem'] = str(self.memory)
  909. if self.maxmem < self.memory:
  910. args['mem'] = str(self.maxmem)
  911. args['maxmem'] = str(self.maxmem)
  912. if 'meminfo-writer' in self.services and not self.services['meminfo-writer']:
  913. # If dynamic memory management disabled, set maxmem=mem
  914. args['maxmem'] = args['mem']
  915. args['vcpus'] = str(self.vcpus)
  916. if self.netvm is not None:
  917. args['ip'] = self.ip
  918. args['mac'] = self.mac
  919. args['gateway'] = self.netvm.gateway
  920. args['dns1'] = self.netvm.gateway
  921. args['dns2'] = self.secondary_dns
  922. args['netmask'] = self.netmask
  923. args['netdev'] = self._format_net_dev(self.ip, self.mac, self.netvm.name)
  924. args['disable_network1'] = '';
  925. args['disable_network2'] = '';
  926. else:
  927. args['ip'] = ''
  928. args['mac'] = ''
  929. args['gateway'] = ''
  930. args['dns1'] = ''
  931. args['dns2'] = ''
  932. args['netmask'] = ''
  933. args['netdev'] = ''
  934. args['disable_network1'] = '<!--';
  935. args['disable_network2'] = '-->';
  936. args.update(self.storage.get_config_params())
  937. if hasattr(self, 'kernelopts'):
  938. args['kernelopts'] = self.kernelopts
  939. if self.debug:
  940. print >> sys.stderr, "--> Debug mode: adding 'earlyprintk=xen' to kernel opts"
  941. args['kernelopts'] += ' earlyprintk=xen'
  942. # fire hooks
  943. for hook in self.hooks_get_config_params:
  944. args = hook(self, args)
  945. return args
  946. @property
  947. def uses_custom_config(self):
  948. return self.conf_file != self.absolute_path(self.name + ".conf", None)
  949. def create_config_file(self, file_path = None, prepare_dvm = False):
  950. if file_path is None:
  951. file_path = self.conf_file
  952. if self.uses_custom_config:
  953. conf_appvm = open(file_path, "r")
  954. domain_config = conf_appvm.read()
  955. conf_appvm.close()
  956. return domain_config
  957. f_conf_template = open(self.config_file_template, 'r')
  958. conf_template = f_conf_template.read()
  959. f_conf_template.close()
  960. template_params = self.get_config_params()
  961. if prepare_dvm:
  962. template_params['name'] = '%NAME%'
  963. template_params['privatedev'] = ''
  964. template_params['netdev'] = re.sub(r"address='[0-9.]*'", "address='%IP%'", template_params['netdev'])
  965. domain_config = conf_template.format(**template_params)
  966. # FIXME: This is only for debugging purposes
  967. old_umask = os.umask(002)
  968. try:
  969. if os.path.exists(file_path):
  970. os.unlink(file_path)
  971. conf_appvm = open(file_path, "w")
  972. conf_appvm.write(domain_config)
  973. conf_appvm.close()
  974. except:
  975. # Ignore errors
  976. pass
  977. finally:
  978. os.umask(old_umask)
  979. return domain_config
  980. def create_on_disk(self, verbose=False, source_template = None):
  981. self.log.debug('create_on_disk(source_template={!r})'.format(
  982. source_template))
  983. if source_template is None:
  984. source_template = self.template
  985. assert source_template is not None
  986. if dry_run:
  987. return
  988. self.storage.create_on_disk(verbose, source_template)
  989. if self.updateable:
  990. kernels_dir = source_template.kernels_dir
  991. if verbose:
  992. print >> sys.stderr, "--> Copying the kernel (set kernel \"none\" to use it): {0}".\
  993. format(kernels_dir)
  994. os.mkdir (self.dir_path + '/kernels')
  995. for f in ("vmlinuz", "initramfs", "modules.img"):
  996. shutil.copy(os.path.join(kernels_dir, f),
  997. os.path.join(self.dir_path, vm_files["kernels_subdir"], f))
  998. if verbose:
  999. print >> sys.stderr, "--> Creating icon symlink: {0} -> {1}".format(self.icon_path, self.label.icon_path)
  1000. if hasattr(os, "symlink"):
  1001. os.symlink (self.label.icon_path, self.icon_path)
  1002. else:
  1003. shutil.copy(self.label.icon_path, self.icon_path)
  1004. # Make sure that we have UUID allocated
  1005. self._update_libvirt_domain()
  1006. # fire hooks
  1007. for hook in self.hooks_create_on_disk:
  1008. hook(self, verbose, source_template=source_template)
  1009. def get_clone_attrs(self):
  1010. attrs = ['kernel', 'uses_default_kernel', 'netvm', 'uses_default_netvm', \
  1011. 'memory', 'maxmem', 'kernelopts', 'uses_default_kernelopts', 'services', 'vcpus', \
  1012. '_mac', 'pcidevs', 'include_in_backups', '_label', 'default_user']
  1013. # fire hooks
  1014. for hook in self.hooks_get_clone_attrs:
  1015. attrs = hook(self, attrs)
  1016. return attrs
  1017. def clone_attrs(self, src_vm, fail_on_error=True):
  1018. self._do_not_reset_firewall = True
  1019. for prop in self.get_clone_attrs():
  1020. try:
  1021. setattr(self, prop, getattr(src_vm, prop))
  1022. except Exception as e:
  1023. if fail_on_error:
  1024. self._do_not_reset_firewall = False
  1025. raise
  1026. else:
  1027. print >>sys.stderr, "WARNING: %s" % str(e)
  1028. self._do_not_reset_firewall = False
  1029. def clone_disk_files(self, src_vm, verbose):
  1030. if dry_run:
  1031. return
  1032. if src_vm.is_running():
  1033. raise QubesException("Attempt to clone a running VM!")
  1034. self.storage.clone_disk_files(src_vm, verbose)
  1035. if src_vm.icon_path is not None and self.icon_path is not None:
  1036. if os.path.exists (src_vm.dir_path):
  1037. if os.path.islink(src_vm.icon_path):
  1038. icon_path = os.readlink(src_vm.icon_path)
  1039. if verbose:
  1040. print >> sys.stderr, "--> Creating icon symlink: {0} -> {1}".format(self.icon_path, icon_path)
  1041. os.symlink (icon_path, self.icon_path)
  1042. else:
  1043. if verbose:
  1044. print >> sys.stderr, "--> Copying icon: {0} -> {1}".format(src_vm.icon_path, self.icon_path)
  1045. shutil.copy(src_vm.icon_path, self.icon_path)
  1046. # Make sure that we have UUID allocated
  1047. self._update_libvirt_domain()
  1048. # fire hooks
  1049. for hook in self.hooks_clone_disk_files:
  1050. hook(self, src_vm, verbose)
  1051. def verify_files(self):
  1052. if dry_run:
  1053. return
  1054. self.storage.verify_files()
  1055. if not os.path.exists (os.path.join(self.kernels_dir, 'vmlinuz')):
  1056. raise QubesException (
  1057. "VM kernel does not exist: {0}".\
  1058. format(os.path.join(self.kernels_dir, 'vmlinuz')))
  1059. if not os.path.exists (os.path.join(self.kernels_dir, 'initramfs')):
  1060. raise QubesException (
  1061. "VM initramfs does not exist: {0}".\
  1062. format(os.path.join(self.kernels_dir, 'initramfs')))
  1063. # fire hooks
  1064. for hook in self.hooks_verify_files:
  1065. hook(self)
  1066. return True
  1067. def remove_from_disk(self):
  1068. self.log.debug('remove_from_disk()')
  1069. if dry_run:
  1070. return
  1071. # fire hooks
  1072. for hook in self.hooks_remove_from_disk:
  1073. hook(self)
  1074. self.libvirt_domain.undefine()
  1075. self.storage.remove_from_disk()
  1076. def write_firewall_conf(self, conf):
  1077. defaults = self.get_firewall_conf()
  1078. expiring_rules_present = False
  1079. for item in defaults.keys():
  1080. if item not in conf:
  1081. conf[item] = defaults[item]
  1082. root = lxml.etree.Element(
  1083. "QubesFirewallRules",
  1084. policy = "allow" if conf["allow"] else "deny",
  1085. dns = "allow" if conf["allowDns"] else "deny",
  1086. icmp = "allow" if conf["allowIcmp"] else "deny",
  1087. yumProxy = "allow" if conf["allowYumProxy"] else "deny"
  1088. )
  1089. for rule in conf["rules"]:
  1090. # For backward compatibility
  1091. if "proto" not in rule:
  1092. if rule["portBegin"] is not None and rule["portBegin"] > 0:
  1093. rule["proto"] = "tcp"
  1094. else:
  1095. rule["proto"] = "any"
  1096. element = lxml.etree.Element(
  1097. "rule",
  1098. address=rule["address"],
  1099. proto=str(rule["proto"]),
  1100. )
  1101. if rule["netmask"] is not None and rule["netmask"] != 32:
  1102. element.set("netmask", str(rule["netmask"]))
  1103. if rule.get("portBegin", None) is not None and \
  1104. rule["portBegin"] > 0:
  1105. element.set("port", str(rule["portBegin"]))
  1106. if rule.get("portEnd", None) is not None and rule["portEnd"] > 0:
  1107. element.set("toport", str(rule["portEnd"]))
  1108. if "expire" in rule:
  1109. element.set("expire", str(rule["expire"]))
  1110. expiring_rules_present = True
  1111. root.append(element)
  1112. tree = lxml.etree.ElementTree(root)
  1113. try:
  1114. old_umask = os.umask(002)
  1115. with open(self.firewall_conf, 'w') as f:
  1116. tree.write(f, encoding="UTF-8", pretty_print=True)
  1117. f.close()
  1118. os.umask(old_umask)
  1119. except EnvironmentError as err:
  1120. print >> sys.stderr, "{0}: save error: {1}".format(
  1121. os.path.basename(sys.argv[0]), err)
  1122. return False
  1123. # Automatically enable/disable 'yum-proxy-setup' service based on allowYumProxy
  1124. if conf['allowYumProxy']:
  1125. self.services['yum-proxy-setup'] = True
  1126. else:
  1127. if self.services.has_key('yum-proxy-setup'):
  1128. self.services.pop('yum-proxy-setup')
  1129. if expiring_rules_present:
  1130. subprocess.call(["sudo", "systemctl", "start",
  1131. "qubes-reload-firewall@%s.timer" % self.name])
  1132. return True
  1133. def has_firewall(self):
  1134. return os.path.exists (self.firewall_conf)
  1135. def get_firewall_defaults(self):
  1136. return { "rules": list(), "allow": True, "allowDns": True, "allowIcmp": True, "allowYumProxy": False }
  1137. def get_firewall_conf(self):
  1138. conf = self.get_firewall_defaults()
  1139. try:
  1140. tree = lxml.etree.parse(self.firewall_conf)
  1141. root = tree.getroot()
  1142. conf["allow"] = (root.get("policy") == "allow")
  1143. conf["allowDns"] = (root.get("dns") == "allow")
  1144. conf["allowIcmp"] = (root.get("icmp") == "allow")
  1145. conf["allowYumProxy"] = (root.get("yumProxy") == "allow")
  1146. for element in root:
  1147. rule = {}
  1148. attr_list = ("address", "netmask", "proto", "port", "toport",
  1149. "expire")
  1150. for attribute in attr_list:
  1151. rule[attribute] = element.get(attribute)
  1152. if rule["netmask"] is not None:
  1153. rule["netmask"] = int(rule["netmask"])
  1154. else:
  1155. rule["netmask"] = 32
  1156. if rule["port"] is not None:
  1157. rule["portBegin"] = int(rule["port"])
  1158. else:
  1159. # backward compatibility
  1160. rule["portBegin"] = 0
  1161. # For backward compatibility
  1162. if rule["proto"] is None:
  1163. if rule["portBegin"] > 0:
  1164. rule["proto"] = "tcp"
  1165. else:
  1166. rule["proto"] = "any"
  1167. if rule["toport"] is not None:
  1168. rule["portEnd"] = int(rule["toport"])
  1169. else:
  1170. rule["portEnd"] = None
  1171. if rule["expire"] is not None:
  1172. rule["expire"] = int(rule["expire"])
  1173. if rule["expire"] <= int(datetime.datetime.now().strftime(
  1174. "%s")):
  1175. continue
  1176. else:
  1177. del(rule["expire"])
  1178. del(rule["port"])
  1179. del(rule["toport"])
  1180. conf["rules"].append(rule)
  1181. except EnvironmentError as err:
  1182. return conf
  1183. except (xml.parsers.expat.ExpatError,
  1184. ValueError, LookupError) as err:
  1185. print("{0}: load error: {1}".format(
  1186. os.path.basename(sys.argv[0]), err))
  1187. return None
  1188. return conf
  1189. def pci_add(self, pci):
  1190. self.log.debug('pci_add(pci={!r})'.format(pci))
  1191. if not os.path.exists('/sys/bus/pci/devices/0000:%s' % pci):
  1192. raise QubesException("Invalid PCI device: %s" % pci)
  1193. if self.pcidevs.count(pci):
  1194. # already added
  1195. return
  1196. self.pcidevs.append(pci)
  1197. if self.is_running():
  1198. try:
  1199. subprocess.check_call(['sudo', system_path["qubes_pciback_cmd"], pci])
  1200. subprocess.check_call(['sudo', 'xl', 'pci-attach', str(self.xid), pci])
  1201. except Exception as e:
  1202. print >>sys.stderr, "Failed to attach PCI device on the fly " \
  1203. "(%s), changes will be seen after VM restart" % str(e)
  1204. def pci_remove(self, pci):
  1205. self.log.debug('pci_remove(pci={!r})'.format(pci))
  1206. if not self.pcidevs.count(pci):
  1207. # not attached
  1208. return
  1209. self.pcidevs.remove(pci)
  1210. if self.is_running():
  1211. p = subprocess.Popen(['xl', 'pci-list', str(self.xid)],
  1212. stdout=subprocess.PIPE)
  1213. result = p.communicate()
  1214. m = re.search(r"^(\d+.\d+)\s+0000:%s$" % pci, result[0], flags=re.MULTILINE)
  1215. if not m:
  1216. print >>sys.stderr, "Device %s already detached" % pci
  1217. return
  1218. vmdev = m.group(1)
  1219. try:
  1220. self.run_service("qubes.DetachPciDevice",
  1221. user="root", input="00:%s" % vmdev)
  1222. subprocess.check_call(['sudo', 'xl', 'pci-detach', str(self.xid), pci])
  1223. except Exception as e:
  1224. print >>sys.stderr, "Failed to detach PCI device on the fly " \
  1225. "(%s), changes will be seen after VM restart" % str(e)
  1226. def run(self, command, user = None, verbose = True, autostart = False,
  1227. notify_function = None,
  1228. passio = False, passio_popen = False, passio_stderr=False,
  1229. ignore_stderr=False, localcmd = None, wait = False, gui = True,
  1230. filter_esc = False):
  1231. """command should be in form 'cmdline'
  1232. When passio_popen=True, popen object with stdout connected to pipe.
  1233. When additionally passio_stderr=True, stderr also is connected to pipe.
  1234. When ignore_stderr=True, stderr is connected to /dev/null.
  1235. """
  1236. self.log.debug(
  1237. 'run(command={!r}, user={!r}, passio={!r}, wait={!r})'.format(
  1238. command, user, passio, wait))
  1239. if user is None:
  1240. user = self.default_user
  1241. null = None
  1242. if not self.is_running() and not self.is_paused():
  1243. if not autostart:
  1244. raise QubesException("VM not running")
  1245. try:
  1246. if notify_function is not None:
  1247. notify_function ("info", "Starting the '{0}' VM...".format(self.name))
  1248. elif verbose:
  1249. print >> sys.stderr, "Starting the VM '{0}'...".format(self.name)
  1250. self.start(verbose=verbose, start_guid = gui, notify_function=notify_function)
  1251. except (IOError, OSError, QubesException) as err:
  1252. raise QubesException("Error while starting the '{0}' VM: {1}".format(self.name, err))
  1253. except (MemoryError) as err:
  1254. raise QubesException("Not enough memory to start '{0}' VM! "
  1255. "Close one or more running VMs and try "
  1256. "again.".format(self.name))
  1257. if self.is_paused():
  1258. raise QubesException("VM is paused")
  1259. if not self.is_qrexec_running():
  1260. raise QubesException(
  1261. "Domain '{}': qrexec not connected.".format(self.name))
  1262. if gui and os.getenv("DISPLAY") is not None and not self.is_guid_running():
  1263. self.start_guid(verbose = verbose, notify_function = notify_function)
  1264. args = [system_path["qrexec_client_path"], "-d", str(self.name), "%s:%s" % (user, command)]
  1265. if localcmd is not None:
  1266. args += [ "-l", localcmd]
  1267. if filter_esc:
  1268. args += ["-t"]
  1269. if os.isatty(sys.stderr.fileno()):
  1270. args += ["-T"]
  1271. call_kwargs = {}
  1272. if ignore_stderr or not passio:
  1273. null = open("/dev/null", "rw")
  1274. call_kwargs['stderr'] = null
  1275. if not passio:
  1276. call_kwargs['stdin'] = null
  1277. call_kwargs['stdout'] = null
  1278. if passio_popen:
  1279. popen_kwargs={'stdout': subprocess.PIPE}
  1280. popen_kwargs['stdin'] = subprocess.PIPE
  1281. if passio_stderr:
  1282. popen_kwargs['stderr'] = subprocess.PIPE
  1283. else:
  1284. popen_kwargs['stderr'] = call_kwargs.get('stderr', None)
  1285. p = subprocess.Popen (args, **popen_kwargs)
  1286. if null:
  1287. null.close()
  1288. return p
  1289. if not wait and not passio:
  1290. args += ["-e"]
  1291. retcode = subprocess.call(args, **call_kwargs)
  1292. if null:
  1293. null.close()
  1294. return retcode
  1295. def run_service(self, service, source="dom0", user=None,
  1296. passio_popen = False, input=None):
  1297. if input and passio_popen:
  1298. raise ValueError("'input' and 'passio_popen' cannot be used "
  1299. "together")
  1300. if input:
  1301. return self.run("QUBESRPC %s %s" % (service, source),
  1302. localcmd="echo %s" % input, user=user, wait=True)
  1303. else:
  1304. return self.run("QUBESRPC %s %s" % (service, source),
  1305. passio_popen=passio_popen, user=user, wait=True)
  1306. def attach_network(self, verbose = False, wait = True, netvm = None):
  1307. self.log.debug('attach_network(netvm={!r})'.format(netvm))
  1308. if dry_run:
  1309. return
  1310. if not self.is_running():
  1311. raise QubesException ("VM not running!")
  1312. if netvm is None:
  1313. netvm = self.netvm
  1314. if netvm is None:
  1315. raise QubesException ("NetVM not set!")
  1316. if netvm.qid != 0:
  1317. if not netvm.is_running():
  1318. if verbose:
  1319. print >> sys.stderr, "--> Starting NetVM {0}...".format(netvm.name)
  1320. netvm.start()
  1321. self.libvirt_domain.attachDevice(
  1322. self._format_net_dev(self.ip, self.mac, self.netvm.name))
  1323. def detach_network(self, verbose = False, netvm = None):
  1324. self.log.debug('detach_network(netvm={!r})'.format(netvm))
  1325. if dry_run:
  1326. return
  1327. if not self.is_running():
  1328. raise QubesException ("VM not running!")
  1329. if netvm is None:
  1330. netvm = self.netvm
  1331. if netvm is None:
  1332. raise QubesException ("NetVM not set!")
  1333. self.libvirt_domain.detachDevice( self._format_net_dev(self.ip,
  1334. self.mac, self.netvm.name))
  1335. def wait_for_session(self, notify_function = None):
  1336. self.log.debug('wait_for_session()')
  1337. #self.run('echo $$ >> /tmp/qubes-session-waiter; [ ! -f /tmp/qubes-session-env ] && exec sleep 365d', ignore_stderr=True, gui=False, wait=True)
  1338. # Note : User root is redefined to SYSTEM in the Windows agent code
  1339. p = self.run('QUBESRPC qubes.WaitForSession none', user="root", passio_popen=True, gui=False, wait=True)
  1340. p.communicate(input=self.default_user)
  1341. def start_guid(self, verbose = True, notify_function = None,
  1342. extra_guid_args=None, before_qrexec=False):
  1343. self.log.debug(
  1344. 'start_guid(extra_guid_args={!r}, before_qrexec={!r})'.format(
  1345. extra_guid_args, before_qrexec))
  1346. if verbose:
  1347. print >> sys.stderr, "--> Starting Qubes GUId..."
  1348. guid_cmd = [system_path["qubes_guid_path"],
  1349. "-d", str(self.xid), "-N", self.name,
  1350. "-c", self.label.color,
  1351. "-i", self.label.icon_path,
  1352. "-l", str(self.label.index)]
  1353. if extra_guid_args is not None:
  1354. guid_cmd += extra_guid_args
  1355. if self.debug:
  1356. guid_cmd += ['-v', '-v']
  1357. elif not verbose:
  1358. guid_cmd += ['-q']
  1359. retcode = subprocess.call (guid_cmd)
  1360. if (retcode != 0) :
  1361. raise QubesException("Cannot start qubes-guid!")
  1362. if not self.is_qrexec_running():
  1363. return
  1364. try:
  1365. import qubes.monitorlayoutnotify
  1366. if verbose:
  1367. print >> sys.stderr, "--> Sending monitor layout..."
  1368. monitor_layout = qubes.monitorlayoutnotify.get_monitor_layout()
  1369. qubes.monitorlayoutnotify.notify_vm(self, monitor_layout)
  1370. except ImportError as e:
  1371. print >>sys.stderr, "ERROR: %s" % e
  1372. if verbose:
  1373. print >> sys.stderr, "--> Waiting for qubes-session..."
  1374. self.wait_for_session(notify_function)
  1375. def start_qrexec_daemon(self, verbose = False, notify_function = None):
  1376. self.log.debug('start_qrexec_daemon()')
  1377. if verbose:
  1378. print >> sys.stderr, "--> Starting the qrexec daemon..."
  1379. qrexec_args = [str(self.xid), self.name, self.default_user]
  1380. if not verbose:
  1381. qrexec_args.insert(0, "-q")
  1382. qrexec_env = os.environ
  1383. qrexec_env['QREXEC_STARTUP_TIMEOUT'] = str(self.qrexec_timeout)
  1384. retcode = subprocess.call ([system_path["qrexec_daemon_path"]] +
  1385. qrexec_args, env=qrexec_env)
  1386. if (retcode != 0) :
  1387. raise OSError ("Cannot execute qrexec-daemon!")
  1388. def start_qubesdb(self):
  1389. self.log.debug('start_qubesdb()')
  1390. retcode = subprocess.call ([
  1391. system_path["qubesdb_daemon_path"],
  1392. str(self.xid),
  1393. self.name])
  1394. if retcode != 0:
  1395. self.force_shutdown()
  1396. raise OSError("ERROR: Cannot execute qubesdb-daemon!")
  1397. def start(self, verbose = False, preparing_dvm = False, start_guid = True,
  1398. notify_function = None, mem_required = None):
  1399. self.log.debug('start('
  1400. 'preparing_dvm={!r}, start_guid={!r}, mem_required={!r})'.format(
  1401. preparing_dvm, start_guid, mem_required))
  1402. if dry_run:
  1403. return
  1404. # Intentionally not used is_running(): eliminate also "Paused", "Crashed", "Halting"
  1405. if self.get_power_state() != "Halted":
  1406. raise QubesException ("VM is already running!")
  1407. self.verify_files()
  1408. if self.netvm is not None:
  1409. if self.netvm.qid != 0:
  1410. if not self.netvm.is_running():
  1411. if verbose:
  1412. print >> sys.stderr, "--> Starting NetVM {0}...".format(self.netvm.name)
  1413. self.netvm.start(verbose = verbose, start_guid = start_guid, notify_function = notify_function)
  1414. self.storage.prepare_for_vm_startup(verbose=verbose)
  1415. if verbose:
  1416. print >> sys.stderr, "--> Loading the VM (type = {0})...".format(self.type)
  1417. self._update_libvirt_domain()
  1418. if mem_required is None:
  1419. mem_required = int(self.memory) * 1024 * 1024
  1420. if qmemman_present:
  1421. qmemman_client = QMemmanClient()
  1422. try:
  1423. got_memory = qmemman_client.request_memory(mem_required)
  1424. except IOError as e:
  1425. raise IOError("ERROR: Failed to connect to qmemman: %s" % str(e))
  1426. if not got_memory:
  1427. qmemman_client.close()
  1428. raise MemoryError ("ERROR: insufficient memory to start VM '%s'" % self.name)
  1429. # Bind pci devices to pciback driver
  1430. for pci in self.pcidevs:
  1431. nd = vmm.libvirt_conn.nodeDeviceLookupByName('pci_0000_' + pci.replace(':','_').replace('.','_'))
  1432. try:
  1433. nd.dettach()
  1434. except libvirt.libvirtError:
  1435. if vmm.libvirt_conn.virConnGetLastError()[0] == libvirt.VIR_ERR_INTERNAL_ERROR:
  1436. # allready detached
  1437. pass
  1438. else:
  1439. raise
  1440. self.libvirt_domain.createWithFlags(libvirt.VIR_DOMAIN_START_PAUSED)
  1441. if verbose:
  1442. print >> sys.stderr, "--> Starting Qubes DB..."
  1443. self.start_qubesdb()
  1444. xid = self.xid
  1445. self.log.debug('xid={}'.format(xid))
  1446. if preparing_dvm:
  1447. self.services['qubes-dvm'] = True
  1448. if verbose:
  1449. print >> sys.stderr, "--> Setting Qubes DB info for the VM..."
  1450. self.create_qubesdb_entries()
  1451. if verbose:
  1452. print >> sys.stderr, "--> Updating firewall rules..."
  1453. netvm = self.netvm
  1454. while netvm is not None:
  1455. if netvm.is_proxyvm() and netvm.is_running():
  1456. netvm.write_iptables_qubesdb_entry()
  1457. netvm = netvm.netvm
  1458. # fire hooks
  1459. for hook in self.hooks_start:
  1460. hook(self, verbose = verbose, preparing_dvm = preparing_dvm,
  1461. start_guid = start_guid, notify_function = notify_function)
  1462. if verbose:
  1463. print >> sys.stderr, "--> Starting the VM..."
  1464. self.libvirt_domain.resume()
  1465. # close() is not really needed, because the descriptor is close-on-exec
  1466. # anyway, the reason to postpone close() is that possibly xl is not done
  1467. # constructing the domain after its main process exits
  1468. # so we close() when we know the domain is up
  1469. # the successful unpause is some indicator of it
  1470. if qmemman_present:
  1471. qmemman_client.close()
  1472. extra_guid_args = None
  1473. if preparing_dvm:
  1474. # Run GUI daemon in "invisible" mode, so applications started by
  1475. # prerun script will not disturb the user
  1476. extra_guid_args = ['-I']
  1477. elif not os.path.exists('/var/run/shm.id'):
  1478. # Start GUI daemon only when shmoverride is loaded; unless
  1479. # preparing DispVM, where it isn't needed because of "invisible"
  1480. # mode
  1481. start_guid = False
  1482. if self._start_guid_first and start_guid:
  1483. self.start_guid(verbose=verbose, notify_function=notify_function,
  1484. before_qrexec=True, extra_guid_args=extra_guid_args)
  1485. if not preparing_dvm:
  1486. self.start_qrexec_daemon(verbose=verbose,notify_function=notify_function)
  1487. if start_guid:
  1488. self.start_guid(verbose=verbose, notify_function=notify_function,
  1489. extra_guid_args=extra_guid_args)
  1490. return xid
  1491. def _cleanup_zombie_domains(self):
  1492. """
  1493. This function is workaround broken libxl (which leaves not fully
  1494. created domain on failure) and vchan on domain crash behaviour
  1495. @return: None
  1496. """
  1497. xc = self.get_xc_dominfo()
  1498. if xc and xc['dying'] == 1:
  1499. # GUID still running?
  1500. guid_pidfile = '/var/run/qubes/guid-running.%d' % xc['domid']
  1501. if os.path.exists(guid_pidfile):
  1502. guid_pid = open(guid_pidfile).read().strip()
  1503. os.kill(int(guid_pid), 15)
  1504. # qrexec still running?
  1505. if self.is_qrexec_running():
  1506. #TODO: kill qrexec daemon
  1507. pass
  1508. def shutdown(self, force=False, xid = None):
  1509. self.log.debug('shutdown()')
  1510. if dry_run:
  1511. return
  1512. if not self.is_running():
  1513. raise QubesException ("VM already stopped!")
  1514. self.libvirt_domain.shutdown()
  1515. def force_shutdown(self, xid = None):
  1516. self.log.debug('force_shutdown()')
  1517. if dry_run:
  1518. return
  1519. if not self.is_running() and not self.is_paused():
  1520. raise QubesException ("VM already stopped!")
  1521. self.libvirt_domain.destroy()
  1522. self.refresh()
  1523. def suspend(self):
  1524. self.log.debug('suspend()')
  1525. if dry_run:
  1526. return
  1527. if not self.is_running() and not self.is_paused() or \
  1528. self.get_power_state() == "Suspended":
  1529. raise QubesException ("VM not running!")
  1530. if len (self.pcidevs) > 0:
  1531. self.libvirt_domain.pMSuspendForDuration(
  1532. libvirt.VIR_NODE_SUSPEND_TARGET_MEM, 0, 0)
  1533. else:
  1534. self.pause()
  1535. def resume(self):
  1536. self.log.debug('resume()')
  1537. if dry_run:
  1538. return
  1539. if self.get_power_state() == "Suspended":
  1540. self.libvirt_domain.pMWakeup()
  1541. else:
  1542. self.unpause()
  1543. def pause(self):
  1544. self.log.debug('pause()')
  1545. if dry_run:
  1546. return
  1547. if not self.is_running():
  1548. raise QubesException ("VM not running!")
  1549. self.libvirt_domain.suspend()
  1550. def unpause(self):
  1551. self.log.debug('unpause()')
  1552. if dry_run:
  1553. return
  1554. if not self.is_paused():
  1555. raise QubesException ("VM not paused!")
  1556. self.libvirt_domain.resume()
  1557. def get_xml_attrs(self):
  1558. attrs = {}
  1559. attrs_config = self.get_attrs_config()
  1560. for attr in attrs_config:
  1561. attr_config = attrs_config[attr]
  1562. if 'save' in attr_config:
  1563. if 'save_skip' in attr_config:
  1564. if callable(attr_config['save_skip']):
  1565. if attr_config['save_skip']():
  1566. continue
  1567. elif eval(attr_config['save_skip']):
  1568. continue
  1569. if callable(attr_config['save']):
  1570. value = attr_config['save']()
  1571. else:
  1572. value = eval(attr_config['save'])
  1573. if 'save_attr' in attr_config:
  1574. attrs[attr_config['save_attr']] = value
  1575. else:
  1576. attrs[attr] = value
  1577. return attrs
  1578. def create_xml_element(self):
  1579. attrs = self.get_xml_attrs()
  1580. element = lxml.etree.Element(
  1581. # Compatibility hack (Qubes*VM in type vs Qubes*Vm in XML)...
  1582. "Qubes" + self.type.replace("VM", "Vm"),
  1583. **attrs)
  1584. return element
  1585. register_qubes_vm_class(QubesVm)