qubesvm.py 57 KB

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