000QubesVm.py 80 KB

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