000QubesVm.py 65 KB

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