qubesvm.py 57 KB

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