qubesvm.py 58 KB

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