000QubesVm.py 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158
  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. "ends with '-dm', 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. if name.endswith('-dm'):
  505. # avoid conflict with device model stubdomain names for HVMs
  506. return False
  507. return re.match(r"^[a-zA-Z][a-zA-Z0-9_.-]*$", name) is not None
  508. def pre_rename(self, new_name):
  509. if self.autostart:
  510. subprocess.check_call(['sudo', 'systemctl', '-q', 'disable',
  511. 'qubes-vm@{}.service'.format(self.name)])
  512. # fire hooks
  513. for hook in self.hooks_pre_rename:
  514. hook(self, new_name)
  515. def set_name(self, name):
  516. self.log.debug('name = {!r}'.format(name))
  517. if self.is_running():
  518. raise QubesException("Cannot change name of running VM!")
  519. if not self.verify_name(name):
  520. raise QubesException("Invalid VM name")
  521. if self.installed_by_rpm:
  522. raise QubesException("Cannot rename VM installed by RPM -- first clone VM and then use yum to remove package.")
  523. assert self._collection is not None
  524. if self._collection.get_vm_by_name(name):
  525. raise QubesException("VM with this name already exists")
  526. self.pre_rename(name)
  527. try:
  528. self.libvirt_domain.undefine()
  529. except libvirt.libvirtError as e:
  530. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  531. pass
  532. else:
  533. raise
  534. if self._qdb_connection:
  535. self._qdb_connection.close()
  536. self._qdb_connection = None
  537. new_conf = os.path.join(self.dir_path, name + '.conf')
  538. if os.path.exists(self.conf_file):
  539. os.rename(self.conf_file, new_conf)
  540. old_dirpath = self.dir_path
  541. self.storage.rename(self.name, name)
  542. new_dirpath = self.storage.vmdir
  543. self.dir_path = new_dirpath
  544. old_name = self.name
  545. self.name = name
  546. if self.conf_file is not None:
  547. self.conf_file = new_conf.replace(old_dirpath, new_dirpath)
  548. if self.icon_path is not None:
  549. self.icon_path = self.icon_path.replace(old_dirpath, new_dirpath)
  550. if hasattr(self, 'kernels_dir') and self.kernels_dir is not None:
  551. self.kernels_dir = self.kernels_dir.replace(old_dirpath, new_dirpath)
  552. if self.firewall_conf is not None:
  553. self.firewall_conf = self.firewall_conf.replace(old_dirpath,
  554. new_dirpath)
  555. self._update_libvirt_domain()
  556. self.post_rename(old_name)
  557. def post_rename(self, old_name):
  558. if self.autostart:
  559. # force setter to be called again
  560. self.autostart = self.autostart
  561. # fire hooks
  562. for hook in self.hooks_post_rename:
  563. hook(self, old_name)
  564. @property
  565. def internal(self):
  566. return self._internal
  567. @internal.setter
  568. def internal(self, value):
  569. oldvalue = self._internal
  570. self._internal = value
  571. self.post_set_attr('internal', value, oldvalue)
  572. @property
  573. def dispvm_netvm(self):
  574. if self.uses_default_dispvm_netvm:
  575. return self.netvm
  576. else:
  577. if isinstance(self._dispvm_netvm, int):
  578. return self._collection[self._dispvm_netvm]
  579. else:
  580. return self._dispvm_netvm
  581. @dispvm_netvm.setter
  582. def dispvm_netvm(self, value):
  583. if value and not value.is_netvm():
  584. raise ValueError("Vm {!r} does not provide network".format(
  585. value))
  586. self._dispvm_netvm = value
  587. @property
  588. def autostart(self):
  589. return self._autostart
  590. @autostart.setter
  591. def autostart(self, value):
  592. if value:
  593. retcode = subprocess.call(["sudo", "ln", "-sf",
  594. "/usr/lib/systemd/system/qubes-vm@.service",
  595. "/etc/systemd/system/multi-user.target.wants/qubes-vm@%s.service" % self.name])
  596. else:
  597. retcode = subprocess.call(["sudo", "systemctl", "disable", "qubes-vm@%s.service" % self.name])
  598. if retcode != 0:
  599. raise QubesException("Failed to set autostart for VM via systemctl")
  600. self._autostart = bool(value)
  601. @classmethod
  602. def is_template_compatible(cls, template):
  603. """Check if given VM can be a template for this VM"""
  604. # FIXME: check if the value is instance of QubesTemplateVM, not the VM
  605. # type. The problem is while this file is loaded, QubesTemplateVM is
  606. # not defined yet.
  607. if template and (not template.is_template() or template.type != "TemplateVM"):
  608. return False
  609. return True
  610. @property
  611. def template(self):
  612. return self._template
  613. @template.setter
  614. def template(self, value):
  615. if self._template is None and value is not None:
  616. raise QubesException("Cannot set template for standalone VM")
  617. if value and not self.is_template_compatible(value):
  618. raise QubesException("Incompatible template type %s with VM of type %s" % (value.type, self.type))
  619. self._template = value
  620. def is_template(self):
  621. return False
  622. def is_appvm(self):
  623. return False
  624. def is_netvm(self):
  625. return False
  626. def is_proxyvm(self):
  627. return False
  628. def is_disposablevm(self):
  629. return False
  630. @property
  631. def qdb(self):
  632. if self._qdb_connection is None:
  633. from qubes.qdb import QubesDB
  634. self._qdb_connection = QubesDB(self.name)
  635. return self._qdb_connection
  636. @property
  637. def xid(self):
  638. try:
  639. return self.libvirt_domain.ID()
  640. except libvirt.libvirtError as e:
  641. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  642. return -1
  643. else:
  644. print >>sys.stderr, "libvirt error code: {!r}".format(
  645. e.get_error_code())
  646. raise
  647. def get_xid(self):
  648. # obsoleted
  649. return self.xid
  650. def _update_libvirt_domain(self):
  651. domain_config = self.create_config_file()
  652. try:
  653. self._libvirt_domain = vmm.libvirt_conn.defineXML(domain_config)
  654. except libvirt.libvirtError as e:
  655. # shouldn't this be in QubesHVm implementation?
  656. if e.get_error_code() == libvirt.VIR_ERR_OS_TYPE and \
  657. e.get_str2() == 'hvm':
  658. raise QubesException("HVM domains not supported on this "
  659. "machine. Check BIOS settings for "
  660. "VT-x/AMD-V extensions.")
  661. else:
  662. raise e
  663. self.uuid = uuid.UUID(bytes=self._libvirt_domain.UUID())
  664. @property
  665. def libvirt_domain(self):
  666. if self._libvirt_domain is None:
  667. if self.uuid is not None:
  668. self._libvirt_domain = vmm.libvirt_conn.lookupByUUID(self.uuid.bytes)
  669. else:
  670. self._libvirt_domain = vmm.libvirt_conn.lookupByName(self.name)
  671. self.uuid = uuid.UUID(bytes=self._libvirt_domain.UUID())
  672. return self._libvirt_domain
  673. def get_uuid(self):
  674. # obsoleted
  675. return self.uuid
  676. def refresh(self):
  677. self._libvirt_domain = None
  678. self._qdb_connection = None
  679. def get_mem(self):
  680. if dry_run:
  681. return 666
  682. try:
  683. if not self.libvirt_domain.isActive():
  684. return 0
  685. return self.libvirt_domain.info()[1]
  686. except libvirt.libvirtError as e:
  687. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  688. return 0
  689. # libxl_domain_info failed - domain no longer exists
  690. elif e.get_error_code() == libvirt.VIR_ERR_INTERNAL_ERROR:
  691. return 0
  692. elif e.get_error_code() is None: # unknown...
  693. return 0
  694. else:
  695. print >>sys.stderr, "libvirt error code: {!r}".format(
  696. e.get_error_code())
  697. raise
  698. def get_cputime(self):
  699. if dry_run:
  700. return 666
  701. try:
  702. if not self.libvirt_domain.isActive():
  703. return 0
  704. return self.libvirt_domain.info()[4]
  705. except libvirt.libvirtError as e:
  706. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  707. return 0
  708. # libxl_domain_info failed - domain no longer exists
  709. elif e.get_error_code() == libvirt.VIR_ERR_INTERNAL_ERROR:
  710. return 0
  711. elif e.get_error_code() is None: # unknown...
  712. return 0
  713. else:
  714. print >>sys.stderr, "libvirt error code: {!r}".format(
  715. e.get_error_code())
  716. raise
  717. def get_mem_static_max(self):
  718. if dry_run:
  719. return 666
  720. try:
  721. return self.libvirt_domain.maxMemory()
  722. except libvirt.libvirtError as e:
  723. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  724. return 0
  725. else:
  726. raise
  727. def get_prefmem(self):
  728. # TODO: qmemman is still xen specific
  729. untrusted_meminfo_key = vmm.xs.read('',
  730. '/local/domain/%s/memory/meminfo'
  731. % self.xid)
  732. if untrusted_meminfo_key is None or untrusted_meminfo_key == '':
  733. return 0
  734. domain = qmemman.DomainState(self.xid)
  735. qmemman_algo.refresh_meminfo_for_domain(domain, untrusted_meminfo_key)
  736. domain.memory_maximum = self.get_mem_static_max()*1024
  737. return qmemman_algo.prefmem(domain)/1024
  738. def get_per_cpu_time(self):
  739. if dry_run:
  740. import random
  741. return random.random() * 100
  742. try:
  743. if self.libvirt_domain.isActive():
  744. return self.libvirt_domain.getCPUStats(
  745. libvirt.VIR_NODE_CPU_STATS_ALL_CPUS, 0)[0]['cpu_time']/10**9
  746. else:
  747. return 0
  748. except libvirt.libvirtError as e:
  749. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  750. return 0
  751. else:
  752. print >>sys.stderr, "libvirt error code: {!r}".format(
  753. e.get_error_code())
  754. raise
  755. def get_disk_utilization_root_img(self):
  756. return qubes.qubesutils.get_disk_usage(self.root_img)
  757. def get_root_img_sz(self):
  758. if not os.path.exists(self.root_img):
  759. return 0
  760. return os.path.getsize(self.root_img)
  761. def get_power_state(self):
  762. if dry_run:
  763. return "NA"
  764. try:
  765. libvirt_domain = self.libvirt_domain
  766. if libvirt_domain.isActive():
  767. if libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PAUSED:
  768. return "Paused"
  769. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_CRASHED:
  770. return "Crashed"
  771. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_SHUTDOWN:
  772. return "Halting"
  773. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_SHUTOFF:
  774. return "Dying"
  775. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PMSUSPENDED:
  776. return "Suspended"
  777. else:
  778. if not self.is_fully_usable():
  779. return "Transient"
  780. else:
  781. return "Running"
  782. else:
  783. return 'Halted'
  784. except libvirt.libvirtError as e:
  785. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  786. return "Halted"
  787. else:
  788. raise
  789. def is_guid_running(self):
  790. xid = self.xid
  791. if xid < 0:
  792. return False
  793. if not os.path.exists('/var/run/qubes/guid-running.%d' % xid):
  794. return False
  795. return True
  796. def is_qrexec_running(self):
  797. if self.xid < 0:
  798. return False
  799. return os.path.exists('/var/run/qubes/qrexec.%s' % self.name)
  800. def is_fully_usable(self):
  801. # Running gui-daemon implies also VM running
  802. if not self.is_guid_running():
  803. return False
  804. if not self.is_qrexec_running():
  805. return False
  806. return True
  807. def is_running(self):
  808. if vmm.offline_mode:
  809. return False
  810. try:
  811. if self.libvirt_domain.isActive():
  812. return True
  813. else:
  814. return False
  815. except libvirt.libvirtError as e:
  816. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  817. return False
  818. # libxl_domain_info failed - domain no longer exists
  819. elif e.get_error_code() == libvirt.VIR_ERR_INTERNAL_ERROR:
  820. return False
  821. elif e.get_error_code() is None: # unknown...
  822. return False
  823. else:
  824. print >>sys.stderr, "libvirt error code: {!r}".format(
  825. e.get_error_code())
  826. raise
  827. def is_paused(self):
  828. try:
  829. if self.libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PAUSED:
  830. return True
  831. else:
  832. return False
  833. except libvirt.libvirtError as e:
  834. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  835. return False
  836. # libxl_domain_info failed - domain no longer exists
  837. elif e.get_error_code() == libvirt.VIR_ERR_INTERNAL_ERROR:
  838. return False
  839. elif e.get_error_code() is None: # unknown...
  840. return False
  841. else:
  842. print >>sys.stderr, "libvirt error code: {!r}".format(
  843. e.get_error_code())
  844. raise
  845. def get_start_time(self):
  846. if not self.is_running():
  847. return None
  848. # TODO
  849. uuid = self.uuid
  850. start_time = vmm.xs.read('', "/vm/%s/start_time" % str(uuid))
  851. if start_time:
  852. return datetime.datetime.fromtimestamp(float(start_time))
  853. else:
  854. return None
  855. def is_outdated(self):
  856. # Makes sense only on VM based on template
  857. if self.template is None:
  858. return False
  859. if not self.is_running():
  860. return False
  861. if not hasattr(self.template, 'rootcow_img'):
  862. return False
  863. rootimg_inode = os.stat(self.template.root_img)
  864. try:
  865. rootcow_inode = os.stat(self.template.rootcow_img)
  866. except OSError:
  867. # The only case when rootcow_img doesn't exists is in the middle of
  868. # commit_changes, so VM is outdated right now
  869. return True
  870. current_dmdev = "/dev/mapper/snapshot-{0:x}:{1}-{2:x}:{3}".format(
  871. rootimg_inode[2], rootimg_inode[1],
  872. rootcow_inode[2], rootcow_inode[1])
  873. # FIXME
  874. # 51712 (0xCA00) is xvda
  875. # backend node name not available through xenapi :(
  876. used_dmdev = vmm.xs.read('', "/local/domain/0/backend/vbd/{0}/51712/node".format(self.xid))
  877. return used_dmdev != current_dmdev
  878. @property
  879. def private_img(self):
  880. return self.storage.private_img
  881. @property
  882. def root_img(self):
  883. return self.storage.root_img
  884. @property
  885. def volatile_img(self):
  886. return self.storage.volatile_img
  887. def get_disk_utilization(self):
  888. return qubes.qubesutils.get_disk_usage(self.dir_path)
  889. def get_disk_utilization_private_img(self):
  890. return qubes.qubesutils.get_disk_usage(self.private_img)
  891. def get_private_img_sz(self):
  892. return self.storage.get_private_img_sz()
  893. def resize_private_img(self, size):
  894. assert size >= self.get_private_img_sz(), "Cannot shrink private.img"
  895. # resize the image
  896. self.storage.resize_private_img(size)
  897. # and then the filesystem
  898. retcode = 0
  899. if self.is_running():
  900. retcode = self.run("while [ \"`blockdev --getsize64 /dev/xvdb`\" -lt {0} ]; do ".format(size) +
  901. "head /dev/xvdb > /dev/null; sleep 0.2; done; resize2fs /dev/xvdb", user="root", wait=True)
  902. if retcode != 0:
  903. raise QubesException("resize2fs failed")
  904. # FIXME: should be outside of QubesVM?
  905. def get_timezone(self):
  906. # fc18
  907. if os.path.islink('/etc/localtime'):
  908. return '/'.join(os.readlink('/etc/localtime').split('/')[-2:])
  909. # <=fc17
  910. elif os.path.exists('/etc/sysconfig/clock'):
  911. clock_config = open('/etc/sysconfig/clock', "r")
  912. clock_config_lines = clock_config.readlines()
  913. clock_config.close()
  914. zone_re = re.compile(r'^ZONE="(.*)"')
  915. for line in clock_config_lines:
  916. line_match = zone_re.match(line)
  917. if line_match:
  918. return line_match.group(1)
  919. else:
  920. # last resort way, some applications makes /etc/localtime
  921. # hardlink instead of symlink...
  922. tz_info = os.stat('/etc/localtime')
  923. if not tz_info:
  924. return None
  925. if tz_info.st_nlink > 1:
  926. p = subprocess.Popen(['find', '/usr/share/zoneinfo',
  927. '-inum', str(tz_info.st_ino),
  928. '-print', '-quit'],
  929. stdout=subprocess.PIPE)
  930. tz_path = p.communicate()[0].strip()
  931. return tz_path.replace('/usr/share/zoneinfo/', '')
  932. return None
  933. def cleanup_vifs(self):
  934. """
  935. Xend does not remove vif when backend domain is down, so we must do it
  936. manually
  937. """
  938. # FIXME: remove this?
  939. if not self.is_running():
  940. return
  941. dev_basepath = '/local/domain/%d/device/vif' % self.xid
  942. for dev in (vmm.xs.ls('', dev_basepath) or []):
  943. # check if backend domain is alive
  944. backend_xid = int(vmm.xs.read('', '%s/%s/backend-id' % (dev_basepath, dev)))
  945. if backend_xid in vmm.libvirt_conn.listDomainsID():
  946. # check if device is still active
  947. if vmm.xs.read('', '%s/%s/state' % (dev_basepath, dev)) == '4':
  948. continue
  949. # remove dead device
  950. vmm.xs.rm('', '%s/%s' % (dev_basepath, dev))
  951. def create_qubesdb_entries(self):
  952. if dry_run:
  953. return
  954. self.qdb.write("/name", self.name)
  955. self.qdb.write("/qubes-vm-type", self.type)
  956. self.qdb.write("/qubes-vm-updateable", str(self.updateable))
  957. self.qdb.write("/qubes-vm-persistence",
  958. "full" if self.updateable else "rw-only")
  959. self.qdb.write("/qubes-base-template",
  960. self.template.name if self.template else '')
  961. if self.is_netvm():
  962. self.qdb.write("/qubes-netvm-gateway", self.gateway)
  963. self.qdb.write("/qubes-netvm-primary-dns", self.gateway)
  964. self.qdb.write("/qubes-netvm-secondary-dns", self.secondary_dns)
  965. self.qdb.write("/qubes-netvm-netmask", self.netmask)
  966. self.qdb.write("/qubes-netvm-network", self.network)
  967. if self.netvm is not None:
  968. self.qdb.write("/qubes-ip", self.ip)
  969. self.qdb.write("/qubes-netmask", self.netvm.netmask)
  970. self.qdb.write("/qubes-gateway", self.netvm.gateway)
  971. self.qdb.write("/qubes-primary-dns", self.netvm.gateway)
  972. self.qdb.write("/qubes-secondary-dns", self.netvm.secondary_dns)
  973. tzname = self.get_timezone()
  974. if tzname:
  975. self.qdb.write("/qubes-timezone", tzname)
  976. for srv in self.services.keys():
  977. # convert True/False to "1"/"0"
  978. self.qdb.write("/qubes-service/{0}".format(srv),
  979. str(int(self.services[srv])))
  980. self.qdb.write("/qubes-block-devices", '')
  981. self.qdb.write("/qubes-usb-devices", '')
  982. self.qdb.write("/qubes-debug-mode", str(int(self.debug)))
  983. self.provide_random_seed_to_vm()
  984. # TODO: Currently the whole qmemman is quite Xen-specific, so stay with
  985. # xenstore for it until decided otherwise
  986. if qmemman_present:
  987. vmm.xs.set_permissions('', '/local/domain/{0}/memory'.format(self.xid),
  988. [{ 'dom': self.xid }])
  989. # fire hooks
  990. for hook in self.hooks_create_qubesdb_entries:
  991. hook(self)
  992. def provide_random_seed_to_vm(self):
  993. f = open('/dev/urandom', 'r')
  994. s = f.read(64)
  995. if len(s) != 64:
  996. raise IOError("failed to read seed from /dev/urandom")
  997. f.close()
  998. self.qdb.write("/qubes-random-seed", base64.b64encode(hashlib.sha512(s).digest()))
  999. def _format_net_dev(self, ip, mac, backend):
  1000. template = " <interface type='ethernet'>\n" \
  1001. " <mac address='{mac}'/>\n" \
  1002. " <ip address='{ip}'/>\n" \
  1003. " <script path='vif-route-qubes'/>\n" \
  1004. " <backenddomain name='{backend}'/>\n" \
  1005. " </interface>\n"
  1006. return template.format(ip=ip, mac=mac, backend=backend)
  1007. def _format_pci_dev(self, address):
  1008. template = " <hostdev type='pci' managed='yes'{strictreset}>\n" \
  1009. " <source>\n" \
  1010. " <address bus='0x{bus}' slot='0x{slot}' function='0x{fun}'/>\n" \
  1011. " </source>\n" \
  1012. " </hostdev>\n"
  1013. dev_match = re.match('([0-9a-f]+):([0-9a-f]+)\.([0-9a-f]+)', address)
  1014. if not dev_match:
  1015. raise QubesException("Invalid PCI device address: %s" % address)
  1016. return template.format(
  1017. bus=dev_match.group(1),
  1018. slot=dev_match.group(2),
  1019. fun=dev_match.group(3),
  1020. strictreset=("" if self.pci_strictreset else
  1021. " nostrictreset='yes'"),
  1022. )
  1023. def get_config_params(self):
  1024. args = {}
  1025. args['name'] = self.name
  1026. if hasattr(self, 'kernels_dir'):
  1027. args['kerneldir'] = self.kernels_dir
  1028. args['uuidnode'] = "<uuid>%s</uuid>" % str(self.uuid) if self.uuid else ""
  1029. args['vmdir'] = self.dir_path
  1030. args['pcidevs'] = ''.join(map(self._format_pci_dev, self.pcidevs))
  1031. args['mem'] = str(self.memory)
  1032. if self.maxmem < self.memory:
  1033. args['mem'] = str(self.maxmem)
  1034. args['maxmem'] = str(self.maxmem)
  1035. if 'meminfo-writer' in self.services and not self.services['meminfo-writer']:
  1036. # If dynamic memory management disabled, set maxmem=mem
  1037. args['maxmem'] = args['mem']
  1038. args['vcpus'] = str(self.vcpus)
  1039. args['features'] = ''
  1040. if self.netvm is not None:
  1041. args['ip'] = self.ip
  1042. args['mac'] = self.mac
  1043. args['gateway'] = self.netvm.gateway
  1044. args['dns1'] = self.netvm.gateway
  1045. args['dns2'] = self.secondary_dns
  1046. args['netmask'] = self.netmask
  1047. args['netdev'] = self._format_net_dev(self.ip, self.mac, self.netvm.name)
  1048. args['network_begin'] = ''
  1049. args['network_end'] = ''
  1050. args['no_network_begin'] = '<!--'
  1051. args['no_network_end'] = '-->'
  1052. else:
  1053. args['ip'] = ''
  1054. args['mac'] = ''
  1055. args['gateway'] = ''
  1056. args['dns1'] = ''
  1057. args['dns2'] = ''
  1058. args['netmask'] = ''
  1059. args['netdev'] = ''
  1060. args['network_begin'] = '<!--'
  1061. args['network_end'] = '-->'
  1062. args['no_network_begin'] = ''
  1063. args['no_network_end'] = ''
  1064. if len(self.pcidevs) and self.pci_e820_host:
  1065. args['features'] = '<xen><e820_host state=\'on\'/></xen>'
  1066. args.update(self.storage.get_config_params())
  1067. if hasattr(self, 'kernelopts'):
  1068. args['kernelopts'] = self.kernelopts
  1069. if self.debug:
  1070. print >> sys.stderr, "--> Debug mode: adding 'earlyprintk=xen' to kernel opts"
  1071. args['kernelopts'] += ' earlyprintk=xen'
  1072. # fire hooks
  1073. for hook in self.hooks_get_config_params:
  1074. args = hook(self, args)
  1075. return args
  1076. @property
  1077. def uses_custom_config(self):
  1078. return self.conf_file != self.absolute_path(self.name + ".conf", None)
  1079. def create_config_file(self, file_path = None, prepare_dvm = False):
  1080. if file_path is None:
  1081. file_path = self.conf_file
  1082. if self.uses_custom_config:
  1083. conf_appvm = open(file_path, "r")
  1084. domain_config = conf_appvm.read()
  1085. conf_appvm.close()
  1086. return domain_config
  1087. f_conf_template = open(self.config_file_template, 'r')
  1088. conf_template = f_conf_template.read()
  1089. f_conf_template.close()
  1090. template_params = self.get_config_params()
  1091. if prepare_dvm:
  1092. template_params['name'] = '%NAME%'
  1093. template_params['privatedev'] = ''
  1094. template_params['netdev'] = re.sub(r"address='[0-9.]*'", "address='%IP%'", template_params['netdev'])
  1095. domain_config = conf_template.format(**template_params)
  1096. # FIXME: This is only for debugging purposes
  1097. old_umask = os.umask(002)
  1098. try:
  1099. if os.path.exists(file_path):
  1100. os.unlink(file_path)
  1101. conf_appvm = open(file_path, "w")
  1102. conf_appvm.write(domain_config)
  1103. conf_appvm.close()
  1104. except:
  1105. # Ignore errors
  1106. pass
  1107. finally:
  1108. os.umask(old_umask)
  1109. return domain_config
  1110. def create_on_disk(self, verbose=False, source_template = None):
  1111. self.log.debug('create_on_disk(source_template={!r})'.format(
  1112. source_template))
  1113. if source_template is None:
  1114. source_template = self.template
  1115. assert source_template is not None
  1116. if dry_run:
  1117. return
  1118. self.storage.create_on_disk(verbose, source_template)
  1119. if self.updateable:
  1120. kernels_dir = source_template.kernels_dir
  1121. if verbose:
  1122. print >> sys.stderr, "--> Copying the kernel (set kernel \"none\" to use it): {0}".\
  1123. format(kernels_dir)
  1124. os.mkdir (self.dir_path + '/kernels')
  1125. for f in ("vmlinuz", "initramfs", "modules.img"):
  1126. shutil.copy(os.path.join(kernels_dir, f),
  1127. os.path.join(self.dir_path, vm_files["kernels_subdir"], f))
  1128. if verbose:
  1129. print >> sys.stderr, "--> Creating icon symlink: {0} -> {1}".format(self.icon_path, self.label.icon_path)
  1130. if hasattr(os, "symlink"):
  1131. os.symlink (self.label.icon_path, self.icon_path)
  1132. else:
  1133. shutil.copy(self.label.icon_path, self.icon_path)
  1134. # Make sure that we have UUID allocated
  1135. if not vmm.offline_mode:
  1136. self._update_libvirt_domain()
  1137. else:
  1138. self.uuid = uuid.uuid4()
  1139. # fire hooks
  1140. for hook in self.hooks_create_on_disk:
  1141. hook(self, verbose, source_template=source_template)
  1142. def get_clone_attrs(self):
  1143. attrs = ['kernel', 'uses_default_kernel', 'netvm', 'uses_default_netvm',
  1144. 'memory', 'maxmem', 'kernelopts', 'uses_default_kernelopts',
  1145. 'services', 'vcpus', '_mac', 'pcidevs', 'include_in_backups',
  1146. '_label', 'default_user', 'qrexec_timeout']
  1147. # fire hooks
  1148. for hook in self.hooks_get_clone_attrs:
  1149. attrs = hook(self, attrs)
  1150. return attrs
  1151. def clone_attrs(self, src_vm, fail_on_error=True):
  1152. self._do_not_reset_firewall = True
  1153. for prop in self.get_clone_attrs():
  1154. try:
  1155. val = getattr(src_vm, prop)
  1156. if isinstance(val, dict):
  1157. val = val.copy()
  1158. setattr(self, prop, val)
  1159. except Exception as e:
  1160. if fail_on_error:
  1161. self._do_not_reset_firewall = False
  1162. raise
  1163. else:
  1164. print >>sys.stderr, "WARNING: %s" % str(e)
  1165. self._do_not_reset_firewall = False
  1166. def clone_disk_files(self, src_vm, verbose):
  1167. if dry_run:
  1168. return
  1169. if src_vm.is_running():
  1170. raise QubesException("Attempt to clone a running VM!")
  1171. self.storage.clone_disk_files(src_vm, verbose)
  1172. if src_vm.icon_path is not None and self.icon_path is not None:
  1173. if os.path.exists (src_vm.dir_path):
  1174. if os.path.islink(src_vm.icon_path):
  1175. icon_path = os.readlink(src_vm.icon_path)
  1176. if verbose:
  1177. print >> sys.stderr, "--> Creating icon symlink: {0} -> {1}".format(self.icon_path, icon_path)
  1178. os.symlink (icon_path, self.icon_path)
  1179. else:
  1180. if verbose:
  1181. print >> sys.stderr, "--> Copying icon: {0} -> {1}".format(src_vm.icon_path, self.icon_path)
  1182. shutil.copy(src_vm.icon_path, self.icon_path)
  1183. if src_vm.has_firewall():
  1184. self.write_firewall_conf(src_vm.get_firewall_conf())
  1185. # Make sure that we have UUID allocated
  1186. self._update_libvirt_domain()
  1187. # fire hooks
  1188. for hook in self.hooks_clone_disk_files:
  1189. hook(self, src_vm, verbose)
  1190. def verify_files(self):
  1191. if dry_run:
  1192. return
  1193. self.storage.verify_files()
  1194. if not os.path.exists (os.path.join(self.kernels_dir, 'vmlinuz')):
  1195. raise QubesException (
  1196. "VM kernel does not exist: {0}".\
  1197. format(os.path.join(self.kernels_dir, 'vmlinuz')))
  1198. if not os.path.exists (os.path.join(self.kernels_dir, 'initramfs')):
  1199. raise QubesException (
  1200. "VM initramfs does not exist: {0}".\
  1201. format(os.path.join(self.kernels_dir, 'initramfs')))
  1202. # fire hooks
  1203. for hook in self.hooks_verify_files:
  1204. hook(self)
  1205. return True
  1206. def remove_from_disk(self):
  1207. self.log.debug('remove_from_disk()')
  1208. if dry_run:
  1209. return
  1210. # fire hooks
  1211. for hook in self.hooks_remove_from_disk:
  1212. hook(self)
  1213. try:
  1214. self.libvirt_domain.undefine()
  1215. except libvirt.libvirtError as e:
  1216. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  1217. # already undefined
  1218. pass
  1219. else:
  1220. print >>sys.stderr, "libvirt error code: {!r}".format(
  1221. e.get_error_code())
  1222. raise
  1223. if os.path.exists("/etc/systemd/system/multi-user.target.wants/qubes-vm@" + self.name + ".service"):
  1224. retcode = subprocess.call(["sudo", "systemctl", "-q", "disable",
  1225. "qubes-vm@" + self.name + ".service"])
  1226. if retcode != 0:
  1227. raise QubesException("Failed to delete autostart entry for VM")
  1228. self.storage.remove_from_disk()
  1229. def write_firewall_conf(self, conf):
  1230. defaults = self.get_firewall_conf()
  1231. expiring_rules_present = False
  1232. for item in defaults.keys():
  1233. if item not in conf:
  1234. conf[item] = defaults[item]
  1235. root = lxml.etree.Element(
  1236. "QubesFirewallRules",
  1237. policy = "allow" if conf["allow"] else "deny",
  1238. dns = "allow" if conf["allowDns"] else "deny",
  1239. icmp = "allow" if conf["allowIcmp"] else "deny",
  1240. yumProxy = "allow" if conf["allowYumProxy"] else "deny"
  1241. )
  1242. for rule in conf["rules"]:
  1243. # For backward compatibility
  1244. if "proto" not in rule:
  1245. if rule["portBegin"] is not None and rule["portBegin"] > 0:
  1246. rule["proto"] = "tcp"
  1247. else:
  1248. rule["proto"] = "any"
  1249. element = lxml.etree.Element(
  1250. "rule",
  1251. address=rule["address"],
  1252. proto=str(rule["proto"]),
  1253. )
  1254. if rule["netmask"] is not None and rule["netmask"] != 32:
  1255. element.set("netmask", str(rule["netmask"]))
  1256. if rule.get("portBegin", None) is not None and \
  1257. rule["portBegin"] > 0:
  1258. element.set("port", str(rule["portBegin"]))
  1259. if rule.get("portEnd", None) is not None and rule["portEnd"] > 0:
  1260. element.set("toport", str(rule["portEnd"]))
  1261. if "expire" in rule:
  1262. element.set("expire", str(rule["expire"]))
  1263. expiring_rules_present = True
  1264. root.append(element)
  1265. tree = lxml.etree.ElementTree(root)
  1266. try:
  1267. old_umask = os.umask(002)
  1268. with open(self.firewall_conf, 'w') as f:
  1269. tree.write(f, encoding="UTF-8", pretty_print=True)
  1270. f.close()
  1271. os.umask(old_umask)
  1272. except EnvironmentError as err:
  1273. print >> sys.stderr, "{0}: save error: {1}".format(
  1274. os.path.basename(sys.argv[0]), err)
  1275. return False
  1276. # Automatically enable/disable 'yum-proxy-setup' service based on allowYumProxy
  1277. if conf['allowYumProxy']:
  1278. self.services['yum-proxy-setup'] = True
  1279. else:
  1280. if self.services.has_key('yum-proxy-setup'):
  1281. self.services.pop('yum-proxy-setup')
  1282. if expiring_rules_present:
  1283. subprocess.call(["sudo", "systemctl", "start",
  1284. "qubes-reload-firewall@%s.timer" % self.name])
  1285. return True
  1286. def has_firewall(self):
  1287. return os.path.exists (self.firewall_conf)
  1288. def get_firewall_defaults(self):
  1289. return { "rules": list(), "allow": True, "allowDns": True, "allowIcmp": True, "allowYumProxy": False }
  1290. def get_firewall_conf(self):
  1291. conf = self.get_firewall_defaults()
  1292. try:
  1293. tree = lxml.etree.parse(self.firewall_conf)
  1294. root = tree.getroot()
  1295. conf["allow"] = (root.get("policy") == "allow")
  1296. conf["allowDns"] = (root.get("dns") == "allow")
  1297. conf["allowIcmp"] = (root.get("icmp") == "allow")
  1298. conf["allowYumProxy"] = (root.get("yumProxy") == "allow")
  1299. for element in root:
  1300. rule = {}
  1301. attr_list = ("address", "netmask", "proto", "port", "toport",
  1302. "expire")
  1303. for attribute in attr_list:
  1304. rule[attribute] = element.get(attribute)
  1305. if rule["netmask"] is not None:
  1306. rule["netmask"] = int(rule["netmask"])
  1307. else:
  1308. rule["netmask"] = 32
  1309. if rule["port"] is not None:
  1310. rule["portBegin"] = int(rule["port"])
  1311. else:
  1312. # backward compatibility
  1313. rule["portBegin"] = 0
  1314. # For backward compatibility
  1315. if rule["proto"] is None:
  1316. if rule["portBegin"] > 0:
  1317. rule["proto"] = "tcp"
  1318. else:
  1319. rule["proto"] = "any"
  1320. if rule["toport"] is not None:
  1321. rule["portEnd"] = int(rule["toport"])
  1322. else:
  1323. rule["portEnd"] = None
  1324. if rule["expire"] is not None:
  1325. rule["expire"] = int(rule["expire"])
  1326. if rule["expire"] <= int(datetime.datetime.now().strftime(
  1327. "%s")):
  1328. continue
  1329. else:
  1330. del(rule["expire"])
  1331. del(rule["port"])
  1332. del(rule["toport"])
  1333. conf["rules"].append(rule)
  1334. except EnvironmentError as err:
  1335. return conf
  1336. except (xml.parsers.expat.ExpatError,
  1337. ValueError, LookupError) as err:
  1338. print("{0}: load error: {1}".format(
  1339. os.path.basename(sys.argv[0]), err))
  1340. return None
  1341. return conf
  1342. def pci_add(self, pci):
  1343. self.log.debug('pci_add(pci={!r})'.format(pci))
  1344. if not os.path.exists('/sys/bus/pci/devices/0000:%s' % pci):
  1345. raise QubesException("Invalid PCI device: %s" % pci)
  1346. if self.pcidevs.count(pci):
  1347. # already added
  1348. return
  1349. self.pcidevs.append(pci)
  1350. if self.is_running():
  1351. try:
  1352. subprocess.check_call(['sudo', system_path["qubes_pciback_cmd"], pci])
  1353. subprocess.check_call(['sudo', 'xl', 'pci-attach', str(self.xid), pci])
  1354. except Exception as e:
  1355. print >>sys.stderr, "Failed to attach PCI device on the fly " \
  1356. "(%s), changes will be seen after VM restart" % str(e)
  1357. def pci_remove(self, pci):
  1358. self.log.debug('pci_remove(pci={!r})'.format(pci))
  1359. if not self.pcidevs.count(pci):
  1360. # not attached
  1361. return
  1362. self.pcidevs.remove(pci)
  1363. if self.is_running():
  1364. p = subprocess.Popen(['xl', 'pci-list', str(self.xid)],
  1365. stdout=subprocess.PIPE)
  1366. result = p.communicate()
  1367. m = re.search(r"^(\d+.\d+)\s+0000:%s$" % pci, result[0], flags=re.MULTILINE)
  1368. if not m:
  1369. print >>sys.stderr, "Device %s already detached" % pci
  1370. return
  1371. vmdev = m.group(1)
  1372. try:
  1373. self.run_service("qubes.DetachPciDevice",
  1374. user="root", input="00:%s" % vmdev)
  1375. subprocess.check_call(['sudo', 'xl', 'pci-detach', str(self.xid), pci])
  1376. except Exception as e:
  1377. print >>sys.stderr, "Failed to detach PCI device on the fly " \
  1378. "(%s), changes will be seen after VM restart" % str(e)
  1379. def run(self, command, user = None, verbose = True, autostart = False,
  1380. notify_function = None,
  1381. passio = False, passio_popen = False, passio_stderr=False,
  1382. ignore_stderr=False, localcmd = None, wait = False, gui = True,
  1383. filter_esc = False):
  1384. """command should be in form 'cmdline'
  1385. When passio_popen=True, popen object with stdout connected to pipe.
  1386. When additionally passio_stderr=True, stderr also is connected to pipe.
  1387. When ignore_stderr=True, stderr is connected to /dev/null.
  1388. """
  1389. self.log.debug(
  1390. 'run(command={!r}, user={!r}, passio={!r}, wait={!r})'.format(
  1391. command, user, passio, wait))
  1392. if user is None:
  1393. user = self.default_user
  1394. null = None
  1395. if not self.is_running() and not self.is_paused():
  1396. if not autostart:
  1397. raise QubesException("VM not running")
  1398. try:
  1399. if notify_function is not None:
  1400. notify_function ("info", "Starting the '{0}' VM...".format(self.name))
  1401. elif verbose:
  1402. print >> sys.stderr, "Starting the VM '{0}'...".format(self.name)
  1403. self.start(verbose=verbose, start_guid = gui, notify_function=notify_function)
  1404. except (IOError, OSError, QubesException) as err:
  1405. raise QubesException("Error while starting the '{0}' VM: {1}".format(self.name, err))
  1406. except (MemoryError) as err:
  1407. raise QubesException("Not enough memory to start '{0}' VM! "
  1408. "Close one or more running VMs and try "
  1409. "again.".format(self.name))
  1410. if self.is_paused():
  1411. raise QubesException("VM is paused")
  1412. if not self.is_qrexec_running():
  1413. raise QubesException(
  1414. "Domain '{}': qrexec not connected.".format(self.name))
  1415. if gui and os.getenv("DISPLAY") is not None and not self.is_guid_running():
  1416. self.start_guid(verbose = verbose, notify_function = notify_function)
  1417. args = [system_path["qrexec_client_path"], "-d", str(self.name), "%s:%s" % (user, command)]
  1418. if localcmd is not None:
  1419. args += [ "-l", localcmd]
  1420. if filter_esc:
  1421. args += ["-t"]
  1422. if os.isatty(sys.stderr.fileno()):
  1423. args += ["-T"]
  1424. call_kwargs = {}
  1425. if ignore_stderr or not passio:
  1426. null = open("/dev/null", "w+")
  1427. call_kwargs['stderr'] = null
  1428. if not passio:
  1429. call_kwargs['stdin'] = null
  1430. call_kwargs['stdout'] = null
  1431. if passio_popen:
  1432. popen_kwargs={'stdout': subprocess.PIPE}
  1433. popen_kwargs['stdin'] = subprocess.PIPE
  1434. if passio_stderr:
  1435. popen_kwargs['stderr'] = subprocess.PIPE
  1436. else:
  1437. popen_kwargs['stderr'] = call_kwargs.get('stderr', None)
  1438. p = subprocess.Popen (args, **popen_kwargs)
  1439. if null:
  1440. null.close()
  1441. return p
  1442. if not wait and not passio:
  1443. args += ["-e"]
  1444. retcode = subprocess.call(args, **call_kwargs)
  1445. if null:
  1446. null.close()
  1447. return retcode
  1448. def run_service(self, service, source="dom0", user=None,
  1449. passio_popen=False, input=None, localcmd=None, gui=False,
  1450. wait=True):
  1451. if bool(input) + bool(passio_popen) + bool(localcmd) > 1:
  1452. raise ValueError("'input', 'passio_popen', 'localcmd' cannot be "
  1453. "used together")
  1454. if not wait and (localcmd or input):
  1455. raise ValueError("Cannot use wait=False with input or "
  1456. "localcmd specified")
  1457. if localcmd:
  1458. return self.run("QUBESRPC %s %s" % (service, source),
  1459. localcmd=localcmd, user=user, wait=wait, gui=gui)
  1460. elif input:
  1461. p = self.run("QUBESRPC %s %s" % (service, source),
  1462. user=user, wait=wait, gui=gui, passio_popen=True,
  1463. passio_stderr=True)
  1464. p.communicate(input)
  1465. return p.returncode
  1466. else:
  1467. return self.run("QUBESRPC %s %s" % (service, source),
  1468. passio_popen=passio_popen, user=user, wait=wait,
  1469. gui=gui, passio_stderr=passio_popen)
  1470. def attach_network(self, verbose = False, wait = True, netvm = None):
  1471. self.log.debug('attach_network(netvm={!r})'.format(netvm))
  1472. if dry_run:
  1473. return
  1474. if not self.is_running():
  1475. raise QubesException ("VM not running!")
  1476. if netvm is None:
  1477. netvm = self.netvm
  1478. if netvm is None:
  1479. raise QubesException ("NetVM not set!")
  1480. if netvm.qid != 0:
  1481. if not netvm.is_running():
  1482. if verbose:
  1483. print >> sys.stderr, "--> Starting NetVM {0}...".format(netvm.name)
  1484. netvm.start()
  1485. self.libvirt_domain.attachDevice(
  1486. self._format_net_dev(self.ip, self.mac, self.netvm.name))
  1487. def detach_network(self, verbose = False, netvm = None):
  1488. self.log.debug('detach_network(netvm={!r})'.format(netvm))
  1489. if dry_run:
  1490. return
  1491. if not self.is_running():
  1492. raise QubesException ("VM not running!")
  1493. if netvm is None:
  1494. netvm = self.netvm
  1495. if netvm is None:
  1496. raise QubesException ("NetVM not set!")
  1497. self.libvirt_domain.detachDevice( self._format_net_dev(self.ip,
  1498. self.mac, self.netvm.name))
  1499. def wait_for_session(self, notify_function = None):
  1500. self.log.debug('wait_for_session()')
  1501. #self.run('echo $$ >> /tmp/qubes-session-waiter; [ ! -f /tmp/qubes-session-env ] && exec sleep 365d', ignore_stderr=True, gui=False, wait=True)
  1502. # Note : User root is redefined to SYSTEM in the Windows agent code
  1503. p = self.run('QUBESRPC qubes.WaitForSession none', user="root", passio_popen=True, gui=False, wait=True)
  1504. p.communicate(input=self.default_user)
  1505. def start_guid(self, verbose = True, notify_function = None,
  1506. extra_guid_args=None, before_qrexec=False):
  1507. self.log.debug(
  1508. 'start_guid(extra_guid_args={!r}, before_qrexec={!r})'.format(
  1509. extra_guid_args, before_qrexec))
  1510. if before_qrexec:
  1511. # On PV start GUId only after qrexec-daemon
  1512. return
  1513. if verbose:
  1514. print >> sys.stderr, "--> Starting Qubes GUId..."
  1515. guid_cmd = []
  1516. if os.getuid() == 0:
  1517. # try to always have guid running as normal user, otherwise
  1518. # clipboard file may be created as root and other permission
  1519. # problems
  1520. qubes_group = grp.getgrnam('qubes')
  1521. guid_cmd = ['runuser', '-u', qubes_group.gr_mem[0], '--']
  1522. guid_cmd += [system_path["qubes_guid_path"],
  1523. "-d", str(self.xid), "-N", self.name,
  1524. "-c", self.label.color,
  1525. "-i", self.label.icon_path,
  1526. "-l", str(self.label.index)]
  1527. if extra_guid_args is not None:
  1528. guid_cmd += extra_guid_args
  1529. if self.debug:
  1530. guid_cmd += ['-v', '-v']
  1531. elif not verbose:
  1532. guid_cmd += ['-q']
  1533. # Avoid using environment variables for checking the current session,
  1534. # because this script may be called with cleared env (like with sudo).
  1535. if subprocess.check_output(
  1536. ['xprop', '-root', '-notype', 'KWIN_RUNNING']) == \
  1537. 'KWIN_RUNNING = 0x1\n':
  1538. # native decoration plugins is used, so adjust window properties
  1539. # accordingly
  1540. guid_cmd += ['-T'] # prefix window titles with VM name
  1541. # get owner of X11 session
  1542. session_owner = None
  1543. for line in subprocess.check_output(['xhost']).splitlines():
  1544. if line == 'SI:localuser:root':
  1545. pass
  1546. elif line.startswith('SI:localuser:'):
  1547. session_owner = line.split(":")[2]
  1548. if session_owner is not None:
  1549. data_dir = os.path.expanduser(
  1550. '~{}/.local/share'.format(session_owner))
  1551. else:
  1552. # fallback to current user
  1553. data_dir = os.path.expanduser('~/.local/share')
  1554. guid_cmd += ['-p',
  1555. '_KDE_NET_WM_COLOR_SCHEME=s:{}'.format(
  1556. os.path.join(data_dir,
  1557. 'qubes-kde', self.label.name + '.colors'))]
  1558. retcode = subprocess.call (guid_cmd)
  1559. if (retcode != 0) :
  1560. raise QubesException("Cannot start qubes-guid!")
  1561. if not self.is_qrexec_running():
  1562. return
  1563. try:
  1564. import qubes.monitorlayoutnotify
  1565. if verbose:
  1566. print >> sys.stderr, "--> Sending monitor layout..."
  1567. monitor_layout = qubes.monitorlayoutnotify.get_monitor_layout()
  1568. # Notify VM only if we've got a monitor_layout which is not empty
  1569. # or else we break proper VM resolution set by gui-agent
  1570. if len(monitor_layout) > 0:
  1571. qubes.monitorlayoutnotify.notify_vm(self, monitor_layout)
  1572. except ImportError as e:
  1573. print >>sys.stderr, "ERROR: %s" % e
  1574. if verbose:
  1575. print >> sys.stderr, "--> Waiting for qubes-session..."
  1576. self.wait_for_session(notify_function)
  1577. def start_qrexec_daemon(self, verbose = False, notify_function = None):
  1578. self.log.debug('start_qrexec_daemon()')
  1579. if verbose:
  1580. print >> sys.stderr, "--> Starting the qrexec daemon..."
  1581. qrexec = []
  1582. if os.getuid() == 0:
  1583. # try to always have qrexec running as normal user, otherwise
  1584. # many qrexec services would need to deal with root/user
  1585. # permission problems
  1586. qubes_group = grp.getgrnam('qubes')
  1587. qrexec = ['runuser', '-u', qubes_group.gr_mem[0], '--']
  1588. qrexec += ['env', 'QREXEC_STARTUP_TIMEOUT=' + str(self.qrexec_timeout),
  1589. system_path["qrexec_daemon_path"]]
  1590. qrexec_args = [str(self.xid), self.name, self.default_user]
  1591. if not verbose:
  1592. qrexec_args.insert(0, "-q")
  1593. retcode = subprocess.call(qrexec + qrexec_args)
  1594. if (retcode != 0) :
  1595. raise OSError ("Cannot execute qrexec-daemon!")
  1596. def start_qubesdb(self):
  1597. self.log.debug('start_qubesdb()')
  1598. pidfile = '/var/run/qubes/qubesdb.{}.pid'.format(self.name)
  1599. try:
  1600. if os.path.exists(pidfile):
  1601. old_qubesdb_pid = open(pidfile, 'r').read()
  1602. try:
  1603. os.kill(int(old_qubesdb_pid), signal.SIGTERM)
  1604. except OSError:
  1605. raise QubesException(
  1606. "Failed to kill old QubesDB instance (PID {}). "
  1607. "Terminate it manually and retry. "
  1608. "If that isn't QubesDB process, "
  1609. "remove the pidfile: {}".format(old_qubesdb_pid,
  1610. pidfile))
  1611. timeout = 25
  1612. while os.path.exists(pidfile) and timeout:
  1613. time.sleep(0.2)
  1614. timeout -= 1
  1615. except IOError: # ENOENT (pidfile)
  1616. pass
  1617. # force connection to a new daemon
  1618. self._qdb_connection = None
  1619. qubesdb_cmd = []
  1620. if os.getuid() == 0:
  1621. # try to always have qubesdb running as normal user, otherwise
  1622. # killing it at VM restart (see above) will always fail
  1623. qubes_group = grp.getgrnam('qubes')
  1624. qubesdb_cmd = ['runuser', '-u', qubes_group.gr_mem[0], '--']
  1625. qubesdb_cmd += [
  1626. system_path["qubesdb_daemon_path"],
  1627. str(self.xid),
  1628. self.name]
  1629. retcode = subprocess.call (qubesdb_cmd)
  1630. if retcode != 0:
  1631. raise OSError("ERROR: Cannot execute qubesdb-daemon!")
  1632. def request_memory(self, mem_required = None):
  1633. # Overhead of per-VM/per-vcpu Xen structures, taken from OpenStack nova/virt/xenapi/driver.py
  1634. # see https://wiki.openstack.org/wiki/XenServer/Overhead
  1635. # add an extra MB because Nova rounds up to MBs
  1636. MEM_OVERHEAD_BASE = (3 + 1) * 1024 * 1024
  1637. MEM_OVERHEAD_PER_VCPU = 3 * 1024 * 1024 / 2
  1638. if mem_required is None:
  1639. mem_required = int(self.memory) * 1024 * 1024
  1640. if qmemman_present:
  1641. qmemman_client = QMemmanClient()
  1642. try:
  1643. mem_required_with_overhead = mem_required + MEM_OVERHEAD_BASE + self.vcpus * MEM_OVERHEAD_PER_VCPU
  1644. got_memory = qmemman_client.request_memory(mem_required_with_overhead)
  1645. except IOError as e:
  1646. raise IOError("ERROR: Failed to connect to qmemman: %s" % str(e))
  1647. if not got_memory:
  1648. qmemman_client.close()
  1649. raise MemoryError ("ERROR: insufficient memory to start VM '%s'" % self.name)
  1650. return qmemman_client
  1651. def start(self, verbose = False, preparing_dvm = False, start_guid = True,
  1652. notify_function = None, mem_required = None):
  1653. self.log.debug('start('
  1654. 'preparing_dvm={!r}, start_guid={!r}, mem_required={!r})'.format(
  1655. preparing_dvm, start_guid, mem_required))
  1656. if dry_run:
  1657. return
  1658. # Intentionally not used is_running(): eliminate also "Paused", "Crashed", "Halting"
  1659. if self.get_power_state() != "Halted":
  1660. raise QubesException ("VM is already running!")
  1661. self.verify_files()
  1662. if self.netvm is not None:
  1663. if self.netvm.qid != 0:
  1664. if not self.netvm.is_running():
  1665. if verbose:
  1666. print >> sys.stderr, "--> Starting NetVM {0}...".format(self.netvm.name)
  1667. self.netvm.start(verbose = verbose, start_guid = start_guid, notify_function = notify_function)
  1668. self.storage.prepare_for_vm_startup(verbose=verbose)
  1669. if verbose:
  1670. print >> sys.stderr, "--> Loading the VM (type = {0})...".format(self.type)
  1671. self._update_libvirt_domain()
  1672. qmemman_client = self.request_memory(mem_required)
  1673. # Bind pci devices to pciback driver
  1674. for pci in self.pcidevs:
  1675. try:
  1676. nd = vmm.libvirt_conn.nodeDeviceLookupByName('pci_0000_' + pci.replace(':','_').replace('.','_'))
  1677. except libvirt.libvirtError as e:
  1678. if e.get_error_code() == libvirt.VIR_ERR_NO_NODE_DEVICE:
  1679. raise QubesException(
  1680. "PCI device {} does not exist (domain {})".
  1681. format(pci, self.name))
  1682. else:
  1683. raise
  1684. try:
  1685. nd.dettach()
  1686. except libvirt.libvirtError as e:
  1687. if e.get_error_code() == libvirt.VIR_ERR_INTERNAL_ERROR:
  1688. # already detached
  1689. pass
  1690. else:
  1691. raise
  1692. self.libvirt_domain.createWithFlags(libvirt.VIR_DOMAIN_START_PAUSED)
  1693. try:
  1694. if verbose:
  1695. print >> sys.stderr, "--> Starting Qubes DB..."
  1696. self.start_qubesdb()
  1697. xid = self.xid
  1698. self.log.debug('xid={}'.format(xid))
  1699. if preparing_dvm:
  1700. self.services['qubes-dvm'] = True
  1701. if verbose:
  1702. print >> sys.stderr, "--> Setting Qubes DB info for the VM..."
  1703. self.create_qubesdb_entries()
  1704. if verbose:
  1705. print >> sys.stderr, "--> Updating firewall rules..."
  1706. netvm = self.netvm
  1707. while netvm is not None:
  1708. if netvm.is_proxyvm() and netvm.is_running():
  1709. netvm.write_iptables_qubesdb_entry()
  1710. netvm = netvm.netvm
  1711. # fire hooks
  1712. for hook in self.hooks_start:
  1713. hook(self, verbose = verbose, preparing_dvm = preparing_dvm,
  1714. start_guid = start_guid, notify_function = notify_function)
  1715. except:
  1716. self.force_shutdown()
  1717. raise
  1718. if verbose:
  1719. print >> sys.stderr, "--> Starting the VM..."
  1720. self.libvirt_domain.resume()
  1721. # close() is not really needed, because the descriptor is close-on-exec
  1722. # anyway, the reason to postpone close() is that possibly xl is not done
  1723. # constructing the domain after its main process exits
  1724. # so we close() when we know the domain is up
  1725. # the successful unpause is some indicator of it
  1726. if qmemman_present:
  1727. qmemman_client.close()
  1728. extra_guid_args = []
  1729. if preparing_dvm:
  1730. # Run GUI daemon in "invisible" mode, so applications started by
  1731. # prerun script will not disturb the user
  1732. extra_guid_args = ['-I']
  1733. elif not os.path.exists('/var/run/qubes/shm.id') \
  1734. and not os.path.exists('/var/run/shm.id'):
  1735. # Start GUI daemon only when shmoverride is loaded; unless
  1736. # preparing DispVM, where it isn't needed because of "invisible"
  1737. # mode
  1738. start_guid = False
  1739. if start_guid and 'DISPLAY' not in os.environ:
  1740. if verbose:
  1741. print >> sys.stderr, \
  1742. "WARNING: not starting GUI, because DISPLAY not set"
  1743. start_guid = False
  1744. if start_guid:
  1745. self.start_guid(verbose=verbose, notify_function=notify_function,
  1746. before_qrexec=True, extra_guid_args=extra_guid_args)
  1747. if not preparing_dvm:
  1748. self.start_qrexec_daemon(verbose=verbose,notify_function=notify_function)
  1749. if start_guid:
  1750. self.start_guid(verbose=verbose, notify_function=notify_function,
  1751. extra_guid_args=extra_guid_args)
  1752. return xid
  1753. def _cleanup_zombie_domains(self):
  1754. """
  1755. This function is workaround broken libxl (which leaves not fully
  1756. created domain on failure) and vchan on domain crash behaviour
  1757. @return: None
  1758. """
  1759. xc = self.get_xc_dominfo()
  1760. if xc and xc['dying'] == 1:
  1761. # GUID still running?
  1762. guid_pidfile = '/var/run/qubes/guid-running.%d' % xc['domid']
  1763. if os.path.exists(guid_pidfile):
  1764. guid_pid = open(guid_pidfile).read().strip()
  1765. os.kill(int(guid_pid), 15)
  1766. # qrexec still running?
  1767. if self.is_qrexec_running():
  1768. #TODO: kill qrexec daemon
  1769. pass
  1770. def shutdown(self, force=False, xid = None):
  1771. self.log.debug('shutdown()')
  1772. if dry_run:
  1773. return
  1774. if not self.is_running():
  1775. raise QubesException ("VM already stopped!")
  1776. self.libvirt_domain.shutdown()
  1777. def force_shutdown(self, xid = None):
  1778. self.log.debug('force_shutdown()')
  1779. if dry_run:
  1780. return
  1781. if not self.is_running() and not self.is_paused():
  1782. raise QubesException ("VM already stopped!")
  1783. self.libvirt_domain.destroy()
  1784. self.refresh()
  1785. def suspend(self):
  1786. self.log.debug('suspend()')
  1787. if dry_run:
  1788. return
  1789. if not self.is_running() and not self.is_paused() or \
  1790. self.get_power_state() == "Suspended":
  1791. raise QubesException ("VM not running!")
  1792. if len (self.pcidevs) > 0:
  1793. self.libvirt_domain.pMSuspendForDuration(
  1794. libvirt.VIR_NODE_SUSPEND_TARGET_MEM, 0, 0)
  1795. else:
  1796. self.pause()
  1797. def resume(self):
  1798. self.log.debug('resume()')
  1799. if dry_run:
  1800. return
  1801. if self.get_power_state() == "Suspended":
  1802. self.libvirt_domain.pMWakeup()
  1803. else:
  1804. self.unpause()
  1805. def pause(self):
  1806. self.log.debug('pause()')
  1807. if dry_run:
  1808. return
  1809. if not self.is_running():
  1810. raise QubesException ("VM not running!")
  1811. self.libvirt_domain.suspend()
  1812. def unpause(self):
  1813. self.log.debug('unpause()')
  1814. if dry_run:
  1815. return
  1816. if not self.is_paused():
  1817. raise QubesException ("VM not paused!")
  1818. self.libvirt_domain.resume()
  1819. def get_xml_attrs(self):
  1820. attrs = {}
  1821. attrs_config = self.get_attrs_config()
  1822. for attr in attrs_config:
  1823. attr_config = attrs_config[attr]
  1824. if 'save' in attr_config:
  1825. if 'save_skip' in attr_config:
  1826. if callable(attr_config['save_skip']):
  1827. if attr_config['save_skip']():
  1828. continue
  1829. elif eval(attr_config['save_skip']):
  1830. continue
  1831. if callable(attr_config['save']):
  1832. value = attr_config['save']()
  1833. else:
  1834. value = eval(attr_config['save'])
  1835. if 'save_attr' in attr_config:
  1836. attrs[attr_config['save_attr']] = value
  1837. else:
  1838. attrs[attr] = value
  1839. return attrs
  1840. def create_xml_element(self):
  1841. attrs = self.get_xml_attrs()
  1842. element = lxml.etree.Element(
  1843. # Compatibility hack (Qubes*VM in type vs Qubes*Vm in XML)...
  1844. "Qubes" + self.type.replace("VM", "Vm"),
  1845. **attrs)
  1846. return element
  1847. register_qubes_vm_class(QubesVm)