__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. # -*- encoding: utf8 -*-
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2017 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU Lesser General Public License as published by
  10. # the Free Software Foundation; either version 2.1 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public License along
  19. # with this program; if not, see <http://www.gnu.org/licenses/>.
  20. '''Qubes VM objects.'''
  21. import logging
  22. import subprocess
  23. import qubesadmin.base
  24. import qubesadmin.exc
  25. import qubesadmin.storage
  26. import qubesadmin.features
  27. import qubesadmin.devices
  28. import qubesadmin.firewall
  29. import qubesadmin.tags
  30. class QubesVM(qubesadmin.base.PropertyHolder):
  31. '''Qubes domain.'''
  32. log = None
  33. tags = None
  34. features = None
  35. devices = None
  36. firewall = None
  37. def __init__(self, app, name, klass=None):
  38. super(QubesVM, self).__init__(app, 'admin.vm.property.', name)
  39. self._volumes = None
  40. self._klass = klass
  41. self.log = logging.getLogger(name)
  42. self.tags = qubesadmin.tags.Tags(self)
  43. self.features = qubesadmin.features.Features(self)
  44. self.devices = qubesadmin.devices.DeviceManager(self)
  45. self.firewall = qubesadmin.firewall.Firewall(self)
  46. @property
  47. def name(self):
  48. '''Domain name'''
  49. return self._method_dest
  50. @name.setter
  51. def name(self, new_value):
  52. self.qubesd_call(
  53. self._method_dest,
  54. self._method_prefix + 'Set',
  55. 'name',
  56. str(new_value).encode('utf-8'))
  57. self._method_dest = new_value
  58. self._volumes = None
  59. self.app.domains.clear_cache()
  60. def __str__(self):
  61. return self._method_dest
  62. def __lt__(self, other):
  63. if isinstance(other, QubesVM):
  64. return self.name < other.name
  65. return NotImplemented
  66. def __eq__(self, other):
  67. if isinstance(other, QubesVM):
  68. return self.name == other.name
  69. elif isinstance(other, str):
  70. return self.name == other
  71. return NotImplemented
  72. def __hash__(self):
  73. return hash(self.name)
  74. def start(self):
  75. '''
  76. Start domain.
  77. :return:
  78. '''
  79. self.qubesd_call(self._method_dest, 'admin.vm.Start')
  80. def shutdown(self, force=False):
  81. '''
  82. Shutdown domain.
  83. :return:
  84. '''
  85. # TODO: force parameter
  86. # TODO: wait parameter (using event?)
  87. if force:
  88. raise NotImplementedError
  89. self.qubesd_call(self._method_dest, 'admin.vm.Shutdown')
  90. def kill(self):
  91. '''
  92. Kill domain (forcefuly shutdown).
  93. :return:
  94. '''
  95. self.qubesd_call(self._method_dest, 'admin.vm.Kill')
  96. def pause(self):
  97. '''
  98. Pause domain.
  99. Pause its execution without any prior notification.
  100. :return:
  101. '''
  102. self.qubesd_call(self._method_dest, 'admin.vm.Pause')
  103. def unpause(self):
  104. '''
  105. Unpause domain.
  106. Opposite to :py:meth:`pause`.
  107. :return:
  108. '''
  109. self.qubesd_call(self._method_dest, 'admin.vm.Unpause')
  110. def get_power_state(self):
  111. '''Return power state description string.
  112. Return value may be one of those:
  113. =============== ========================================================
  114. return value meaning
  115. =============== ========================================================
  116. ``'Halted'`` Machine is not active.
  117. ``'Transient'`` Machine is running, but does not have :program:`guid`
  118. or :program:`qrexec` available.
  119. ``'Running'`` Machine is ready and running.
  120. ``'Paused'`` Machine is paused.
  121. ``'Suspended'`` Machine is S3-suspended.
  122. ``'Halting'`` Machine is in process of shutting down (OS shutdown).
  123. ``'Dying'`` Machine is in process of shutting down (cleanup).
  124. ``'Crashed'`` Machine crashed and is unusable.
  125. ``'NA'`` Machine is in unknown state.
  126. =============== ========================================================
  127. .. seealso::
  128. http://wiki.libvirt.org/page/VM_lifecycle
  129. Description of VM life cycle from the point of view of libvirt.
  130. https://libvirt.org/html/libvirt-libvirt-domain.html#virDomainState
  131. Libvirt's enum describing precise state of a domain.
  132. '''
  133. try:
  134. vm_list_info = [line
  135. for line in self.qubesd_call(
  136. self._method_dest, 'admin.vm.List', None, None
  137. ).decode('ascii').split('\n')
  138. if line.startswith(self._method_dest+' ')]
  139. except qubesadmin.exc.QubesDaemonNoResponseError:
  140. return 'NA'
  141. assert len(vm_list_info) == 1
  142. # name class=... state=... other=...
  143. # NOTE: when querying dom0, we get whole list
  144. vm_state = vm_list_info[0].strip().partition('state=')[2].split(' ')[0]
  145. return vm_state
  146. def is_halted(self):
  147. ''' Check whether this domain's state is 'Halted'
  148. :returns: :py:obj:`True` if this domain is halted, \
  149. :py:obj:`False` otherwise.
  150. :rtype: bool
  151. '''
  152. return self.get_power_state() == 'Halted'
  153. def is_paused(self):
  154. '''Check whether this domain is paused.
  155. :returns: :py:obj:`True` if this domain is paused, \
  156. :py:obj:`False` otherwise.
  157. :rtype: bool
  158. '''
  159. return self.get_power_state() == 'Paused'
  160. def is_running(self):
  161. '''Check whether this domain is running.
  162. :returns: :py:obj:`True` if this domain is started, \
  163. :py:obj:`False` otherwise.
  164. :rtype: bool
  165. '''
  166. return self.get_power_state() not in ('Halted', 'NA')
  167. def is_networked(self):
  168. '''Check whether this VM can reach network (firewall notwithstanding).
  169. :returns: :py:obj:`True` if is machine can reach network, \
  170. :py:obj:`False` otherwise.
  171. :rtype: bool
  172. '''
  173. if self.provides_network:
  174. return True
  175. return self.netvm is not None
  176. @property
  177. def volumes(self):
  178. '''VM disk volumes'''
  179. if self._volumes is None:
  180. volumes_list = self.qubesd_call(
  181. self._method_dest, 'admin.vm.volume.List')
  182. self._volumes = {}
  183. for volname in volumes_list.decode('ascii').splitlines():
  184. if not volname:
  185. continue
  186. self._volumes[volname] = qubesadmin.storage.Volume(self.app,
  187. vm=self.name, vm_name=volname)
  188. return self._volumes
  189. def get_disk_utilization(self):
  190. '''Get total disk usage of the VM'''
  191. return sum(vol.usage for vol in self.volumes.values())
  192. def run_service(self, service, **kwargs):
  193. '''Run service on this VM
  194. :param str service: service name
  195. :rtype: subprocess.Popen
  196. '''
  197. return self.app.run_service(self._method_dest, service, **kwargs)
  198. def run_service_for_stdio(self, service, input=None, **kwargs):
  199. '''Run a service, pass an optional input and return (stdout, stderr).
  200. Raises an exception if return code != 0.
  201. *args* and *kwargs* are passed verbatim to :py:meth:`run_service`.
  202. .. warning::
  203. There are some combinations if stdio-related *kwargs*, which are
  204. not filtered for problems originating between the keyboard and the
  205. chair.
  206. ''' # pylint: disable=redefined-builtin
  207. p = self.run_service(service, **kwargs)
  208. # this one is actually a tuple, but there is no need to unpack it
  209. stdouterr = p.communicate(input=input)
  210. if p.returncode:
  211. exc = subprocess.CalledProcessError(p.returncode, service)
  212. # Python < 3.5 didn't have those
  213. exc.output, exc.stderr = stdouterr
  214. raise exc
  215. return stdouterr
  216. @staticmethod
  217. def prepare_input_for_vmshell(command, input=None):
  218. '''Prepare shell input for the given command and optional (real) input
  219. ''' # pylint: disable=redefined-builtin
  220. if input is None:
  221. input = b''
  222. return b''.join((command.rstrip('\n').encode('utf-8'),
  223. b'; exit\n', input))
  224. def run(self, command, input=None, **kwargs):
  225. '''Run a shell command inside the domain using qubes.VMShell qrexec.
  226. ''' # pylint: disable=redefined-builtin
  227. try:
  228. return self.run_service_for_stdio('qubes.VMShell',
  229. input=self.prepare_input_for_vmshell(command, input), **kwargs)
  230. except subprocess.CalledProcessError as e:
  231. e.cmd = command
  232. raise e
  233. @property
  234. def appvms(self):
  235. ''' Returns a generator containing all domains based on the current
  236. TemplateVM.
  237. Do not check vm type of self, core (including its extentions) have
  238. ultimate control what can be a template of what.
  239. '''
  240. for vm in self.app.domains:
  241. try:
  242. if vm.template == self:
  243. yield vm
  244. except AttributeError:
  245. pass
  246. @property
  247. def klass(self):
  248. ''' Qube class '''
  249. # use cached value if available
  250. if self._klass is None:
  251. # pylint: disable=no-member
  252. self._klass = super(QubesVM, self).klass
  253. return self._klass
  254. class DispVMWrapper(QubesVM):
  255. '''Wrapper class for new DispVM, supporting only service call
  256. Note that when running in dom0, one need to manually kill the DispVM after
  257. service call ends.
  258. '''
  259. def run_service(self, service, **kwargs):
  260. if self.app.qubesd_connection_type == 'socket':
  261. # create dispvm at service call
  262. if self._method_dest.startswith('$dispvm'):
  263. if self._method_dest.startswith('$dispvm:'):
  264. method_dest = self._method_dest[len('$dispvm:'):]
  265. else:
  266. method_dest = 'dom0'
  267. dispvm = self.app.qubesd_call(method_dest,
  268. 'admin.vm.CreateDisposable')
  269. dispvm = dispvm.decode('ascii')
  270. self._method_dest = dispvm
  271. return super(DispVMWrapper, self).run_service(service, **kwargs)
  272. def cleanup(self):
  273. '''Cleanup after DispVM usage'''
  274. # in 'remote' case nothing is needed, as DispVM is cleaned up
  275. # automatically
  276. if self.app.qubesd_connection_type == 'socket' and \
  277. not self._method_dest.startswith('$dispvm'):
  278. try:
  279. self.kill()
  280. except qubesadmin.exc.QubesVMNotRunningError:
  281. pass
  282. class DispVM(QubesVM):
  283. '''Disposable VM'''
  284. @classmethod
  285. def from_appvm(cls, app, appvm):
  286. '''Returns a wrapper for calling service in a new DispVM based on given
  287. AppVM. If *appvm* is none, use default DispVM template'''
  288. if appvm:
  289. method_dest = '$dispvm:' + str(appvm)
  290. else:
  291. method_dest = '$dispvm'
  292. wrapper = DispVMWrapper(app, method_dest)
  293. return wrapper