qubesvm.py 55 KB

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