000QubesVm.py 68 KB

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