qubesvm.py 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735
  1. #!/usr/bin/python2 -O
  2. # vim: fileencoding=utf-8
  3. #
  4. # The Qubes OS Project, https://www.qubes-os.org/
  5. #
  6. # Copyright (C) 2010-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  7. # Copyright (C) 2013-2015 Marek Marczykowski-Górecki
  8. # <marmarek@invisiblethingslab.com>
  9. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  10. #
  11. # This program is free software; you can redistribute it and/or modify
  12. # it under the terms of the GNU General Public License as published by
  13. # the Free Software Foundation; either version 2 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # This program is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU General Public License along
  22. # with this program; if not, write to the Free Software Foundation, Inc.,
  23. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  24. #
  25. import datetime
  26. import lxml.etree
  27. import os
  28. import os.path
  29. import re
  30. import shutil
  31. import subprocess
  32. import sys
  33. import time
  34. import uuid
  35. import xml.parsers.expat
  36. import libvirt
  37. import warnings
  38. import qubes
  39. import qubes.config
  40. #import qubes.qdb
  41. #import qubes.qmemman
  42. #import qubes.qmemman_algo
  43. import qubes.storage
  44. import qubes.utils
  45. import qubes.vm
  46. qmemman_present = False
  47. try:
  48. import qubes.qmemman_client
  49. qmemman_present = True
  50. except ImportError:
  51. pass
  52. def _setter_qid(self, prop, value):
  53. if not 0 <= value <= qubes.config.max_qid:
  54. raise ValueError(
  55. '{} value must be between 0 and qubes.config.max_qid'.format(
  56. prop.__name__))
  57. return value
  58. def _setter_name(self, prop, value):
  59. if not isinstance(value, basestring):
  60. raise TypeError('{} value must be string, {!r} found'.format(
  61. prop.__name__, type(value).__name__))
  62. if len(value) > 31:
  63. raise ValueError('{} value must be shorter than 32 characters'.format(
  64. prop.__name__))
  65. if re.match(r"^[a-zA-Z][a-zA-Z0-9_-]*$", value) is None:
  66. raise ValueError('{} value contains illegal characters'.format(
  67. prop.__name__))
  68. if self.is_running():
  69. raise qubes.QubesException('Cannot change name of running VM')
  70. try:
  71. if self.installed_by_rpm:
  72. raise qubes.QubesException('Cannot rename VM installed by RPM -- '
  73. 'first clone VM and then use yum to remove package.')
  74. except AttributeError:
  75. pass
  76. return value
  77. def _setter_kernel(self, prop, value):
  78. if not os.path.exists(os.path.join(system_path[
  79. 'qubes_kernels_base_dir'], value)):
  80. raise qubes.QubesException('Kernel {!r} not installed'.format(value))
  81. for f in ('vmlinuz', 'modules.img'):
  82. if not os.path.exists(os.path.join(
  83. system_path['qubes_kernels_base_dir'], value, f)):
  84. raise qubes.QubesException(
  85. 'Kernel {!r} not properly installed: missing {!r} file'.format(
  86. value, f))
  87. return value
  88. def _default_conf_file(self, name=None):
  89. return (name or self.name) + '.conf'
  90. class QubesVM(qubes.vm.BaseVM):
  91. '''Base functionality of Qubes VM shared between all VMs.'''
  92. #
  93. # properties loaded from XML
  94. #
  95. label = qubes.property('label',
  96. setter=(lambda self, prop, value: self.app.labels[
  97. int(value.rsplit('-', 1)[1])]),
  98. doc='Colourful label assigned to VM. This is where you set the colour '
  99. 'of the padlock.')
  100. # XXX swallowed uses_default_netvm
  101. netvm = qubes.VMProperty('netvm', load_stage=4, allow_none=True,
  102. default=(lambda self: self.app.default_fw_netvm if self.provides_network
  103. else self.app.default_netvm),
  104. doc='''VM that provides network connection to this domain. When
  105. `None`, machine is disconnected. When absent, domain uses default
  106. NetVM.''')
  107. provides_network = qubes.property('provides_network',
  108. type=bool, setter=qubes.property.bool,
  109. doc='`True` if it is NetVM or ProxyVM, false otherwise.')
  110. qid = qubes.property('qid', type=int,
  111. setter=_setter_qid,
  112. doc='''Internal, persistent identificator of particular domain. Note
  113. this is different from Xen domid.''')
  114. name = qubes.property('name', type=str,
  115. doc='User-specified name of the domain.')
  116. uuid = qubes.property('uuid', type=uuid.UUID, default=None,
  117. doc='UUID from libvirt.')
  118. # TODO meaningful default
  119. # TODO setter to ensure absolute/relative path?
  120. dir_path = qubes.property('dir_path', type=str, default=None,
  121. doc='FIXME')
  122. conf_file = qubes.property('conf_file', type=str,
  123. default=_default_conf_file,
  124. saver=(lambda self, prop, value: self.relative_path(value)),
  125. doc='XXX libvirt config file?')
  126. # XXX this should be part of qubes.xml
  127. firewall_conf = qubes.property('firewall_conf', type=str,
  128. default='firewall.xml')
  129. installed_by_rpm = qubes.property('installed_by_rpm',
  130. type=bool, setter=qubes.property.bool,
  131. default=False,
  132. doc='''If this domain's image was installed from package tracked by
  133. package manager.''')
  134. memory = qubes.property('memory', type=int,
  135. default=qubes.config.defaults['memory'],
  136. doc='Memory currently available for this VM.')
  137. maxmem = qubes.property('maxmem', type=int, default=None,
  138. doc='''Maximum amount of memory available for this VM (for the purpose
  139. of the memory balancer).''')
  140. internal = qubes.property('internal', default=False,
  141. type=bool, setter=qubes.property.bool,
  142. doc='''Internal VM (not shown in qubes-manager, don't create appmenus
  143. entries.''')
  144. # XXX what is that
  145. vcpus = qubes.property('vcpus', default=None,
  146. doc='FIXME')
  147. # XXX swallowed uses_default_kernel
  148. # XXX not applicable to HVM?
  149. kernel = qubes.property('kernel', type=str,
  150. setter=_setter_kernel,
  151. default=(lambda self: self.app.default_kernel),
  152. doc='Kernel used by this domain.')
  153. # XXX swallowed uses_default_kernelopts
  154. # XXX not applicable to HVM?
  155. kernelopts = qubes.property('kernelopts', type=str, load_stage=4,
  156. default=(lambda self: defaults['kernelopts_pcidevs'] \
  157. if len(self.devices['pci']) > 0 \
  158. else qubes.config.defaults['kernelopts']),
  159. doc='Kernel command line passed to domain.')
  160. mac = qubes.property('mac', type=str,
  161. default=(lambda self: '00:16:3E:5E:6C:{:02X}'.format(self.qid)),
  162. doc='MAC address of the NIC emulated inside VM')
  163. debug = qubes.property('debug', type=bool, default=False,
  164. setter=qubes.property.bool,
  165. doc='Turns on debugging features.')
  166. # XXX what this exactly does?
  167. # XXX shouldn't this go to standalone VM and TemplateVM, and leave here
  168. # only plain property?
  169. default_user = qubes.property('default_user', type=str,
  170. default=(lambda self: self.template.default_user),
  171. doc='FIXME')
  172. # @property
  173. # def default_user(self):
  174. # if self.template is not None:
  175. # return self.template.default_user
  176. # else:
  177. # return self._default_user
  178. qrexec_timeout = qubes.property('qrexec_timeout', type=int, default=60,
  179. doc='''Time in seconds after which qrexec connection attempt is deemed
  180. failed. Operating system inside VM should be able to boot in this
  181. time.''')
  182. autostart = qubes.property('autostart', default=False,
  183. type=bool, setter=qubes.property.bool,
  184. doc='''Setting this to `True` means that VM should be autostarted on
  185. dom0 boot.''')
  186. # XXX I don't understand backups
  187. include_in_backups = qubes.property('include_in_backups', default=True,
  188. type=bool, setter=qubes.property.bool,
  189. doc='If this domain is to be included in default backup.')
  190. backup_content = qubes.property('backup_content', default=False,
  191. type=bool, setter=qubes.property.bool,
  192. doc='FIXME')
  193. backup_size = qubes.property('backup_size', type=int, default=0,
  194. doc='FIXME')
  195. backup_path = qubes.property('backup_path', type=str, default='',
  196. doc='FIXME')
  197. # format got changed from %s to str(datetime.datetime)
  198. backup_timestamp = qubes.property('backup_timestamp', default=None,
  199. setter=(lambda self, prop, value:
  200. datetime.datetime.fromtimestamp(value)),
  201. saver=(lambda self, prop, value: value.strftime('%s')),
  202. doc='FIXME')
  203. #
  204. # static, class-wide properties
  205. #
  206. # config file should go away to storage/backend class
  207. #: template for libvirt config file (XML)
  208. config_file_template = qubes.config.system_path["config_template_pv"]
  209. #
  210. # properties not loaded from XML, calculated at run-time
  211. #
  212. # VMM-related
  213. @property
  214. def xid(self):
  215. '''Xen ID.
  216. Or not Xen, but ID.
  217. '''
  218. if self.libvirt_domain is None:
  219. return -1
  220. return self.libvirt_domain.ID()
  221. @property
  222. def libvirt_domain(self):
  223. '''Libvirt domain object from libvirt.
  224. May be :py:obj:`None`, if libvirt knows nothing about this domain.
  225. '''
  226. if self._libvirt_domain is not None:
  227. return self._libvirt_domain
  228. # XXX _update_libvirt_domain?
  229. try:
  230. if self.uuid is not None:
  231. self._libvirt_domain = vmm.libvirt_conn.lookupByUUID(
  232. self.uuid.bytes)
  233. else:
  234. self._libvirt_domain = vmm.libvirt_conn.lookupByName(self.name)
  235. self.uuid = uuid.UUID(bytes=self._libvirt_domain.UUID())
  236. except libvirt.libvirtError:
  237. if vmm.libvirt_conn.virConnGetLastError()[0] == \
  238. libvirt.VIR_ERR_NO_DOMAIN:
  239. self._update_libvirt_domain()
  240. else:
  241. raise
  242. return self._libvirt_domain
  243. @property
  244. def qdb(self):
  245. '''QubesDB handle for this domain.'''
  246. if self._qdb_connection is None:
  247. if self.is_running():
  248. self._qdb_connection = qubes.qdb.QubesDB(self.name)
  249. return self._qdb_connection
  250. # XXX this should go to to AppVM?
  251. @property
  252. def private_img(self):
  253. '''Location of private image of the VM (that contains :file:`/rw` \
  254. and :file:`/home`).'''
  255. return self.storage.private_img
  256. # XXX this should go to to AppVM? or TemplateVM?
  257. @property
  258. def root_img(self):
  259. '''Location of root image.'''
  260. return self.storage.root_img
  261. # XXX and this should go to exactly where? DispVM has it.
  262. @property
  263. def volatile_img(self):
  264. '''Volatile image that overlays :py:attr:`root_img`.'''
  265. return self.storage.volatile_img
  266. # XXX shouldn't this go elsewhere?
  267. @property
  268. def updateable(self):
  269. '''True if this machine may be updated on its own.'''
  270. return hasattr(self, 'template')
  271. @property
  272. def uses_custom_config(self):
  273. '''True if this machine has config in non-standard place.'''
  274. return not self.property_is_default(self, 'conf_file')
  275. # return self.conf_file != self.storage.abspath(self.name + '.conf')
  276. @property
  277. def icon_path(self):
  278. return self.dir_path and os.path.join(self.dir_path, "icon.png")
  279. # XXX I don't know what to do with these; probably should be isinstance(...)
  280. # def is_template(self):
  281. # return False
  282. #
  283. # def is_appvm(self):
  284. # return False
  285. #
  286. # def is_proxyvm(self):
  287. # return False
  288. #
  289. # def is_disposablevm(self):
  290. # return False
  291. # network-related
  292. @property
  293. def ip(self):
  294. '''IP address of this domain.'''
  295. if self.netvm is not None:
  296. return self.netvm.get_ip_for_vm(self.qid)
  297. else:
  298. return None
  299. @property
  300. def netmask(self):
  301. '''Netmask for this domain's IP address.'''
  302. if self.netvm is not None:
  303. return self.netvm.netmask
  304. else:
  305. return None
  306. @property
  307. def gateway(self):
  308. '''Gateway for other domains that use this domain as netvm.'''
  309. # This is gateway IP for _other_ VMs, so make sense only in NetVMs
  310. return None
  311. @property
  312. def secondary_dns(self):
  313. '''Secondary DNS server set up for this domain.'''
  314. if self.netvm is not None:
  315. return self.netvm.secondary_dns
  316. else:
  317. return None
  318. @property
  319. def vif(self):
  320. '''Name of the network interface backend in netvm that is connected to
  321. NIC inside this domain.'''
  322. if self.xid < 0:
  323. return None
  324. if self.netvm is None:
  325. return None
  326. return "vif{0}.+".format(self.xid)
  327. #
  328. # constructor
  329. #
  330. def __init__(self, app, xml, **kwargs):
  331. super(QubesVM, self).__init__(app, xml, **kwargs)
  332. #Init private attrs
  333. self._libvirt_domain = None
  334. self._qdb_connection = None
  335. assert self.qid < qubes.config.max_qid, "VM id out of bounds!"
  336. assert self.name is not None
  337. # Not in generic way to not create QubesHost() to frequently
  338. # XXX this doesn't apply, host is instantiated once
  339. if self.maxmem is None and not self.app.vmm.offline_mode:
  340. total_mem_mb = self.app.host.memory_total/1024
  341. self.maxmem = total_mem_mb/2
  342. # Linux specific cap: max memory can't scale beyond 10.79*init_mem
  343. # see https://groups.google.com/forum/#!topic/qubes-devel/VRqkFj1IOtA
  344. if self.maxmem > self.memory * 10:
  345. self.maxmem = self.memory * 10
  346. # By default allow use all VCPUs
  347. if not hasattr(self, 'vcpus') and not self.app.vmm.offline_mode:
  348. self.vcpus = self.app.host.no_cpus
  349. # Always set if meminfo-writer should be active or not
  350. if 'meminfo-writer' not in self.services:
  351. self.services['meminfo-writer'] = not len(self.devices['pci']) > 0
  352. # Additionally force meminfo-writer disabled when VM have PCI devices
  353. if len(self.devices['pci']) > 0:
  354. self.services['meminfo-writer'] = False
  355. # Initialize VM image storage class
  356. self.storage = qubes.storage.get_storage(self)
  357. if hasattr(self, 'kernels_dir'):
  358. self.storage.modules_img = os.path.join(self.kernels_dir,
  359. "modules.img")
  360. self.storage.modules_img_rw = self.kernel is None
  361. # fire hooks
  362. self.fire_event('domain-init')
  363. #
  364. # event handlers
  365. #
  366. @qubes.events.handler('property-set:label')
  367. def on_property_set_label(self, event, name, new_label, old_label=None):
  368. if self.icon_path:
  369. try:
  370. os.remove(self.icon_path)
  371. except:
  372. pass
  373. if hasattr(os, "symlink"):
  374. os.symlink(new_label.icon_path, self.icon_path)
  375. # FIXME: some os-independent wrapper?
  376. subprocess.call(['sudo', 'xdg-icon-resource', 'forceupdate'])
  377. else:
  378. shutil.copy(new_label.icon_path, self.icon_path)
  379. @qubes.events.handler('property-del:netvm')
  380. def on_property_del_netvm(self, event, name, old_netvm):
  381. # we are changing to default netvm
  382. new_netvm = self.netvm
  383. if new_netvm == old_netvm:
  384. return
  385. self.fire_event('property-set:netvm', 'netvm', new_netvm, old_netvm)
  386. @qubes.events.handler('property-set:netvm')
  387. def on_property_set_netvm(self, event, name, new_netvm, old_netvm=None):
  388. if self.is_running() and new_netvm is not None \
  389. and not new_netvm.is_running():
  390. raise QubesException("Cannot dynamically attach to stopped NetVM")
  391. if self.netvm is not None:
  392. del self.netvm.connected_vms[self]
  393. if self.is_running():
  394. self.detach_network()
  395. # TODO change to domain-removed event handler in netvm
  396. # if hasattr(self.netvm, 'post_vm_net_detach'):
  397. # self.netvm.post_vm_net_detach(self)
  398. if new_netvm is None:
  399. if not self._do_not_reset_firewall:
  400. # Set also firewall to block all traffic as discussed in #370
  401. if os.path.exists(self.firewall_conf):
  402. shutil.copy(self.firewall_conf,
  403. os.path.join(system_path["qubes_base_dir"],
  404. "backup",
  405. "%s-firewall-%s.xml" % (self.name,
  406. time.strftime('%Y-%m-%d-%H:%M:%S'))))
  407. self.write_firewall_conf({'allow': False, 'allowDns': False,
  408. 'allowIcmp': False, 'allowYumProxy': False, 'rules': []})
  409. else:
  410. new_netvm.connected_vms.add(self)
  411. if new_netvm is None:
  412. return
  413. if self.is_running():
  414. # refresh IP, DNS etc
  415. self.create_qdb_entries()
  416. self.attach_network()
  417. # TODO domain-added event handler in netvm
  418. # if hasattr(self.netvm, 'post_vm_net_attach'):
  419. # self.netvm.post_vm_net_attach(self)
  420. @qubes.events.handler('property-pre-set:name')
  421. def on_property_pre_set_name(self, event, name, newvalue, oldvalue=None):
  422. # TODO not self.is_stopped() would be more appropriate
  423. if self.is_running():
  424. raise QubesException('Cannot change name of running domain')
  425. @qubes.events.handler('property-pre-set:dir_path')
  426. def on_property_pre_set_name(self, event, name, newvalue, oldvalue=None):
  427. # TODO not self.is_stopped() would be more appropriate
  428. if self.is_running():
  429. raise QubesException('Cannot change dir_path of running domain')
  430. @qubes.events.handler('property-set:dir_path')
  431. def on_property_set_dir_path(self, event, name, newvalue, oldvalue=None):
  432. self.storage.rename(newvalue, oldvalue)
  433. @qubes.events.handler('property-set:name')
  434. def on_property_set_name(self, event, name, new_name, old_name=None):
  435. if self._libvirt_domain is not None:
  436. self.libvirt_domain.undefine()
  437. self._libvirt_domain = None
  438. if self._qdb_connection is not None:
  439. self._qdb_connection.close()
  440. self._qdb_connection = None
  441. # move: dir_path, conf_file
  442. self.dir_path = self.dir_path.replace(
  443. '/{}/', '/{}/'.format(old_name, new_name))
  444. if self.property_is_default(self, 'conf_file'):
  445. new_conf = os.path.join(
  446. self.dir_path, _default_conf_file(self, old_name))
  447. old_conf = os.path.join(
  448. self.dir_path, _default_conf_file(self, old_name))
  449. self.storage.rename(old_conf, new_conf)
  450. self.fire_event('property-set:conf_file', 'conf_file',
  451. new_conf, old_conf)
  452. if hasattr(self, 'kernels_dir') and self.kernels_dir is not None:
  453. self.kernels_dir = self.kernels_dir.replace(
  454. old_dirpath, new_dirpath)
  455. self._update_libvirt_domain()
  456. @qubes.events.handler('property-pre-set:autostart')
  457. def on_property_pre_set_autostart(self, event, prop, name, value,
  458. oldvalue=None):
  459. if subprocess.call(['sudo', 'systemctl',
  460. ('enable' if value else 'disable'),
  461. 'qubes-vm@{}.service'.format(self.name)]):
  462. raise QubesException("Failed to set autostart for VM via systemctl")
  463. @qubes.events.handler('device-pre-attached:pci')
  464. def on_device_pre_attached_pci(self, event, pci):
  465. if not os.path.exists('/sys/bus/pci/devices/0000:%s' % pci):
  466. raise QubesException("Invalid PCI device: %s" % pci)
  467. if not self.is_running():
  468. return
  469. try:
  470. # TODO: libvirt-ise
  471. subprocess.check_call(
  472. ['sudo', system_path["qubes_pciback_cmd"], pci])
  473. subprocess.check_call(
  474. ['sudo', 'xl', 'pci-attach', str(self.xid), pci])
  475. except Exception as e:
  476. print >>sys.stderr, "Failed to attach PCI device on the fly " \
  477. "(%s), changes will be seen after VM restart" % str(e)
  478. @qubes.events.handler('device-pre-detached:pci')
  479. def on_device_pre_detached_pci(self, event, pci):
  480. if not self.is_running():
  481. return
  482. # TODO: libvirt-ise
  483. p = subprocess.Popen(['xl', 'pci-list', str(self.xid)],
  484. stdout=subprocess.PIPE)
  485. result = p.communicate()
  486. m = re.search(r"^(\d+.\d+)\s+0000:%s$" % pci, result[0],
  487. flags=re.MULTILINE)
  488. if not m:
  489. print >>sys.stderr, "Device %s already detached" % pci
  490. return
  491. vmdev = m.group(1)
  492. try:
  493. self.run_service("qubes.DetachPciDevice",
  494. user="root", input="00:%s" % vmdev)
  495. subprocess.check_call(
  496. ['sudo', 'xl', 'pci-detach', str(self.xid), pci])
  497. except Exception as e:
  498. print >>sys.stderr, "Failed to detach PCI device on the fly " \
  499. "(%s), changes will be seen after VM restart" % str(e)
  500. #
  501. # methods for changing domain state
  502. #
  503. def start(self, preparing_dvm=False, start_guid=True,
  504. notify_function=None, mem_required=None):
  505. '''Start domain
  506. :param bool preparing_dvm: FIXME
  507. :param bool start_guid: FIXME
  508. :param collections.Callable notify_function: FIXME
  509. :param int mem_required: FIXME
  510. '''
  511. # Intentionally not used is_running(): eliminate also "Paused",
  512. # "Crashed", "Halting"
  513. if self.get_power_state() != "Halted":
  514. raise QubesException("VM is already running!")
  515. self.log.info('Starting {}'.format(self.name))
  516. self.verify_files()
  517. if self.netvm is not None:
  518. if self.netvm.qid != 0:
  519. if not self.netvm.is_running():
  520. self.netvm.start(start_guid=start_guid,
  521. notify_function=notify_function)
  522. self.storage.prepare_for_vm_startup()
  523. self._update_libvirt_domain()
  524. if mem_required is None:
  525. mem_required = int(self.memory) * 1024 * 1024
  526. if qmemman_present:
  527. qmemman_client = qubes.qmemman_client.QMemmanClient()
  528. try:
  529. got_memory = qmemman_client.request_memory(mem_required)
  530. except IOError as e:
  531. raise IOError('Failed to connect to qmemman: {!s}'.format(e))
  532. if not got_memory:
  533. qmemman_client.close()
  534. raise MemoryError(
  535. 'Insufficient memory to start VM {!r}'.format(self.name))
  536. # Bind pci devices to pciback driver
  537. for pci in self.devices['pci']:
  538. nd = vmm.libvirt_conn.nodeDeviceLookupByName(
  539. 'pci_0000_' + pci.replace(':', '_').replace('.', '_'))
  540. try:
  541. nd.dettach()
  542. except libvirt.libvirtError:
  543. if vmm.libvirt_conn.virConnGetLastError()[0] == \
  544. libvirt.VIR_ERR_INTERNAL_ERROR:
  545. # already detached
  546. pass
  547. else:
  548. raise
  549. self.libvirt_domain.createWithFlags(libvirt.VIR_DOMAIN_START_PAUSED)
  550. if preparing_dvm:
  551. self.services['qubes-dvm'] = True
  552. self.log.info('Setting Qubes DB info for the VM')
  553. self.start_qubesdb()
  554. self.create_qdb_entries()
  555. self.log.info('Updating firewall rules')
  556. for vm in self.app.domains:
  557. if vm.is_proxyvm() and vm.is_running():
  558. vm.write_iptables_xenstore_entry()
  559. self.fire_event('domain-started',
  560. preparing_dvm=preparing_dvm, start_guid=start_guid)
  561. self.log.warning('Activating the {} VM'.format(self.name))
  562. self.libvirt_domain.resume()
  563. # close() is not really needed, because the descriptor is close-on-exec
  564. # anyway, the reason to postpone close() is that possibly xl is not done
  565. # constructing the domain after its main process exits
  566. # so we close() when we know the domain is up
  567. # the successful unpause is some indicator of it
  568. if qmemman_present:
  569. qmemman_client.close()
  570. if self._start_guid_first and start_guid and not preparing_dvm \
  571. and os.path.exists('/var/run/shm.id'):
  572. self.start_guid(notify_function=notify_function)
  573. if not preparing_dvm:
  574. self.start_qrexec_daemon(notify_function=notify_function)
  575. if start_guid and not preparing_dvm \
  576. and os.path.exists('/var/run/shm.id'):
  577. self.start_guid(notify_function=notify_function)
  578. def shutdown(self):
  579. '''Shutdown domain.
  580. :raises QubesException: when domain is already shut down.
  581. '''
  582. if not self.is_running():
  583. raise QubesException("VM already stopped!")
  584. self.libvirt_domain.shutdown()
  585. def force_shutdown(self):
  586. '''Forcefuly shutdown (destroy) domain.
  587. :raises QubesException: when domain is already shut down.
  588. '''
  589. if not self.is_running() and not self.is_paused():
  590. raise QubesException("VM already stopped!")
  591. self.libvirt_domain.destroy()
  592. def suspend(self):
  593. '''Suspend (pause) domain.
  594. :raises QubesException: when domain is already shut down.
  595. :raises NotImplemetedError: when domain has PCI devices attached.
  596. '''
  597. if not self.is_running() and not self.is_paused():
  598. raise QubesException("VM already stopped!")
  599. if len(self.devices['pci']) > 0:
  600. raise NotImplementedError()
  601. else:
  602. self.libvirt_domain.suspend()
  603. def pause(self):
  604. '''Pause (suspend) domain. This currently delegates to \
  605. :py:meth:`suspend`.'''
  606. if not self.is_running():
  607. raise QubesException("VM not running!")
  608. self.suspend()
  609. def resume(self):
  610. '''Resume suspended domain.
  611. :raises NotImplemetedError: when machine is alread suspended.
  612. '''
  613. if self.get_power_state() == "Suspended":
  614. raise NotImplementedError()
  615. else:
  616. self.unpause()
  617. def unpause(self):
  618. '''Resume (unpause) a domain'''
  619. if not self.is_paused():
  620. raise QubesException("VM not paused!")
  621. self.libvirt_domain.resume()
  622. def run(self, command, user=None, autostart=False, notify_function=None,
  623. passio=False, passio_popen=False, passio_stderr=False,
  624. ignore_stderr=False, localcmd=None, wait=False, gui=True,
  625. filter_esc=False):
  626. '''Run specified command inside domain
  627. :param str command: the command to be run
  628. :param str user: user to run the command as
  629. :param bool autostart: if :py:obj:`True`, machine will be started if \
  630. it is not running
  631. :param collections.Callable notify_function: FIXME, may go away
  632. :param bool passio: FIXME
  633. :param bool passio_popen: if :py:obj:`True`, \
  634. :py:class:`subprocess.Popen` object has connected ``stdin`` and \
  635. ``stdout``
  636. :param bool passio_stderr: if :py:obj:`True`, \
  637. :py:class:`subprocess.Popen` has additionaly ``stderr`` connected
  638. :param bool ignore_stderr: if :py:obj:`True`, ``stderr`` is connected \
  639. to :file:`/dev/null`
  640. :param str localcmd: local command to communicate with remote command
  641. :param bool wait: if :py:obj:`True`, wait for command completion
  642. :param bool gui: when autostarting, also start gui daemon
  643. :param bool filter_esc: filter escape sequences to protect terminal \
  644. emulator
  645. '''
  646. if user is None:
  647. user = self.default_user
  648. null = None
  649. if not self.is_running() and not self.is_paused():
  650. if not autostart:
  651. raise QubesException("VM not running")
  652. try:
  653. if notify_function is not None:
  654. notify_function('info',
  655. 'Starting the {!r} VM...'.format(self.name))
  656. self.start(start_guid=gui, notify_function=notify_function)
  657. except (IOError, OSError, QubesException) as e:
  658. raise QubesException(
  659. 'Error while starting the {!r} VM: {!s}'.format(
  660. self.name, e))
  661. except (MemoryError) as err:
  662. raise QubesException('Not enough memory to start {!r} VM! '
  663. 'Close one or more running VMs and try again.'.format(
  664. self.name))
  665. if self.is_paused():
  666. raise QubesException("VM is paused")
  667. if not self.is_qrexec_running():
  668. raise QubesException(
  669. "Domain '{}': qrexec not connected.".format(self.name))
  670. if gui and os.getenv("DISPLAY") is not None \
  671. and not self.is_guid_running():
  672. self.start_guid(verbose=verbose, notify_function=notify_function)
  673. args = [system_path["qrexec_client_path"],
  674. "-d", str(self.name),
  675. '{}:{}'.format(user, command)]
  676. if localcmd is not None:
  677. args += ['-l', localcmd]
  678. if filter_esc:
  679. args += ['-t']
  680. if os.isatty(sys.stderr.fileno()):
  681. args += ['-T']
  682. # TODO: QSB#13
  683. if passio:
  684. if os.name == 'nt':
  685. # wait for qrexec-client to exit, otherwise client is not
  686. # properly attached to console if qvm-run is executed from
  687. # cmd.exe
  688. ret = subprocess.call(args)
  689. exit(ret)
  690. os.execv(system_path["qrexec_client_path"], args)
  691. exit(1)
  692. call_kwargs = {}
  693. if ignore_stderr:
  694. null = open("/dev/null", "w")
  695. call_kwargs['stderr'] = null
  696. if passio_popen:
  697. popen_kwargs = {'stdout': subprocess.PIPE}
  698. popen_kwargs['stdin'] = subprocess.PIPE
  699. if passio_stderr:
  700. popen_kwargs['stderr'] = subprocess.PIPE
  701. else:
  702. popen_kwargs['stderr'] = call_kwargs.get('stderr', None)
  703. p = subprocess.Popen(args, **popen_kwargs)
  704. if null:
  705. null.close()
  706. return p
  707. if not wait:
  708. args += ["-e"]
  709. retcode = subprocess.call(args, **call_kwargs)
  710. if null:
  711. null.close()
  712. return retcode
  713. def run_service(self, service, source=None, user=None,
  714. passio_popen=False, input=None):
  715. '''Run service on this VM
  716. **passio_popen** and **input** are mutually exclusive.
  717. :param str service: service name
  718. :param qubes.vm.QubesVM: source domain as presented to this VM
  719. :param str user: username to run service as
  720. :param bool passio_popen: passed verbatim to :py:meth:`run`
  721. :param str input: string passed as input to service
  722. '''
  723. if input is not None and passio_popen is not None:
  724. raise ValueError("'input' and 'passio_popen' cannot be used "
  725. "together")
  726. source = 'dom0' if source is None else self.app.domains[source].name
  727. # XXX TODO FIXME this looks bad...
  728. if input:
  729. return self.run("QUBESRPC %s %s" % (service, source),
  730. localcmd="echo %s" % input, user=user, wait=True)
  731. else:
  732. return self.run("QUBESRPC %s %s" % (service, source),
  733. passio_popen=passio_popen, user=user, wait=True)
  734. def start_guid(self, extra_guid_args=[]):
  735. '''Launch gui daemon.
  736. GUI daemon securely displays windows from domain.
  737. :param list extra_guid_args: Extra argv to pass to :program:`guid`.
  738. '''
  739. self.log.info('Starting gui daemon')
  740. guid_cmd = [system_path["qubes_guid_path"],
  741. "-d", str(self.xid), "-N", self.name,
  742. "-c", self.label.color,
  743. "-i", self.label.icon_path,
  744. "-l", str(self.label.index)]
  745. guid_cmd += extra_guid_args
  746. if self.debug:
  747. guid_cmd += ['-v', '-v']
  748. # elif not verbose:
  749. guid_cmd += ['-q']
  750. retcode = subprocess.call(guid_cmd)
  751. if retcode != 0:
  752. raise QubesException('Cannot start qubes-guid!')
  753. self.log.info('Sending monitor layout')
  754. try:
  755. subprocess.call(
  756. [system_path['monitor_layout_notify_cmd'], self.name])
  757. except Exception as e:
  758. self.log.error('ERROR: {!s}'.format(e))
  759. self.wait_for_session()
  760. def start_qrexec_daemon(self):
  761. '''Start qrexec daemon.
  762. :raises OSError: when starting fails.
  763. '''
  764. self.log.debug('Starting the qrexec daemon')
  765. qrexec_args = [str(self.xid), self.name, self.default_user]
  766. if not self.debug:
  767. qrexec_args.insert(0, "-q")
  768. qrexec_env = os.environ.copy()
  769. qrexec_env['QREXEC_STARTUP_TIMEOUT'] = str(self.qrexec_timeout)
  770. retcode = subprocess.call([system_path["qrexec_daemon_path"]] +
  771. qrexec_args, env=qrexec_env)
  772. if retcode != 0:
  773. raise OSError('Cannot execute qrexec-daemon!')
  774. def start_qubesdb(self):
  775. '''Start QubesDB daemon.
  776. :raises OSError: when starting fails.
  777. '''
  778. self.log.info('Starting Qubes DB')
  779. retcode = subprocess.call([
  780. system_path["qubesdb_daemon_path"],
  781. str(self.xid),
  782. self.name])
  783. if retcode != 0:
  784. self.force_shutdown()
  785. raise OSError("ERROR: Cannot execute qubesdb-daemon!")
  786. def wait_for_session(self):
  787. '''Wait until machine finished boot sequence.
  788. This is done by executing qubes RPC call that checks if dummy system
  789. service (which is started late in standard runlevel) is active.
  790. '''
  791. self.log.info('Waiting for qubes-session')
  792. # Note : User root is redefined to SYSTEM in the Windows agent code
  793. p = self.run('QUBESRPC qubes.WaitForSession none',
  794. user="root", passio_popen=True, gui=False, wait=True)
  795. p.communicate(input=self.default_user)
  796. def create_on_disk(self, source_template=None):
  797. '''Create files needed for VM.
  798. :param qubes.vm.templatevm.TemplateVM source_template: Template to use
  799. (if :py:obj:`None`, use domain's own template
  800. '''
  801. if source_template is None:
  802. source_template = self.template
  803. assert source_template is not None
  804. self.storage.create_on_disk(verbose, source_template)
  805. if self.updateable:
  806. kernels_dir = source_template.kernels_dir
  807. self.log.info(
  808. 'Copying the kernel (unset kernel to use it): {0}'.format(
  809. kernels_dir))
  810. os.mkdir(self.dir_path + '/kernels')
  811. for f in ("vmlinuz", "initramfs", "modules.img"):
  812. shutil.copy(os.path.join(kernels_dir, f),
  813. os.path.join(self.dir_path,
  814. qubes.config.vm_files["kernels_subdir"], f))
  815. self.log.info('Creating icon symlink: {} -> {}'.format(
  816. self.icon_path, self.label.icon_path))
  817. if hasattr(os, "symlink"):
  818. os.symlink(self.label.icon_path, self.icon_path)
  819. else:
  820. shutil.copy(self.label.icon_path, self.icon_path)
  821. # fire hooks
  822. self.fire_event('domain-created-on-disk', source_template)
  823. def resize_private_img(self, size):
  824. '''Resize private image.'''
  825. # TODO QubesValueError, not assert
  826. assert size >= self.get_private_img_sz(), "Cannot shrink private.img"
  827. # resize the image
  828. self.storage.resize_private_img(size)
  829. # and then the filesystem
  830. # FIXME move this to qubes.storage.xen.XenVMStorage
  831. retcode = 0
  832. if self.is_running():
  833. retcode = self.run('''
  834. while [ "`blockdev --getsize64 /dev/xvdb`" -lt {0} ]; do
  835. head /dev/xvdb >/dev/null;
  836. sleep 0.2;
  837. done;
  838. resize2fs /dev/xvdb'''.format(size), user="root", wait=True)
  839. if retcode != 0:
  840. raise QubesException("resize2fs failed")
  841. def remove_from_disk(self):
  842. '''Remove domain remnants from disk.'''
  843. self.fire_event('domain-removed-from-disk')
  844. self.storage.remove_from_disk()
  845. def clone_disk_files(self, src):
  846. '''Clone files from other vm.
  847. :param qubes.vm.QubesVM src: source VM
  848. '''
  849. if src_vm.is_running():
  850. raise QubesException("Attempt to clone a running VM!")
  851. self.storage.clone_disk_files(src, verbose=False)
  852. if srv.icon_path is not None \
  853. and os.path.exists(src.dir_path) \
  854. and self.icon_path is not None:
  855. if os.path.islink(src.icon_path):
  856. icon_path = os.readlink(src.icon_path)
  857. self.log.info(
  858. 'Creating icon symlink {} -> {}'.format(
  859. self.icon_path, icon_path))
  860. os.symlink(icon_path, self.icon_path)
  861. else:
  862. self.log.info(
  863. 'Copying icon {} -> {}'.format(
  864. src.icon_path, self.icon_path))
  865. shutil.copy(src.icon_path, self.icon_path)
  866. # fire hooks
  867. self.fire_event('cloned-files', src)
  868. # TODO maybe this should be other way: backend.devices['net'].attach(self)
  869. def attach_network(self):
  870. '''Attach network in this machine to it's netvm.'''
  871. if not self.is_running():
  872. raise QubesException("VM not running!")
  873. if self.netvm is None:
  874. raise QubesException("NetVM not set!")
  875. if not netvm.is_running():
  876. self.log.info('Starting NetVM ({0})'.format(netvm.name))
  877. netvm.start()
  878. self.libvirt_domain.attachDevice(lxml.etree.ElementTree(
  879. self.lvxml_net_dev(self.ip, self.mac, self.netvm)).tostring())
  880. def detach_network(self):
  881. '''Detach machine from it's netvm'''
  882. if not self.is_running():
  883. raise QubesException("VM not running!")
  884. if self.netvm is None:
  885. raise QubesException("NetVM not set!")
  886. self.libvirt_domain.detachDevice(lxml.etree.ElementTree(
  887. self.lvxml_net_dev(self.ip, self.mac, self.netvm)).tostring())
  888. #
  889. # methods for querying domain state
  890. #
  891. # state of the machine
  892. def get_power_state(self):
  893. '''Return power state description string.
  894. Return value may be one of those:
  895. =============== ========================================================
  896. return value meaning
  897. =============== ========================================================
  898. ``'Halted'`` Machine is not active.
  899. ``'Transient'`` Machine is running, but does not have :program:`guid`
  900. or :program:`qrexec` available.
  901. ``'Running'`` Machine is ready and running.
  902. ``'Paused'`` Machine is paused (currently not available, see below).
  903. ``'Suspended'`` Machine is S3-suspended.
  904. ``'Halting'`` Machine is in process of shutting down.
  905. ``'Dying'`` Machine crashed and is unusable.
  906. ``'Crashed'`` Machine crashed and is unusable, probably because of
  907. bug in dom0.
  908. ``'NA'`` Machine is in unknown state (most likely libvirt domain
  909. is undefined).
  910. =============== ========================================================
  911. ``Paused`` state is currently unavailable because of missing code in
  912. libvirt/xen glue.
  913. FIXME: graph below may be incomplete and wrong. Click on method name to
  914. see its documentation.
  915. .. graphviz::
  916. digraph {
  917. node [fontname="sans-serif"];
  918. edge [fontname="mono"];
  919. Halted;
  920. NA;
  921. Dying;
  922. Crashed;
  923. Transient;
  924. Halting;
  925. Running;
  926. Paused [color=gray75 fontcolor=gray75];
  927. Suspended;
  928. NA -> Halted;
  929. Halted -> NA [constraint=false];
  930. Halted -> Transient
  931. [xlabel="start()" URL="#qubes.vm.qubesvm.QubesVM.start"];
  932. Transient -> Running;
  933. Running -> Halting
  934. [xlabel="shutdown()"
  935. URL="#qubes.vm.qubesvm.QubesVM.shutdown"
  936. constraint=false];
  937. Halting -> Dying -> Halted [constraint=false];
  938. /* cosmetic, invisible edges to put rank constraint */
  939. Dying -> Halting [style="invis"];
  940. Halting -> Transient [style="invis"];
  941. Running -> Halted
  942. [label="force_shutdown()"
  943. URL="#qubes.vm.qubesvm.QubesVM.force_shutdown"
  944. constraint=false];
  945. Running -> Crashed [constraint=false];
  946. Crashed -> Halted [constraint=false];
  947. Running -> Paused
  948. [label="pause()" URL="#qubes.vm.qubesvm.QubesVM.pause"
  949. color=gray75 fontcolor=gray75];
  950. Running -> Suspended
  951. [label="pause()" URL="#qubes.vm.qubesvm.QubesVM.pause"
  952. color=gray50 fontcolor=gray50];
  953. Paused -> Running
  954. [label="unpause()" URL="#qubes.vm.qubesvm.QubesVM.unpause"
  955. color=gray75 fontcolor=gray75];
  956. Suspended -> Running
  957. [label="unpause()" URL="#qubes.vm.qubesvm.QubesVM.unpause"
  958. color=gray50 fontcolor=gray50];
  959. Running -> Suspended
  960. [label="suspend()" URL="#qubes.vm.qubesvm.QubesVM.suspend"];
  961. Suspended -> Running
  962. [label="resume()" URL="#qubes.vm.qubesvm.QubesVM.resume"];
  963. { rank=source; Halted NA };
  964. { rank=same; Transient Halting };
  965. { rank=same; Crashed Dying };
  966. { rank=sink; Paused Suspended };
  967. }
  968. .. seealso::
  969. http://wiki.libvirt.org/page/VM_lifecycle
  970. Description of VM life cycle from the point of view of libvirt.
  971. https://libvirt.org/html/libvirt-libvirt-domain.html#virDomainState
  972. Libvirt API for changing state of a domain.
  973. '''
  974. libvirt_domain = self.libvirt_domain
  975. if libvirt_domain is None:
  976. return "NA"
  977. if libvirt_domain.isActive():
  978. if libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PAUSED:
  979. return "Paused"
  980. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_CRASHED:
  981. return "Crashed"
  982. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_SHUTDOWN:
  983. return "Halting"
  984. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_SHUTOFF:
  985. return "Dying"
  986. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PMSUSPENDED:
  987. return "Suspended"
  988. else:
  989. if not self.is_fully_usable():
  990. return "Transient"
  991. else:
  992. return "Running"
  993. else:
  994. return 'Halted'
  995. return "NA"
  996. def is_running(self):
  997. '''Check whether this domain is running.
  998. :returns: :py:obj:`True` if this domain is started, \
  999. :py:obj:`False` otherwise.
  1000. :rtype: bool
  1001. '''
  1002. return self.libvirt_domain and self.libvirt_domain.isActive()
  1003. def is_paused(self):
  1004. '''Check whether this domain is paused.
  1005. :returns: :py:obj:`True` if this domain is paused, \
  1006. :py:obj:`False` otherwise.
  1007. :rtype: bool
  1008. '''
  1009. return self.libvirt_domain \
  1010. and self.libvirt_domain.state() == libvirt.VIR_DOMAIN_PAUSED
  1011. def is_guid_running(self):
  1012. '''Check whether gui daemon for this domain is available.
  1013. :returns: :py:obj:`True` if guid is running, \
  1014. :py:obj:`False` otherwise.
  1015. :rtype: bool
  1016. '''
  1017. xid = self.xid
  1018. if xid < 0:
  1019. return False
  1020. if not os.path.exists('/var/run/qubes/guid-running.%d' % xid):
  1021. return False
  1022. return True
  1023. def is_qrexec_running(self):
  1024. '''Check whether qrexec for this domain is available.
  1025. :returns: :py:obj:`True` if qrexec is running, \
  1026. :py:obj:`False` otherwise.
  1027. :rtype: bool
  1028. '''
  1029. if self.xid < 0:
  1030. return False
  1031. return os.path.exists('/var/run/qubes/qrexec.%s' % self.name)
  1032. def is_fully_usable(self):
  1033. '''Check whether domain is running and sane.
  1034. Currently this checks for running guid and qrexec.
  1035. :returns: :py:obj:`True` if qrexec is running, \
  1036. :py:obj:`False` otherwise.
  1037. :rtype: bool
  1038. '''
  1039. # Running gui-daemon implies also VM running
  1040. if not self.is_guid_running():
  1041. return False
  1042. if not self.is_qrexec_running():
  1043. return False
  1044. return True
  1045. # memory and disk
  1046. def get_mem(self):
  1047. '''Get current memory usage from VM.
  1048. :returns: Memory usage [FIXME unit].
  1049. :rtype: FIXME
  1050. '''
  1051. if self.libvirt_domain is None:
  1052. return 0
  1053. if not self.libvirt_domain.isActive():
  1054. return 0
  1055. return self.libvirt_domain.info()[1]
  1056. def get_mem_static_max(self):
  1057. '''Get maximum memory available to VM.
  1058. :returns: Memory limit [FIXME unit].
  1059. :rtype: FIXME
  1060. '''
  1061. if self.libvirt_domain is None:
  1062. return 0
  1063. return self.libvirt_domain.maxMemory()
  1064. def get_per_cpu_time(self):
  1065. '''Get total CPU time burned by this domain since start.
  1066. :returns: CPU time usage [FIXME unit].
  1067. :rtype: FIXME
  1068. '''
  1069. if self.libvirt_domain is None:
  1070. return 0
  1071. if not self.libvirt_domain.isActive():
  1072. return 0
  1073. return libvirt_domain.getCPUStats(
  1074. libvirt.VIR_NODE_CPU_STATS_ALL_CPUS, 0)[0]['cpu_time']/10**9
  1075. # XXX shouldn't this go only to vms that have root image?
  1076. def get_disk_utilization_root_img(self):
  1077. '''Get space that is actually ocuppied by :py:attr:`root_img`.
  1078. Root image is a sparse file, so it is probably much less than logical
  1079. available space.
  1080. :returns: domain's real disk image size [FIXME unit]
  1081. :rtype: FIXME
  1082. .. seealso:: :py:meth:`get_root_img_sz`
  1083. '''
  1084. return qubes.utils.get_disk_usage(self.root_img)
  1085. # XXX shouldn't this go only to vms that have root image?
  1086. def get_root_img_sz(self):
  1087. '''Get image size of :py:attr:`root_img`.
  1088. Root image is a sparse file, so it is probably much more than ocuppied
  1089. physical space.
  1090. :returns: domain's virtual disk size [FIXME unit]
  1091. :rtype: FIXME
  1092. .. seealso:: :py:meth:`get_disk_utilization_root_img`
  1093. '''
  1094. if not os.path.exists(self.root_img):
  1095. return 0
  1096. return os.path.getsize(self.root_img)
  1097. def get_disk_utilization_private_img(self):
  1098. '''Get space that is actually ocuppied by :py:attr:`private_img`.
  1099. Private image is a sparse file, so it is probably much less than
  1100. logical available space.
  1101. :returns: domain's real disk image size [FIXME unit]
  1102. :rtype: FIXME
  1103. .. seealso:: :py:meth:`get_private_img_sz`
  1104. '''
  1105. return qubes.utils.get_disk_usage(self.private_img)
  1106. def get_private_img_sz(self):
  1107. '''Get image size of :py:attr:`private_img`.
  1108. Private image is a sparse file, so it is probably much more than
  1109. ocuppied physical space.
  1110. :returns: domain's virtual disk size [FIXME unit]
  1111. :rtype: FIXME
  1112. .. seealso:: :py:meth:`get_disk_utilization_private_img`
  1113. '''
  1114. return self.storage.get_private_img_sz()
  1115. def get_disk_utilization(self):
  1116. '''Return total space actually occuppied by all files belonging to \
  1117. this domain.
  1118. :returns: domain's total disk usage [FIXME unit]
  1119. :rtype: FIXME
  1120. '''
  1121. return qubes.utils.get_disk_usage(self.dir_path)
  1122. def verify_files(self):
  1123. '''Verify that files accessed by this machine are sane.
  1124. On success, returns normally. On failure, raises exception.
  1125. '''
  1126. self.storage.verify_files()
  1127. if not os.path.exists(os.path.join(self.kernels_dir, 'vmlinuz')):
  1128. raise QubesException(
  1129. "VM kernel does not exist: {0}".\
  1130. format(os.path.join(self.kernels_dir, 'vmlinuz')))
  1131. if not os.path.exists(os.path.join(self.kernels_dir, 'initramfs')):
  1132. raise QubesException(
  1133. "VM initramfs does not exist: {0}".\
  1134. format(os.path.join(self.kernels_dir, 'initramfs')))
  1135. self.fire_event('verify-files')
  1136. return True
  1137. # miscellanous
  1138. def get_start_time(self):
  1139. '''Tell when machine was started.
  1140. :rtype: datetime.datetime
  1141. '''
  1142. if not self.is_running():
  1143. return None
  1144. # TODO shouldn't this be qubesdb?
  1145. start_time = self.app.vmm.xs.read('',
  1146. '/vm/{}/start_time'.format(self.uuid))
  1147. if start_time != '':
  1148. return datetime.datetime.fromtimestamp(float(start_time))
  1149. else:
  1150. return None
  1151. # XXX this probably should go to AppVM
  1152. def is_outdated(self):
  1153. '''Check whether domain needs restart to update root image from \
  1154. template.
  1155. :returns: :py:obj:`True` if is outdated, :py:obj:`False` otherwise.
  1156. :rtype: bool
  1157. '''
  1158. # Makes sense only on VM based on template
  1159. if self.template is None:
  1160. return False
  1161. if not self.is_running():
  1162. return False
  1163. if not hasattr(self.template, 'rootcow_img'):
  1164. return False
  1165. rootimg_inode = os.stat(self.template.root_img)
  1166. try:
  1167. rootcow_inode = os.stat(self.template.rootcow_img)
  1168. except OSError:
  1169. # The only case when rootcow_img doesn't exists is in the middle of
  1170. # commit_changes, so VM is outdated right now
  1171. return True
  1172. current_dmdev = "/dev/mapper/snapshot-{0:x}:{1}-{2:x}:{3}".format(
  1173. rootimg_inode[2], rootimg_inode[1],
  1174. rootcow_inode[2], rootcow_inode[1])
  1175. # FIXME
  1176. # 51712 (0xCA00) is xvda
  1177. # backend node name not available through xenapi :(
  1178. used_dmdev = vmm.xs.read('',
  1179. '/local/domain/0/backend/vbd/{}/51712/node'.format(self.xid))
  1180. return used_dmdev != current_dmdev
  1181. def is_networked(self):
  1182. '''Check whether this VM can reach network (firewall notwithstanding).
  1183. :returns: :py:obj:`True` if is machine can reach network, \
  1184. :py:obj:`False` otherwise.
  1185. :rtype: bool
  1186. '''
  1187. if self.provides_network:
  1188. return True
  1189. return self.netvm is not None
  1190. #
  1191. # helper methods
  1192. #
  1193. def relative_path(self, path):
  1194. '''Return path relative to py:attr:`dir_path`.
  1195. :param str path: Path in question.
  1196. :returns: Relative path.
  1197. '''
  1198. return os.path.relpath(path, self.dir_path)
  1199. # return arg.replace(self.dir_path + '/', '')
  1200. def create_qdb_entries(self):
  1201. '''Create entries in Qubes DB.
  1202. '''
  1203. self.qdb.write("/name", self.name)
  1204. self.qdb.write("/qubes-vm-type", self.type)
  1205. self.qdb.write("/qubes-vm-updateable", str(self.updateable))
  1206. if self.provides_network:
  1207. self.qdb.write("/qubes-netvm-gateway", self.gateway)
  1208. self.qdb.write("/qubes-netvm-secondary-dns", self.secondary_dns)
  1209. self.qdb.write("/qubes-netvm-netmask", self.netmask)
  1210. self.qdb.write("/qubes-netvm-network", self.network)
  1211. if self.netvm is not None:
  1212. self.qdb.write("/qubes-ip", self.ip)
  1213. self.qdb.write("/qubes-netmask", self.netvm.netmask)
  1214. self.qdb.write("/qubes-gateway", self.netvm.gateway)
  1215. self.qdb.write("/qubes-secondary-dns", self.netvm.secondary_dns)
  1216. tzname = qubes.utils.get_timezone()
  1217. if tzname:
  1218. self.qdb.write("/qubes-timezone", tzname)
  1219. for srv in self.services.keys():
  1220. # convert True/False to "1"/"0"
  1221. self.qdb.write("/qubes-service/{0}".format(srv),
  1222. str(int(self.services[srv])))
  1223. self.qdb.write("/qubes-block-devices", '')
  1224. self.qdb.write("/qubes-usb-devices", '')
  1225. self.qdb.write("/qubes-debug-mode", str(int(self.debug)))
  1226. # TODO: Currently the whole qmemman is quite Xen-specific, so stay with
  1227. # xenstore for it until decided otherwise
  1228. if qmemman_present:
  1229. vmm.xs.set_permissions('',
  1230. '/local/domain/{}/memory'.format(self.xid),
  1231. [{'dom': self.xid}])
  1232. self.fire_event('qdb-created')
  1233. def _update_libvirt_domain(self):
  1234. '''Re-initialise :py:attr:`libvirt_domain`.'''
  1235. domain_config = self.create_config_file()
  1236. if self._libvirt_domain is not None:
  1237. self._libvirt_domain.undefine()
  1238. try:
  1239. self._libvirt_domain = vmm.libvirt_conn.defineXML(domain_config)
  1240. self.uuid = uuid.UUID(bytes=self._libvirt_domain.UUID())
  1241. except libvirt.libvirtError:
  1242. if vmm.libvirt_conn.virConnGetLastError()[0] == \
  1243. libvirt.VIR_ERR_NO_DOMAIN:
  1244. # accept the fact that libvirt doesn't know anything about this
  1245. # domain...
  1246. pass
  1247. else:
  1248. raise
  1249. def cleanup_vifs(self):
  1250. '''Remove stale network device backends.
  1251. Xend does not remove vif when backend domain is down, so we must do it
  1252. manually.
  1253. '''
  1254. # FIXME: remove this?
  1255. if not self.is_running():
  1256. return
  1257. dev_basepath = '/local/domain/%d/device/vif' % self.xid
  1258. for dev in self.app.vmm.xs.ls('', dev_basepath):
  1259. # check if backend domain is alive
  1260. backend_xid = int(self.app.vmm.xs.read('',
  1261. '{}/{}/backend-id'.format(dev_basepath, dev)))
  1262. if backend_xid in self.app.vmm.libvirt_conn.listDomainsID():
  1263. # check if device is still active
  1264. if self.app.vmm.xs.read('',
  1265. '{}/{}/state'.format(dev_basepath, dev)) == '4':
  1266. continue
  1267. # remove dead device
  1268. self.app.vmm.xs.rm('', '{}/{}'.format(dev_basepath, dev))
  1269. #
  1270. # workshop -- those are to be reworked later
  1271. #
  1272. def get_prefmem(self):
  1273. # TODO: qmemman is still xen specific
  1274. untrusted_meminfo_key = xs.read('', '/local/domain/%s/memory/meminfo'
  1275. % self.xid)
  1276. if untrusted_meminfo_key is None or untrusted_meminfo_key == '':
  1277. return 0
  1278. domain = qmemman.DomainState(self.xid)
  1279. qmemman_algo.refresh_meminfo_for_domain(domain, untrusted_meminfo_key)
  1280. domain.memory_maximum = self.get_mem_static_max()*1024
  1281. return qmemman_algo.prefmem(domain)/1024
  1282. #
  1283. # landfill -- those are unneeded
  1284. #
  1285. # attrs = {
  1286. # XXX probably will be obsoleted by .events_enabled
  1287. # "_do_not_reset_firewall": { "func": lambda x: False },
  1288. # XXX WTF?
  1289. # "kernels_dir": {
  1290. # # for backward compatibility (or another rare case): kernel=None ->
  1291. # # kernel in VM dir
  1292. # "func": lambda x: \
  1293. # os.path.join(system_path["qubes_kernels_base_dir"],
  1294. # self.kernel) if self.kernel is not None \
  1295. # else os.path.join(self.dir_path,
  1296. # vm_files["kernels_subdir"]) },
  1297. # "_start_guid_first": { "func": lambda x: False },
  1298. # }
  1299. # this function appears unused
  1300. # def _cleanup_zombie_domains(self):
  1301. # """
  1302. # This function is workaround broken libxl (which leaves not fully
  1303. # created domain on failure) and vchan on domain crash behaviour
  1304. # @return: None
  1305. # """
  1306. # xc = self.get_xc_dominfo()
  1307. # if xc and xc['dying'] == 1:
  1308. # # GUID still running?
  1309. # guid_pidfile = '/var/run/qubes/guid-running.%d' % xc['domid']
  1310. # if os.path.exists(guid_pidfile):
  1311. # guid_pid = open(guid_pidfile).read().strip()
  1312. # os.kill(int(guid_pid), 15)
  1313. # # qrexec still running?
  1314. # if self.is_qrexec_running():
  1315. # #TODO: kill qrexec daemon
  1316. # pass