000QubesVm.py 77 KB

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