000QubesVm.py 76 KB

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