000QubesVm.py 67 KB

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