qubesvm.py 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2010-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  5. # Copyright (C) 2013-2015 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  8. #
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; either version 2 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License along
  20. # with this program; if not, write to the Free Software Foundation, Inc.,
  21. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. #
  23. from __future__ import absolute_import
  24. import copy
  25. import base64
  26. import datetime
  27. import os
  28. import os.path
  29. import re
  30. import shutil
  31. import string
  32. import subprocess
  33. import sys
  34. import time
  35. import uuid
  36. import warnings
  37. import grp
  38. import errno
  39. import lxml
  40. import libvirt # pylint: disable=import-error
  41. import qubes
  42. import qubes.config
  43. import qubes.exc
  44. import qubes.storage
  45. import qubes.storage.domain
  46. import qubes.storage.file
  47. import qubes.tools.qvm_ls
  48. import qubes.utils
  49. import qubes.vm
  50. import qubes.vm.mix.net
  51. qmemman_present = False
  52. try:
  53. import qubes.qmemman.client # pylint: disable=wrong-import-position
  54. qmemman_present = True
  55. except ImportError:
  56. pass
  57. MEM_OVERHEAD_BASE = (3 + 1) * 1024 * 1024
  58. MEM_OVERHEAD_PER_VCPU = 3 * 1024 * 1024 / 2
  59. def _setter_qid(self, prop, value):
  60. ''' Helper for setting the domain qid '''
  61. # pylint: disable=unused-argument
  62. value = int(value)
  63. if not 0 <= value <= qubes.config.max_qid:
  64. raise ValueError(
  65. '{} value must be between 0 and qubes.config.max_qid'.format(
  66. prop.__name__))
  67. return value
  68. def validate_name(holder, prop, value):
  69. ''' Check if value is syntactically correct VM name '''
  70. if not isinstance(value, str):
  71. raise TypeError('VM name must be string, {!r} found'.format(
  72. type(value).__name__))
  73. if len(value) > 31:
  74. if holder is not None and prop is not None:
  75. raise qubes.exc.QubesPropertyValueError(holder, prop, value,
  76. '{} value must be shorter than 32 characters'.format(
  77. prop.__name__))
  78. else:
  79. raise qubes.exc.QubesValueError(
  80. 'VM name must be shorter than 32 characters')
  81. # this regexp does not contain '+'; if it had it, we should specifically
  82. # disallow 'lost+found' #1440
  83. if re.match(r"^[a-zA-Z][a-zA-Z0-9_-]*$", value) is None:
  84. if holder is not None and prop is not None:
  85. raise qubes.exc.QubesPropertyValueError(holder, prop, value,
  86. '{} value contains illegal characters'.format(prop.__name__))
  87. else:
  88. raise qubes.exc.QubesValueError(
  89. 'VM name contains illegal characters')
  90. def _setter_name(self, prop, value):
  91. ''' Helper for setting the domain name '''
  92. validate_name(self, prop, value)
  93. if self.is_running():
  94. raise qubes.exc.QubesVMNotHaltedError(
  95. self, 'Cannot change name of running VM')
  96. try:
  97. if self.installed_by_rpm:
  98. raise qubes.exc.QubesException('Cannot rename VM installed by RPM '
  99. '-- first clone VM and then use yum to remove package.')
  100. except AttributeError:
  101. pass
  102. if value in self.app.domains:
  103. raise qubes.exc.QubesPropertyValueError(self, prop, value,
  104. 'VM named {} alread exists'.format(value))
  105. return value
  106. def _setter_kernel(self, prop, value):
  107. ''' Helper for setting the domain kernel and running sanity checks on it.
  108. ''' # pylint: disable=unused-argument
  109. if value is None:
  110. return value
  111. value = str(value)
  112. if '/' in value:
  113. raise qubes.exc.QubesPropertyValueError(self, prop, value,
  114. 'Kernel name cannot contain \'/\'')
  115. dirname = os.path.join(
  116. qubes.config.system_path['qubes_base_dir'],
  117. qubes.config.system_path['qubes_kernels_base_dir'],
  118. value)
  119. if not os.path.exists(dirname):
  120. raise qubes.exc.QubesPropertyValueError(self, prop, value,
  121. 'Kernel {!r} not installed'.format(value))
  122. for filename in ('vmlinuz', 'initramfs'):
  123. if not os.path.exists(os.path.join(dirname, filename)):
  124. raise qubes.exc.QubesPropertyValueError(self, prop, value,
  125. 'Kernel {!r} not properly installed: missing {!r} file'.format(
  126. value, filename))
  127. return value
  128. def _setter_label(self, prop, value):
  129. ''' Helper for setting the domain label '''
  130. # pylint: disable=unused-argument
  131. if isinstance(value, qubes.Label):
  132. return value
  133. if isinstance(value, str) and value.startswith('label-'):
  134. return self.app.labels[int(value.split('-', 1)[1])]
  135. return self.app.get_label(value)
  136. def _setter_positive_int(self, prop, value):
  137. ''' Helper for setting a positive int. Checks that the int is >= 0 '''
  138. # pylint: disable=unused-argument
  139. value = int(value)
  140. if value <= 0:
  141. raise ValueError('Value must be positive')
  142. return value
  143. def _setter_default_user(self, prop, value):
  144. ''' Helper for setting default user '''
  145. value = str(value)
  146. # specifically forbid: ':', ' ', ''', '"'
  147. allowed_chars = string.ascii_letters + string.digits + '_-+,.'
  148. if not all(c in allowed_chars for c in value):
  149. raise qubes.exc.QubesPropertyValueError(self, prop, value,
  150. 'Username can contain only those characters: ' + allowed_chars)
  151. return value
  152. class QubesVM(qubes.vm.mix.net.NetVMMixin, qubes.vm.BaseVM):
  153. '''Base functionality of Qubes VM shared between all VMs.
  154. The following events are raised on this class or its subclasses:
  155. .. event:: domain-init (subject, event)
  156. Fired at the end of class' constructor.
  157. :param subject: Event emitter (the qube object)
  158. :param event: Event name (``'domain-init'``)
  159. .. event:: domain-load (subject, event)
  160. Fired after the qube was loaded from :file:`qubes.xml`
  161. :param subject: Event emitter (the qube object)
  162. :param event: Event name (``'domain-loaded'``)
  163. .. event:: domain-pre-start \
  164. (subject, event, preparing_dvm, start_guid, mem_required)
  165. Fired at the beginning of :py:meth:`start` method.
  166. :param subject: Event emitter (the qube object)
  167. :param event: Event name (``'domain-pre-start'``)
  168. *other arguments are as in :py:meth:`start`*
  169. .. event:: domain-spawn (subject, event, preparing_dvm, start_guid)
  170. Fired after creating libvirt domain.
  171. :param subject: Event emitter (the qube object)
  172. :param event: Event name (``'domain-spawn'``)
  173. *other arguments are as in :py:meth:`start`*
  174. .. event:: domain-start (subject, event, preparing_dvm, start_guid)
  175. Fired at the end of :py:meth:`start` method.
  176. :param subject: Event emitter (the qube object)
  177. :param event: Event name (``'domain-start'``)
  178. *other arguments are as in :py:meth:`start`*
  179. .. event:: domain-pre-shutdown (subject, event, force)
  180. Fired at the beginning of :py:meth:`shutdown` method.
  181. :param subject: Event emitter (the qube object)
  182. :param event: Event name (``'domain-pre-shutdown'``)
  183. :param force: If the shutdown is to be forceful
  184. .. event:: domain-cmd-pre-run (subject, event, start_guid)
  185. Fired at the beginning of :py:meth:`run` method.
  186. :param subject: Event emitter (the qube object)
  187. :param event: Event name (``'domain-cmd-pre-run'``)
  188. :param start_guid: If the gui daemon can be started
  189. .. event:: domain-create-on-disk (subject, event)
  190. Fired at the end of :py:meth:`create_on_disk` method.
  191. :param subject: Event emitter (the qube object)
  192. :param event: Event name (``'domain-create-on-disk'``)
  193. .. event:: domain-remove-from-disk (subject, event)
  194. Fired at the beginning of :py:meth:`remove_from_disk` method, before
  195. the qube directory is removed.
  196. :param subject: Event emitter (the qube object)
  197. :param event: Event name (``'domain-remove-from-disk'``)
  198. .. event:: domain-clone-files (subject, event, src)
  199. Fired at the end of :py:meth:`clone_disk_files` method.
  200. :param subject: Event emitter (the qube object)
  201. :param event: Event name (``'domain-clone-files'``)
  202. :param src: source qube
  203. .. event:: domain-verify-files (subject, event)
  204. Fired at the end of :py:meth:`clone_disk_files` method.
  205. :param subject: Event emitter (the qube object)
  206. :param event: Event name (``'domain-verify-files'``)
  207. If you think some files are missing or damaged, raise an exception.
  208. .. event:: domain-is-fully-usable (subject, event)
  209. Fired at the end of :py:meth:`clone_disk_files` method.
  210. :param subject: Event emitter (the qube object)
  211. :param event: Event name (``'domain-is-fully-usable'``)
  212. You may ``yield False`` from the handler if you think the qube is
  213. not fully usable. This will cause the domain to be in "transient"
  214. state in the domain lifecycle.
  215. .. event:: domain-qtb-create (subject, event)
  216. Fired at the end of :py:meth:`create_qdb_entries` method.
  217. :param subject: Event emitter (the qube object)
  218. :param event: Event name (``'domain-qtb-create'``)
  219. This event is a good place to add your custom entries to the qdb.
  220. .. event:: backup-get-files (subject, event)
  221. Collects additional file to be included in a backup.
  222. :param subject: Event emitter (the qube object)
  223. :param event: Event name (``'backup-get-files'``)
  224. Handlers should yield paths of the files.
  225. .. event:: domain-restore (subject, event)
  226. Domain was just restored from backup, although the storage was not
  227. yet verified and the app object was not yet saved.
  228. :param subject: Event emitter (the qube object)
  229. :param event: Event name (``'domain-restore'``)
  230. .. event:: domain-feature-set (subject, event, key, value)
  231. A feature was changed.
  232. :param subject: Event emitter (the qube object)
  233. :param event: Event name (``'domain-feature-set'``)
  234. :param key: feature name
  235. :param value: new value
  236. .. event:: domain-feature-delete (subject, event, key)
  237. A feature was removed.
  238. :param subject: Event emitter (the qube object)
  239. :param event: Event name (``'domain-feature-set'``)
  240. :param key: feature name
  241. .. event:: feature-request (subject, event, *, untrusted_features)
  242. The domain is performing a feature request.
  243. :param subject: Event emitter (the qube object)
  244. :param event: Event name (``'feature-request'``)
  245. :param untrusted_features: :py:class:`dict` containing the feature \
  246. request
  247. The content of the `untrusted_features` variable is, as the name
  248. implies, **UNTRUSTED**. The remind this to programmer, the variable
  249. name has to be exactly as provided.
  250. It is up to the extensions to decide, what to do with request,
  251. ranging from plainly ignoring the request to verbatim copy into
  252. :py:attr:`features` with only minimal sanitisation.
  253. .. event:: monitor-layout-change (subject, event, monitor_layout)
  254. Desktop layout was changed, probably because a display was plugged
  255. in or out.
  256. :param subject: Event emitter (the qube object)
  257. :param event: Event name (``'monitor-layout-change'``)
  258. :param monitor_layout: The new layout
  259. .. event:: firewall-changed (subject, event)
  260. Firewall was changed.
  261. :param subject: Event emitter (the qube object)
  262. :param event: Event name (``'firewall-changed'``)
  263. .. event:: net-domain-connect (subject, event, vm)
  264. Fired after connecting a domiain to this vm.
  265. :param subject: Event emitter (the qube object)
  266. :param event: Event name (``'net-domain-connect'``)
  267. :param vm: The domain that was just connected.
  268. On the `vm` object there was probably ``property-set:netvm`` fired
  269. earlier.
  270. '''
  271. #
  272. # per-class properties
  273. #
  274. #: directory in which domains of this class will reside
  275. dir_path_prefix = qubes.config.system_path['qubes_appvms_dir']
  276. #
  277. # properties loaded from XML
  278. #
  279. label = qubes.property('label',
  280. setter=_setter_label,
  281. saver=(lambda self, prop, value: 'label-{}'.format(value.index)),
  282. ls_width=14,
  283. doc='''Colourful label assigned to VM. This is where the colour of the
  284. padlock is set.''')
  285. # provides_network = qubes.property('provides_network',
  286. # type=bool, setter=qubes.property.bool,
  287. # doc='`True` if it is NetVM or ProxyVM, false otherwise.')
  288. qid = qubes.property('qid', type=int, write_once=True,
  289. setter=_setter_qid,
  290. clone=False,
  291. ls_width=3,
  292. doc='''Internal, persistent identificator of particular domain. Note
  293. this is different from Xen domid.''')
  294. name = qubes.property('name', type=str,
  295. clone=False,
  296. ls_width=31,
  297. doc='User-specified name of the domain.')
  298. uuid = qubes.property('uuid', type=uuid.UUID, write_once=True,
  299. clone=False,
  300. ls_width=36,
  301. doc='UUID from libvirt.')
  302. hvm = qubes.property('hvm',
  303. type=bool, setter=qubes.property.bool,
  304. default=False,
  305. doc='''Use full virtualisation (HVM) for this qube,
  306. instead of paravirtualisation (PV)''')
  307. installed_by_rpm = qubes.property('installed_by_rpm',
  308. type=bool, setter=qubes.property.bool,
  309. default=False,
  310. doc='''If this domain's image was installed from package tracked by
  311. package manager.''')
  312. memory = qubes.property('memory', type=int,
  313. setter=_setter_positive_int,
  314. default=(lambda self:
  315. qubes.config.defaults['hvm_memory' if self.hvm else 'memory']),
  316. doc='Memory currently available for this VM.')
  317. maxmem = qubes.property('maxmem', type=int,
  318. setter=_setter_positive_int,
  319. default=(lambda self:
  320. int(min(self.app.host.memory_total / 1024 / 2, 4000))),
  321. doc='''Maximum amount of memory available for this VM (for the purpose
  322. of the memory balancer).''')
  323. internal = qubes.property('internal', default=False,
  324. type=bool, setter=qubes.property.bool,
  325. doc='''Internal VM (not shown in qubes-manager, don't create appmenus
  326. entries.''')
  327. vcpus = qubes.property('vcpus',
  328. type=int,
  329. setter=_setter_positive_int,
  330. default=(lambda self: self.app.host.no_cpus),
  331. ls_width=2,
  332. doc='FIXME')
  333. # CORE2: swallowed uses_default_kernel
  334. kernel = qubes.property('kernel', type=str,
  335. setter=_setter_kernel,
  336. default=(lambda self: self.app.default_kernel),
  337. ls_width=12,
  338. doc='Kernel used by this domain.')
  339. # CORE2: swallowed uses_default_kernelopts
  340. kernelopts = qubes.property('kernelopts', type=str, load_stage=4,
  341. default=(lambda self: qubes.config.defaults['kernelopts_pcidevs']
  342. if list(self.devices['pci'].attached(persistent=True))
  343. else self.template.kernelopts if hasattr(self, 'template')
  344. else qubes.config.defaults['kernelopts']),
  345. ls_width=30,
  346. doc='Kernel command line passed to domain.')
  347. debug = qubes.property('debug', type=bool, default=False,
  348. setter=qubes.property.bool,
  349. doc='Turns on debugging features.')
  350. # XXX what this exactly does?
  351. # XXX shouldn't this go to standalone VM and TemplateVM, and leave here
  352. # only plain property?
  353. default_user = qubes.property('default_user', type=str,
  354. default=(lambda self: self.template.default_user
  355. if hasattr(self, 'template') else 'user'),
  356. setter=_setter_default_user,
  357. ls_width=12,
  358. doc='FIXME')
  359. # @property
  360. # def default_user(self):
  361. # if self.template is not None:
  362. # return self.template.default_user
  363. # else:
  364. # return self._default_user
  365. qrexec_timeout = qubes.property('qrexec_timeout', type=int, default=60,
  366. setter=_setter_positive_int,
  367. ls_width=3,
  368. doc='''Time in seconds after which qrexec connection attempt is deemed
  369. failed. Operating system inside VM should be able to boot in this
  370. time.''')
  371. autostart = qubes.property('autostart', default=False,
  372. type=bool, setter=qubes.property.bool,
  373. doc='''Setting this to `True` means that VM should be autostarted on
  374. dom0 boot.''')
  375. include_in_backups = qubes.property('include_in_backups',
  376. default=(lambda self: not self.internal),
  377. type=bool, setter=qubes.property.bool,
  378. doc='If this domain is to be included in default backup.')
  379. # format got changed from %s to str(datetime.datetime)
  380. backup_timestamp = qubes.property('backup_timestamp', default=None,
  381. setter=(lambda self, prop, value:
  382. value if isinstance(value, datetime.datetime) else
  383. datetime.datetime.fromtimestamp(int(value))),
  384. saver=(lambda self, prop, value: value.strftime('%s')),
  385. doc='FIXME')
  386. default_dispvm = qubes.VMProperty('default_dispvm',
  387. load_stage=4,
  388. allow_none=True,
  389. default=(lambda self: self.app.default_dispvm),
  390. doc='Default VM to be used as Disposable VM for service calls.')
  391. updateable = qubes.property('updateable',
  392. default=(lambda self: not hasattr(self, 'template')),
  393. type=bool,
  394. setter=qubes.property.forbidden,
  395. doc='True if this machine may be updated on its own.')
  396. #
  397. # static, class-wide properties
  398. #
  399. #
  400. # properties not loaded from XML, calculated at run-time
  401. #
  402. def __str__(self):
  403. return self.name
  404. # VMM-related
  405. @qubes.tools.qvm_ls.column(width=3)
  406. @property
  407. def xid(self):
  408. '''Xen ID.
  409. Or not Xen, but ID.
  410. '''
  411. if self.libvirt_domain is None:
  412. return -1
  413. try:
  414. return self.libvirt_domain.ID()
  415. except libvirt.libvirtError as e:
  416. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  417. return -1
  418. else:
  419. self.log.exception('libvirt error code: {!r}'.format(
  420. e.get_error_code()))
  421. raise
  422. @property
  423. def attached_volumes(self):
  424. result = []
  425. xml_desc = self.libvirt_domain.XMLDesc()
  426. xml = lxml.etree.fromstring(xml_desc)
  427. for disk in xml.xpath("//domain/devices/disk"):
  428. if disk.find('backenddomain') is not None:
  429. pool_name = 'p_%s' % disk.find('backenddomain').get('name')
  430. pool = self.app.pools[pool_name]
  431. vid = disk.find('source').get('dev').split('/dev/')[1]
  432. for volume in pool.volumes:
  433. if volume.vid == vid:
  434. result += [volume]
  435. break
  436. return result + list(self.volumes.values())
  437. @property
  438. def libvirt_domain(self):
  439. '''Libvirt domain object from libvirt.
  440. May be :py:obj:`None`, if libvirt knows nothing about this domain.
  441. '''
  442. if self._libvirt_domain is not None:
  443. return self._libvirt_domain
  444. # XXX _update_libvirt_domain?
  445. try:
  446. self._libvirt_domain = self.app.vmm.libvirt_conn.lookupByUUID(
  447. self.uuid.bytes)
  448. except libvirt.libvirtError as e:
  449. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  450. self._update_libvirt_domain()
  451. else:
  452. raise
  453. return self._libvirt_domain
  454. @property
  455. def block_devices(self):
  456. ''' Return all :py:class:`qubes.devices.BlockDevice`s for current domain
  457. for serialization in the libvirt XML template as <disk>.
  458. '''
  459. return [v.block_device() for v in self.volumes.values()]
  460. @property
  461. def qdb(self):
  462. '''QubesDB handle for this domain.'''
  463. if self._qdb_connection is None:
  464. if self.is_running():
  465. import qubesdb # pylint: disable=import-error
  466. self._qdb_connection = qubesdb.QubesDB(self.name)
  467. return self._qdb_connection
  468. @property
  469. def dir_path(self):
  470. '''Root directory for files related to this domain'''
  471. return os.path.join(
  472. qubes.config.system_path['qubes_base_dir'],
  473. self.dir_path_prefix,
  474. self.name)
  475. @property
  476. def icon_path(self):
  477. return os.path.join(self.dir_path, 'icon.png')
  478. @property
  479. def conf_file(self):
  480. return os.path.join(self.dir_path, 'libvirt.xml')
  481. # network-related
  482. #
  483. # constructor
  484. #
  485. def __init__(self, app, xml, volume_config=None, **kwargs):
  486. super(QubesVM, self).__init__(app, xml, **kwargs)
  487. self.volumes = {}
  488. self.storage = None
  489. if volume_config is None:
  490. volume_config = {}
  491. if hasattr(self, 'volume_config'):
  492. if xml is not None:
  493. for node in xml.xpath('volume-config/volume'):
  494. name = node.get('name')
  495. assert name
  496. for key, value in node.items():
  497. # pylint: disable=no-member
  498. if value == 'True':
  499. value = True
  500. try:
  501. self.volume_config[name][key] = value
  502. except KeyError:
  503. self.volume_config[name] = {key: value}
  504. for name, conf in volume_config.items():
  505. for key, value in conf.items():
  506. # pylint: disable=no-member
  507. try:
  508. self.volume_config[name][key] = value
  509. except KeyError:
  510. self.volume_config[name] = {key: value}
  511. elif volume_config:
  512. raise TypeError(
  513. 'volume_config specified, but {} did not expect that.'.format(
  514. self.__class__.__name__))
  515. # Init private attrs
  516. self._libvirt_domain = None
  517. self._qdb_connection = None
  518. if xml is None:
  519. # we are creating new VM and attributes came through kwargs
  520. assert hasattr(self, 'qid')
  521. assert hasattr(self, 'name')
  522. # Linux specific cap: max memory can't scale beyond 10.79*init_mem
  523. # see https://groups.google.com/forum/#!topic/qubes-devel/VRqkFj1IOtA
  524. if self.maxmem > self.memory * 10:
  525. self.maxmem = self.memory * 10
  526. # By default allow use all VCPUs
  527. # if not hasattr(self, 'vcpus') and not self.app.vmm.offline_mode:
  528. # self.vcpus = self.app.host.no_cpus
  529. if xml is None:
  530. # new qube, disable updates check if requested for new qubes
  531. # SEE: 1637 when features are done, migrate to plugin
  532. if not self.app.check_updates_vm:
  533. self.features['check-updates'] = None
  534. # will be initialized after loading all the properties
  535. # fire hooks
  536. if xml is None:
  537. self.events_enabled = True
  538. self.fire_event('domain-init')
  539. def __hash__(self):
  540. return self.qid
  541. def __lt__(self, other):
  542. return self.name < other.name
  543. def __xml__(self):
  544. element = super(QubesVM, self).__xml__()
  545. if hasattr(self, 'volumes'):
  546. volume_config_node = lxml.etree.Element('volume-config')
  547. for volume in self.volumes.values():
  548. volume_config_node.append(volume.__xml__())
  549. element.append(volume_config_node)
  550. return element
  551. #
  552. # event handlers
  553. #
  554. @qubes.events.handler('domain-init', 'domain-load')
  555. def on_domain_init_loaded(self, event):
  556. # pylint: disable=unused-argument
  557. if not hasattr(self, 'uuid'):
  558. self.uuid = uuid.uuid4()
  559. # Initialize VM image storage class
  560. self.storage = qubes.storage.Storage(self)
  561. vm_pool = qubes.storage.domain.DomainPool(self)
  562. self.app.pools[vm_pool.name] = vm_pool
  563. @qubes.events.handler('property-set:label')
  564. def on_property_set_label(self, event, name, newvalue, oldvalue=None):
  565. # pylint: disable=unused-argument
  566. if self.icon_path:
  567. try:
  568. os.remove(self.icon_path)
  569. except OSError:
  570. pass
  571. if hasattr(os, "symlink"):
  572. os.symlink(newvalue.icon_path, self.icon_path)
  573. subprocess.call(['sudo', 'xdg-icon-resource', 'forceupdate'])
  574. else:
  575. shutil.copy(newvalue.icon_path, self.icon_path)
  576. @qubes.events.handler('property-pre-set:name')
  577. def on_property_pre_set_name(self, event, name, newvalue, oldvalue=None):
  578. # pylint: disable=unused-argument
  579. try:
  580. self.app.domains[newvalue]
  581. except KeyError:
  582. pass
  583. else:
  584. raise qubes.exc.QubesValueError(
  585. 'VM named {!r} already exists'.format(newvalue))
  586. # TODO not self.is_stopped() would be more appropriate
  587. if self.is_running():
  588. raise qubes.exc.QubesVMNotHaltedError(
  589. 'Cannot change name of running domain {!r}'.format(oldvalue))
  590. if self.autostart:
  591. subprocess.check_call(['sudo', 'systemctl', '-q', 'disable',
  592. 'qubes-vm@{}.service'.format(oldvalue)])
  593. @qubes.events.handler('property-set:name')
  594. def on_property_set_name(self, event, name, newvalue, oldvalue=None):
  595. # pylint: disable=unused-argument
  596. self.init_log()
  597. self.storage.rename(oldvalue, newvalue)
  598. if self._libvirt_domain is not None:
  599. self.libvirt_domain.undefine()
  600. self._libvirt_domain = None
  601. if self._qdb_connection is not None:
  602. self._qdb_connection.close()
  603. self._qdb_connection = None
  604. self._update_libvirt_domain()
  605. if self.autostart:
  606. self.autostart = self.autostart
  607. @qubes.events.handler('property-pre-set:autostart')
  608. def on_property_pre_set_autostart(self, event, prop, newvalue,
  609. oldvalue=None):
  610. # pylint: disable=unused-argument
  611. # workaround https://bugzilla.redhat.com/show_bug.cgi?id=1181922
  612. if newvalue:
  613. retcode = subprocess.call(
  614. ["sudo", "ln", "-sf",
  615. "/usr/lib/systemd/system/qubes-vm@.service",
  616. "/etc/systemd/system/multi-user.target.wants/qubes-vm@"
  617. "{}.service".format(self.name)])
  618. else:
  619. retcode = subprocess.call(
  620. ['sudo', 'systemctl', 'disable',
  621. 'qubes-vm@{}.service'.format(self.name)])
  622. if retcode:
  623. raise qubes.exc.QubesException(
  624. 'Failed to set autostart for VM in systemd')
  625. @qubes.events.handler('property-pre-del:autostart')
  626. def on_property_pre_del_autostart(self, event, prop, oldvalue=None):
  627. # pylint: disable=unused-argument
  628. if oldvalue:
  629. retcode = subprocess.call(
  630. ['sudo', 'systemctl', 'disable',
  631. 'qubes-vm@{}.service'.format(self.name)])
  632. if retcode:
  633. raise qubes.exc.QubesException(
  634. 'Failed to reset autostart for VM in systemd')
  635. #
  636. # methods for changing domain state
  637. #
  638. def start(self, preparing_dvm=False, start_guid=True,
  639. notify_function=None, mem_required=None):
  640. '''Start domain
  641. :param bool preparing_dvm: FIXME
  642. :param bool start_guid: FIXME
  643. :param collections.Callable notify_function: FIXME
  644. :param int mem_required: FIXME
  645. '''
  646. # Intentionally not used is_running(): eliminate also "Paused",
  647. # "Crashed", "Halting"
  648. if self.get_power_state() != 'Halted':
  649. raise qubes.exc.QubesVMNotHaltedError(self)
  650. self.log.info('Starting {}'.format(self.name))
  651. self.fire_event_pre('domain-pre-start', preparing_dvm=preparing_dvm,
  652. start_guid=start_guid, mem_required=mem_required)
  653. self.storage.verify()
  654. if self.netvm is not None:
  655. # pylint: disable = no-member
  656. if self.netvm.qid != 0:
  657. if not self.netvm.is_running():
  658. self.netvm.start(start_guid=start_guid,
  659. notify_function=notify_function)
  660. self.storage.start()
  661. self._update_libvirt_domain()
  662. qmemman_client = self.request_memory(mem_required)
  663. try:
  664. self.libvirt_domain.createWithFlags(libvirt.VIR_DOMAIN_START_PAUSED)
  665. except:
  666. if qmemman_client:
  667. qmemman_client.close()
  668. raise
  669. try:
  670. self.fire_event('domain-spawn',
  671. preparing_dvm=preparing_dvm, start_guid=start_guid)
  672. self.log.info('Setting Qubes DB info for the VM')
  673. self.start_qubesdb()
  674. self.create_qdb_entries()
  675. if preparing_dvm:
  676. self.qdb.write('/dvm', '1')
  677. self.log.warning('Activating the {} VM'.format(self.name))
  678. self.libvirt_domain.resume()
  679. # close() is not really needed, because the descriptor is
  680. # close-on-exec anyway, the reason to postpone close() is that
  681. # possibly xl is not done constructing the domain after its main
  682. # process exits so we close() when we know the domain is up the
  683. # successful unpause is some indicator of it
  684. if qmemman_client:
  685. qmemman_client.close()
  686. # if self._start_guid_first and start_guid and not preparing_dvm \
  687. # and os.path.exists('/var/run/shm.id'):
  688. # self.start_guid()
  689. if not preparing_dvm:
  690. self.start_qrexec_daemon()
  691. self.fire_event('domain-start',
  692. preparing_dvm=preparing_dvm, start_guid=start_guid)
  693. except: # pylint: disable=bare-except
  694. if self.is_running() or self.is_paused():
  695. # This avoids losing the exception if an exception is raised in
  696. # self.force_shutdown(), because the vm is not running or paused
  697. self.force_shutdown()
  698. raise
  699. return self
  700. def shutdown(self, force=False, wait=False):
  701. '''Shutdown domain.
  702. :raises qubes.exc.QubesVMNotStartedError: \
  703. when domain is already shut down.
  704. '''
  705. if self.is_halted():
  706. raise qubes.exc.QubesVMNotStartedError(self)
  707. self.fire_event_pre('domain-pre-shutdown', force=force)
  708. self.libvirt_domain.shutdown()
  709. self.storage.stop()
  710. while wait and not self.is_halted():
  711. time.sleep(0.25)
  712. return self
  713. def kill(self):
  714. '''Forcefuly shutdown (destroy) domain.
  715. :raises qubes.exc.QubesVMNotStartedError: \
  716. when domain is already shut down.
  717. '''
  718. if not self.is_running() and not self.is_paused():
  719. raise qubes.exc.QubesVMNotStartedError(self)
  720. self.libvirt_domain.destroy()
  721. self.storage.stop()
  722. return self
  723. def force_shutdown(self, *args, **kwargs):
  724. '''Deprecated alias for :py:meth:`kill`'''
  725. warnings.warn(
  726. 'Call to deprecated function force_shutdown(), use kill() instead',
  727. DeprecationWarning, stacklevel=2)
  728. self.kill(*args, **kwargs)
  729. return self
  730. def suspend(self):
  731. '''Suspend (pause) domain.
  732. :raises qubes.exc.QubesVMNotRunnignError: \
  733. when domain is already shut down.
  734. :raises qubes.exc.QubesNotImplemetedError: \
  735. when domain has PCI devices attached.
  736. '''
  737. if not self.is_running() and not self.is_paused():
  738. raise qubes.exc.QubesVMNotRunningError(self)
  739. if list(self.devices['pci'].attached()):
  740. raise qubes.exc.QubesNotImplementedError(
  741. 'Cannot suspend domain {!r} which has PCI devices attached'
  742. .format(self.name))
  743. else:
  744. self.libvirt_domain.suspend()
  745. return self
  746. def pause(self):
  747. '''Pause (suspend) domain. This currently delegates to \
  748. :py:meth:`suspend`.'''
  749. if not self.is_running():
  750. raise qubes.exc.QubesVMNotRunningError(self)
  751. self.suspend()
  752. return self
  753. def resume(self):
  754. '''Resume suspended domain.
  755. :raises qubes.exc.QubesVMNotSuspendedError: when machine is not paused
  756. :raises qubes.exc.QubesVMError: when machine is suspended
  757. '''
  758. if self.get_power_state() == "Suspended":
  759. raise qubes.exc.QubesVMError(self,
  760. 'Cannot resume suspended domain {!r}'.format(self.name))
  761. else:
  762. self.unpause()
  763. return self
  764. def unpause(self):
  765. '''Resume (unpause) a domain'''
  766. if not self.is_paused():
  767. raise qubes.exc.QubesVMNotPausedError(self)
  768. self.libvirt_domain.resume()
  769. return self
  770. def run(self, command, user=None, autostart=False, notify_function=None,
  771. passio=False, passio_popen=False, passio_stderr=False,
  772. ignore_stderr=False, localcmd=None, wait=False, gui=True,
  773. filter_esc=False):
  774. '''Run specified command inside domain
  775. :param str command: the command to be run
  776. :param str user: user to run the command as
  777. :param bool autostart: if :py:obj:`True`, machine will be started if \
  778. it is not running
  779. :param collections.Callable notify_function: FIXME, may go away
  780. :param bool passio: FIXME
  781. :param bool passio_popen: if :py:obj:`True`, \
  782. :py:class:`subprocess.Popen` object has connected ``stdin`` and \
  783. ``stdout``
  784. :param bool passio_stderr: if :py:obj:`True`, \
  785. :py:class:`subprocess.Popen` has additionaly ``stderr`` connected
  786. :param bool ignore_stderr: if :py:obj:`True`, ``stderr`` is connected \
  787. to :file:`/dev/null`
  788. :param str localcmd: local command to communicate with remote command
  789. :param bool wait: if :py:obj:`True`, wait for command completion
  790. :param bool gui: when autostarting, also start gui daemon
  791. :param bool filter_esc: filter escape sequences to protect terminal \
  792. emulator
  793. '''
  794. if user is None:
  795. user = self.default_user
  796. null = None
  797. if not self.is_running() and not self.is_paused():
  798. if not autostart:
  799. raise qubes.exc.QubesVMNotRunningError(self)
  800. if notify_function is not None:
  801. notify_function('info',
  802. 'Starting the {!r} VM...'.format(self.name))
  803. self.start(start_guid=gui, notify_function=notify_function)
  804. if self.is_paused():
  805. # XXX what about autostart?
  806. raise qubes.exc.QubesVMNotRunningError(
  807. self, 'Domain {!r} is paused'.format(self.name))
  808. if not self.is_qrexec_running():
  809. raise qubes.exc.QubesVMError(
  810. self, 'Domain {!r}: qrexec not connected'.format(self.name))
  811. self.fire_event_pre('domain-cmd-pre-run', start_guid=gui)
  812. args = [qubes.config.system_path['qrexec_client_path'],
  813. '-d', str(self.name),
  814. '{}:{}'.format(user, command)]
  815. if localcmd is not None:
  816. args += ['-l', localcmd]
  817. if filter_esc:
  818. args += ['-t']
  819. if os.isatty(sys.stderr.fileno()):
  820. args += ['-T']
  821. call_kwargs = {}
  822. if ignore_stderr or not passio:
  823. null = open("/dev/null", "r+")
  824. call_kwargs['stderr'] = null
  825. if not passio:
  826. call_kwargs['stdin'] = null
  827. call_kwargs['stdout'] = null
  828. if passio_popen:
  829. popen_kwargs = {
  830. 'stdout': subprocess.PIPE,
  831. 'stdin': subprocess.PIPE
  832. }
  833. if passio_stderr:
  834. popen_kwargs['stderr'] = subprocess.PIPE
  835. else:
  836. popen_kwargs['stderr'] = call_kwargs.get('stderr', None)
  837. p = subprocess.Popen(args, **popen_kwargs)
  838. if null:
  839. null.close()
  840. return p
  841. if not wait and not passio:
  842. args += ["-e"]
  843. retcode = subprocess.call(args, **call_kwargs)
  844. if null:
  845. null.close()
  846. return retcode
  847. def run_service(self, service, source=None, user=None,
  848. passio_popen=False, input=None, localcmd=None, gui=False,
  849. wait=True, passio_stderr=False):
  850. '''Run service on this VM
  851. **passio_popen** and **input** are mutually exclusive.
  852. :param str service: service name
  853. :param qubes.vm.qubesvm.QubesVM: source domain as presented to this VM
  854. :param str user: username to run service as
  855. :param bool passio_popen: passed verbatim to :py:meth:`run`
  856. :param str input: string passed as input to service
  857. ''' # pylint: disable=redefined-builtin
  858. if len([i for i in (input, passio_popen, localcmd) if i]) > 1:
  859. raise TypeError(
  860. 'input, passio_popen and localcmd cannot be used together')
  861. if not wait and (localcmd or input):
  862. raise ValueError("Cannot use wait=False with input or "
  863. "localcmd specified")
  864. if passio_stderr and not passio_popen:
  865. raise TypeError('passio_stderr can be used only with passio_popen')
  866. if input:
  867. # Internally use passio_popen, but do not return POpen object to
  868. # the user - use internally for p.communicate()
  869. passio_popen = True
  870. passio_stderr = True
  871. source = 'dom0' if source is None else self.app.domains[source].name
  872. p = self.run('QUBESRPC {} {}'.format(service, source),
  873. localcmd=localcmd, passio_popen=passio_popen, user=user, wait=wait,
  874. gui=gui, passio_stderr=passio_stderr)
  875. if input:
  876. p.communicate(input)
  877. return p.returncode
  878. else:
  879. return p
  880. def request_memory(self, mem_required=None):
  881. # overhead of per-qube/per-vcpu Xen structures,
  882. # taken from OpenStack nova/virt/xenapi/driver.py
  883. # see https://wiki.openstack.org/wiki/XenServer/Overhead
  884. # add an extra MB because Nova rounds up to MBs
  885. if not qmemman_present:
  886. return
  887. if mem_required is None:
  888. mem_required = int(self.memory) * 1024 * 1024
  889. qmemman_client = qubes.qmemman.client.QMemmanClient()
  890. try:
  891. mem_required_with_overhead = mem_required + MEM_OVERHEAD_BASE \
  892. + self.vcpus * MEM_OVERHEAD_PER_VCPU
  893. got_memory = qmemman_client.request_memory(
  894. mem_required_with_overhead)
  895. except IOError as e:
  896. raise IOError('Failed to connect to qmemman: {!s}'.format(e))
  897. if not got_memory:
  898. qmemman_client.close()
  899. raise qubes.exc.QubesMemoryError(self)
  900. return qmemman_client
  901. @staticmethod
  902. def start_daemon(command, **kwargs):
  903. '''Start a daemon for the VM
  904. This function take care to run it as appropriate user.
  905. :param command: command to run (array for
  906. :py:meth:`subprocess.check_call`)
  907. :param kwargs: args for :py:meth:`subprocess.check_call`
  908. :return: None
  909. '''
  910. prefix_cmd = []
  911. if os.getuid() == 0:
  912. # try to always have VM daemons running as normal user, otherwise
  913. # some files (like clipboard) may be created as root and cause
  914. # permission problems
  915. qubes_group = grp.getgrnam('qubes')
  916. prefix_cmd = ['runuser', '-u', qubes_group.gr_mem[0], '--']
  917. subprocess.check_call(prefix_cmd + command, **kwargs)
  918. def start_qrexec_daemon(self):
  919. '''Start qrexec daemon.
  920. :raises OSError: when starting fails.
  921. '''
  922. self.log.debug('Starting the qrexec daemon')
  923. qrexec_args = [str(self.xid), self.name, self.default_user]
  924. if not self.debug:
  925. qrexec_args.insert(0, "-q")
  926. qrexec_env = os.environ.copy()
  927. if not self.features.check_with_template('qrexec', not self.hvm):
  928. self.log.debug(
  929. 'Starting the qrexec daemon in background, because of features')
  930. qrexec_env['QREXEC_STARTUP_NOWAIT'] = '1'
  931. else:
  932. qrexec_env['QREXEC_STARTUP_TIMEOUT'] = str(self.qrexec_timeout)
  933. try:
  934. self.start_daemon(
  935. [qubes.config.system_path["qrexec_daemon_path"]] + qrexec_args,
  936. env=qrexec_env)
  937. except subprocess.CalledProcessError:
  938. raise qubes.exc.QubesVMError(self, 'Cannot execute qrexec-daemon!')
  939. def start_qubesdb(self):
  940. '''Start QubesDB daemon.
  941. :raises OSError: when starting fails.
  942. '''
  943. # drop old connection to QubesDB, if any
  944. self._qdb_connection = None
  945. self.log.info('Starting Qubes DB')
  946. try:
  947. self.start_daemon([
  948. qubes.config.system_path["qubesdb_daemon_path"],
  949. str(self.xid),
  950. self.name])
  951. except subprocess.CalledProcessError:
  952. raise qubes.exc.QubesException('Cannot execute qubesdb-daemon')
  953. def wait_for_session(self):
  954. '''Wait until machine finished boot sequence.
  955. This is done by executing qubes RPC call that checks if dummy system
  956. service (which is started late in standard runlevel) is active.
  957. '''
  958. self.log.info('Waiting for qubes-session')
  959. # Note : User root is redefined to SYSTEM in the Windows agent code
  960. p = self.run('QUBESRPC qubes.WaitForSession none',
  961. user="root", passio_popen=True, gui=False, wait=True)
  962. p.communicate(input=self.default_user.encode())
  963. def create_on_disk(self, pool=None, pools=None):
  964. '''Create files needed for VM.
  965. '''
  966. self.log.info('Creating directory: {0}'.format(self.dir_path))
  967. os.makedirs(self.dir_path, mode=0o775)
  968. if pool or pools:
  969. # pylint: disable=attribute-defined-outside-init
  970. self.volume_config = _patch_volume_config(self.volume_config, pool,
  971. pools)
  972. self.storage = qubes.storage.Storage(self)
  973. self.storage.create()
  974. self.log.info('Creating icon symlink: {} -> {}'.format(
  975. self.icon_path, self.label.icon_path))
  976. if hasattr(os, "symlink"):
  977. os.symlink(self.label.icon_path, self.icon_path)
  978. else:
  979. shutil.copy(self.label.icon_path, self.icon_path)
  980. # fire hooks
  981. self.fire_event('domain-create-on-disk')
  982. def remove_from_disk(self):
  983. '''Remove domain remnants from disk.'''
  984. if not self.is_halted():
  985. raise qubes.exc.QubesVMNotHaltedError(
  986. "Can't remove VM {!s}, beacuse it's in state {!r}.".format(
  987. self, self.get_power_state()))
  988. self.fire_event('domain-remove-from-disk')
  989. try:
  990. shutil.rmtree(self.dir_path)
  991. except OSError as e:
  992. if e.errno == errno.ENOENT:
  993. pass
  994. else:
  995. raise
  996. self.storage.remove()
  997. def clone_disk_files(self, src, pool=None, pools=None, ):
  998. '''Clone files from other vm.
  999. :param qubes.vm.qubesvm.QubesVM src: source VM
  1000. '''
  1001. # If the current vm name is not a part of `self.app.domains.keys()`,
  1002. # then the current vm is in creation process. Calling
  1003. # `self.is_halted()` at this point, would instantiate libvirt, we want
  1004. # avoid that.
  1005. if self.name in self.app.domains.keys() and not self.is_halted():
  1006. raise qubes.exc.QubesVMNotHaltedError(
  1007. self, 'Cannot clone a running domain {!r}'.format(self.name))
  1008. if pool or pools:
  1009. # pylint: disable=attribute-defined-outside-init
  1010. self.volume_config = _patch_volume_config(self.volume_config, pool,
  1011. pools)
  1012. self.storage = qubes.storage.Storage(self)
  1013. self.storage.clone(src)
  1014. self.storage.verify()
  1015. assert self.volumes != {}
  1016. if src.icon_path is not None \
  1017. and os.path.exists(src.dir_path) \
  1018. and self.icon_path is not None:
  1019. if os.path.islink(src.icon_path):
  1020. icon_path = os.readlink(src.icon_path)
  1021. self.log.info(
  1022. 'Creating icon symlink {} -> {}'.format(
  1023. self.icon_path, icon_path))
  1024. os.symlink(icon_path, self.icon_path)
  1025. else:
  1026. self.log.info(
  1027. 'Copying icon {} -> {}'.format(
  1028. src.icon_path, self.icon_path))
  1029. shutil.copy(src.icon_path, self.icon_path)
  1030. # fire hooks
  1031. self.fire_event('domain-clone-files', src=src)
  1032. #
  1033. # methods for querying domain state
  1034. #
  1035. # state of the machine
  1036. def get_power_state(self):
  1037. '''Return power state description string.
  1038. Return value may be one of those:
  1039. =============== ========================================================
  1040. return value meaning
  1041. =============== ========================================================
  1042. ``'Halted'`` Machine is not active.
  1043. ``'Transient'`` Machine is running, but does not have :program:`guid`
  1044. or :program:`qrexec` available.
  1045. ``'Running'`` Machine is ready and running.
  1046. ``'Paused'`` Machine is paused (currently not available, see below).
  1047. ``'Suspended'`` Machine is S3-suspended.
  1048. ``'Halting'`` Machine is in process of shutting down.
  1049. ``'Dying'`` Machine crashed and is unusable.
  1050. ``'Crashed'`` Machine crashed and is unusable, probably because of
  1051. bug in dom0.
  1052. ``'NA'`` Machine is in unknown state (most likely libvirt domain
  1053. is undefined).
  1054. =============== ========================================================
  1055. ``Paused`` state is currently unavailable because of missing code in
  1056. libvirt/xen glue.
  1057. FIXME: graph below may be incomplete and wrong. Click on method name to
  1058. see its documentation.
  1059. .. graphviz::
  1060. digraph {
  1061. node [fontname="sans-serif"];
  1062. edge [fontname="mono"];
  1063. Halted;
  1064. NA;
  1065. Dying;
  1066. Crashed;
  1067. Transient;
  1068. Halting;
  1069. Running;
  1070. Paused [color=gray75 fontcolor=gray75];
  1071. Suspended;
  1072. NA -> Halted;
  1073. Halted -> NA [constraint=false];
  1074. Halted -> Transient
  1075. [xlabel="start()" URL="#qubes.vm.qubesvm.QubesVM.start"];
  1076. Transient -> Running;
  1077. Running -> Halting
  1078. [xlabel="shutdown()"
  1079. URL="#qubes.vm.qubesvm.QubesVM.shutdown"
  1080. constraint=false];
  1081. Halting -> Dying -> Halted [constraint=false];
  1082. /* cosmetic, invisible edges to put rank constraint */
  1083. Dying -> Halting [style="invis"];
  1084. Halting -> Transient [style="invis"];
  1085. Running -> Halted
  1086. [label="force_shutdown()"
  1087. URL="#qubes.vm.qubesvm.QubesVM.force_shutdown"
  1088. constraint=false];
  1089. Running -> Crashed [constraint=false];
  1090. Crashed -> Halted [constraint=false];
  1091. Running -> Paused
  1092. [label="pause()" URL="#qubes.vm.qubesvm.QubesVM.pause"
  1093. color=gray75 fontcolor=gray75];
  1094. Running -> Suspended
  1095. [label="pause()" URL="#qubes.vm.qubesvm.QubesVM.pause"
  1096. color=gray50 fontcolor=gray50];
  1097. Paused -> Running
  1098. [label="unpause()" URL="#qubes.vm.qubesvm.QubesVM.unpause"
  1099. color=gray75 fontcolor=gray75];
  1100. Suspended -> Running
  1101. [label="unpause()" URL="#qubes.vm.qubesvm.QubesVM.unpause"
  1102. color=gray50 fontcolor=gray50];
  1103. Running -> Suspended
  1104. [label="suspend()" URL="#qubes.vm.qubesvm.QubesVM.suspend"];
  1105. Suspended -> Running
  1106. [label="resume()" URL="#qubes.vm.qubesvm.QubesVM.resume"];
  1107. { rank=source; Halted NA };
  1108. { rank=same; Transient Halting };
  1109. { rank=same; Crashed Dying };
  1110. { rank=sink; Paused Suspended };
  1111. }
  1112. .. seealso::
  1113. http://wiki.libvirt.org/page/VM_lifecycle
  1114. Description of VM life cycle from the point of view of libvirt.
  1115. https://libvirt.org/html/libvirt-libvirt-domain.html#virDomainState
  1116. Libvirt's enum describing precise state of a domain.
  1117. ''' # pylint: disable=too-many-return-statements
  1118. libvirt_domain = self.libvirt_domain
  1119. if libvirt_domain is None:
  1120. return 'Halted'
  1121. try:
  1122. if libvirt_domain.isActive():
  1123. # pylint: disable=line-too-long
  1124. if libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PAUSED:
  1125. return "Paused"
  1126. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_CRASHED:
  1127. return "Crashed"
  1128. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_SHUTDOWN:
  1129. return "Halting"
  1130. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_SHUTOFF:
  1131. return "Dying"
  1132. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PMSUSPENDED: # nopep8
  1133. return "Suspended"
  1134. else:
  1135. if not self.is_fully_usable():
  1136. return "Transient"
  1137. else:
  1138. return "Running"
  1139. else:
  1140. return 'Halted'
  1141. except libvirt.libvirtError as e:
  1142. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  1143. return 'Halted'
  1144. else:
  1145. raise
  1146. assert False
  1147. def is_halted(self):
  1148. ''' Check whether this domain's state is 'Halted'
  1149. :returns: :py:obj:`True` if this domain is halted, \
  1150. :py:obj:`False` otherwise.
  1151. :rtype: bool
  1152. '''
  1153. return self.get_power_state() == 'Halted'
  1154. def is_running(self):
  1155. '''Check whether this domain is running.
  1156. :returns: :py:obj:`True` if this domain is started, \
  1157. :py:obj:`False` otherwise.
  1158. :rtype: bool
  1159. '''
  1160. if self.app.vmm.offline_mode:
  1161. return False
  1162. # TODO context manager #1693
  1163. return self.libvirt_domain and self.libvirt_domain.isActive()
  1164. def is_paused(self):
  1165. '''Check whether this domain is paused.
  1166. :returns: :py:obj:`True` if this domain is paused, \
  1167. :py:obj:`False` otherwise.
  1168. :rtype: bool
  1169. '''
  1170. return self.libvirt_domain \
  1171. and self.libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PAUSED
  1172. def is_qrexec_running(self):
  1173. '''Check whether qrexec for this domain is available.
  1174. :returns: :py:obj:`True` if qrexec is running, \
  1175. :py:obj:`False` otherwise.
  1176. :rtype: bool
  1177. '''
  1178. if self.xid < 0:
  1179. return False
  1180. return os.path.exists('/var/run/qubes/qrexec.%s' % self.name)
  1181. def is_fully_usable(self):
  1182. return all(self.fire_event('domain-is-fully-usable'))
  1183. @qubes.events.handler('domain-is-fully-usable')
  1184. def on_domain_is_fully_usable(self, event):
  1185. '''Check whether domain is running and sane.
  1186. Currently this checks for running qrexec.
  1187. ''' # pylint: disable=unused-argument
  1188. # Running gui-daemon implies also VM running
  1189. if not self.is_qrexec_running():
  1190. yield False
  1191. # memory and disk
  1192. def get_mem(self):
  1193. '''Get current memory usage from VM.
  1194. :returns: Memory usage [FIXME unit].
  1195. :rtype: FIXME
  1196. '''
  1197. if self.libvirt_domain is None:
  1198. return 0
  1199. try:
  1200. if not self.libvirt_domain.isActive():
  1201. return 0
  1202. return self.libvirt_domain.info()[1]
  1203. except libvirt.libvirtError as e:
  1204. if e.get_error_code() in (
  1205. # qube no longer exists
  1206. libvirt.VIR_ERR_NO_DOMAIN,
  1207. # libxl_domain_info failed (race condition from isActive)
  1208. libvirt.VIR_ERR_INTERNAL_ERROR):
  1209. return 0
  1210. else:
  1211. self.log.exception(
  1212. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1213. raise
  1214. def get_mem_static_max(self):
  1215. '''Get maximum memory available to VM.
  1216. :returns: Memory limit [FIXME unit].
  1217. :rtype: FIXME
  1218. '''
  1219. if self.libvirt_domain is None:
  1220. return 0
  1221. try:
  1222. return self.libvirt_domain.maxMemory()
  1223. except libvirt.libvirtError as e:
  1224. if e.get_error_code() in (
  1225. # qube no longer exists
  1226. libvirt.VIR_ERR_NO_DOMAIN,
  1227. # libxl_domain_info failed (race condition from isActive)
  1228. libvirt.VIR_ERR_INTERNAL_ERROR):
  1229. return 0
  1230. else:
  1231. self.log.exception(
  1232. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1233. raise
  1234. def get_cputime(self):
  1235. '''Get total CPU time burned by this domain since start.
  1236. :returns: CPU time usage [FIXME unit].
  1237. :rtype: FIXME
  1238. '''
  1239. if self.libvirt_domain is None:
  1240. return 0
  1241. if self.libvirt_domain is None:
  1242. return 0
  1243. if not self.libvirt_domain.isActive():
  1244. return 0
  1245. try:
  1246. if not self.libvirt_domain.isActive():
  1247. return 0
  1248. # this does not work, because libvirt
  1249. # return self.libvirt_domain.getCPUStats(
  1250. # libvirt.VIR_NODE_CPU_STATS_ALL_CPUS, 0)[0]['cpu_time']/10**9
  1251. return self.libvirt_domain.info()[4]
  1252. except libvirt.libvirtError as e:
  1253. if e.get_error_code() in (
  1254. # qube no longer exists
  1255. libvirt.VIR_ERR_NO_DOMAIN,
  1256. # libxl_domain_info failed (race condition from isActive)
  1257. libvirt.VIR_ERR_INTERNAL_ERROR):
  1258. return 0
  1259. else:
  1260. self.log.exception(
  1261. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1262. raise
  1263. # miscellanous
  1264. def get_start_time(self):
  1265. '''Tell when machine was started.
  1266. :rtype: datetime.datetime
  1267. '''
  1268. if not self.is_running():
  1269. return None
  1270. # TODO shouldn't this be qubesdb?
  1271. start_time = self.app.vmm.xs.read('',
  1272. '/vm/{}/start_time'.format(self.uuid))
  1273. if start_time != '':
  1274. return datetime.datetime.fromtimestamp(float(start_time))
  1275. else:
  1276. return None
  1277. def is_outdated(self):
  1278. '''Check whether domain needs restart to update root image from \
  1279. template.
  1280. :returns: :py:obj:`True` if is outdated, :py:obj:`False` otherwise.
  1281. :rtype: bool
  1282. '''
  1283. # pylint: disable=no-member
  1284. # Makes sense only on VM based on template
  1285. if self.template is None:
  1286. return False
  1287. if not self.is_running():
  1288. return False
  1289. if not hasattr(self.template, 'rootcow_img'):
  1290. return False
  1291. rootimg_inode = os.stat(self.template.root_img)
  1292. try:
  1293. rootcow_inode = os.stat(self.template.rootcow_img)
  1294. except OSError:
  1295. # The only case when rootcow_img doesn't exists is in the middle of
  1296. # commit_changes, so VM is outdated right now
  1297. return True
  1298. current_dmdev = "/dev/mapper/snapshot-{0:x}:{1}-{2:x}:{3}".format(
  1299. rootimg_inode[2], rootimg_inode[1],
  1300. rootcow_inode[2], rootcow_inode[1])
  1301. # FIXME
  1302. # 51712 (0xCA00) is xvda
  1303. # backend node name not available through xenapi :(
  1304. used_dmdev = self.app.vmm.xs.read('',
  1305. '/local/domain/0/backend/vbd/{}/51712/node'.format(self.xid))
  1306. return used_dmdev != current_dmdev
  1307. #
  1308. # helper methods
  1309. #
  1310. def relative_path(self, path):
  1311. '''Return path relative to py:attr:`dir_path`.
  1312. :param str path: Path in question.
  1313. :returns: Relative path.
  1314. '''
  1315. return os.path.relpath(path, self.dir_path)
  1316. def create_qdb_entries(self):
  1317. '''Create entries in Qubes DB.
  1318. '''
  1319. # pylint: disable=no-member
  1320. self.qdb.write('/name', self.name)
  1321. self.qdb.write('/type', self.__class__.__name__)
  1322. self.qdb.write('/qubes-vm-updateable', str(self.updateable))
  1323. self.qdb.write('/qubes-vm-persistence',
  1324. 'full' if self.updateable else 'rw-only')
  1325. self.qdb.write('/qubes-debug-mode', str(int(self.debug)))
  1326. try:
  1327. self.qdb.write('/qubes-base-template', self.template.name)
  1328. except AttributeError:
  1329. self.qdb.write('/qubes-base-template', '')
  1330. self.qdb.write('/qubes-random-seed',
  1331. base64.b64encode(qubes.utils.urandom(64)))
  1332. if self.provides_network:
  1333. # '/qubes-netvm-network' value is only checked for being non empty
  1334. self.qdb.write('/qubes-netvm-network', self.gateway)
  1335. self.qdb.write('/qubes-netvm-gateway', self.gateway)
  1336. self.qdb.write('/qubes-netvm-netmask', self.netmask)
  1337. for i, addr in zip(('primary', 'secondary'), self.dns):
  1338. self.qdb.write('/qubes-netvm-{}-dns'.format(i), addr)
  1339. if self.netvm is not None:
  1340. self.qdb.write('/qubes-ip', self.visible_ip)
  1341. self.qdb.write('/qubes-netmask', self.visible_netmask)
  1342. self.qdb.write('/qubes-gateway', self.visible_gateway)
  1343. for i, addr in zip(('primary', 'secondary'), self.dns):
  1344. self.qdb.write('/qubes-{}-dns'.format(i), addr)
  1345. tzname = qubes.utils.get_timezone()
  1346. if tzname:
  1347. self.qdb.write('/qubes-timezone', tzname)
  1348. for feature, value in self.features.items():
  1349. self.qdb.write('/features/{0}'.format(feature),
  1350. str(value) if value else '')
  1351. self.qdb.write('/qubes-block-devices', '')
  1352. self.qdb.write('/qubes-usb-devices', '')
  1353. # TODO: Currently the whole qmemman is quite Xen-specific, so stay with
  1354. # xenstore for it until decided otherwise
  1355. if qmemman_present:
  1356. self.app.vmm.xs.set_permissions('',
  1357. '/local/domain/{}/memory'.format(self.xid),
  1358. [{'dom': self.xid}])
  1359. self.fire_event('domain-qdb-create')
  1360. def _update_libvirt_domain(self):
  1361. '''Re-initialise :py:attr:`libvirt_domain`.'''
  1362. domain_config = self.create_config_file()
  1363. try:
  1364. self._libvirt_domain = self.app.vmm.libvirt_conn.defineXML(
  1365. domain_config)
  1366. except libvirt.libvirtError as e:
  1367. if e.get_error_code() == libvirt.VIR_ERR_OS_TYPE \
  1368. and e.get_str2() == 'hvm':
  1369. raise qubes.exc.QubesVMError(self,
  1370. 'HVM qubes are not supported on this machine. '
  1371. 'Check BIOS settings for VT-x/AMD-V extensions.')
  1372. else:
  1373. raise
  1374. #
  1375. # workshop -- those are to be reworked later
  1376. #
  1377. def get_prefmem(self):
  1378. # TODO: qmemman is still xen specific
  1379. untrusted_meminfo_key = self.app.vmm.xs.read('',
  1380. '/local/domain/{}/memory/meminfo'.format(self.xid))
  1381. if untrusted_meminfo_key is None or untrusted_meminfo_key == '':
  1382. return 0
  1383. domain = qubes.qmemman.DomainState(self.xid)
  1384. qubes.qmemman.algo.refresh_meminfo_for_domain(
  1385. domain, untrusted_meminfo_key)
  1386. if domain.mem_used is None:
  1387. # apparently invalid xenstore content
  1388. return 0
  1389. domain.memory_maximum = self.get_mem_static_max() * 1024
  1390. return qubes.qmemman.algo.prefmem(domain) / 1024
  1391. def _clean_volume_config(config):
  1392. common_attributes = ['name', 'pool', 'size', 'internal', 'removable',
  1393. 'revisions_to_keep', 'rw', 'snap_on_start',
  1394. 'save_on_stop', 'source']
  1395. config_copy = copy.deepcopy(config)
  1396. return {k: v for k, v in config_copy.items() if k in common_attributes}
  1397. def _patch_pool_config(config, pool=None, pools=None):
  1398. assert pool is not None or pools is not None
  1399. is_saveable = 'save_on_stop' in config and config['save_on_stop']
  1400. is_resetable = not ('snap_on_start' in config and # volatile
  1401. config['snap_on_start'] and not is_saveable)
  1402. is_exportable = is_saveable or is_resetable
  1403. name = config['name']
  1404. if pool and is_exportable and config['pool'] == 'default':
  1405. config['pool'] = str(pool)
  1406. elif pool and not is_exportable:
  1407. pass
  1408. elif pools and name in pools.keys():
  1409. if is_exportable:
  1410. config['pool'] = str(pools[name])
  1411. else:
  1412. msg = "Can't clone a snapshot volume {!s} to pool {!s} " \
  1413. .format(name, pools[name])
  1414. raise qubes.exc.QubesException(msg)
  1415. return config
  1416. def _patch_volume_config(volume_config, pool=None, pools=None):
  1417. assert not (pool and pools), \
  1418. 'You can not pass pool & pools parameter at same time'
  1419. assert pool or pools
  1420. result = {}
  1421. for name, config in volume_config.items():
  1422. # copy only the subset of volume_config key/values
  1423. dst_config = _clean_volume_config(config)
  1424. if pool is not None or pools is not None:
  1425. dst_config = _patch_pool_config(dst_config, pool, pools)
  1426. result[name] = dst_config
  1427. return result