qubesvm.py 55 KB

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