__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. vm_list_info = [line
  134. for line in self.qubesd_call(
  135. self._method_dest, 'admin.vm.List', None, None
  136. ).decode('ascii').split('\n')
  137. if line.startswith(self._method_dest+' ')]
  138. assert len(vm_list_info) == 1
  139. # name class=... state=... other=...
  140. # NOTE: when querying dom0, we get whole list
  141. vm_state = vm_list_info[0].strip().partition('state=')[2].split(' ')[0]
  142. return vm_state
  143. def is_halted(self):
  144. ''' Check whether this domain's state is 'Halted'
  145. :returns: :py:obj:`True` if this domain is halted, \
  146. :py:obj:`False` otherwise.
  147. :rtype: bool
  148. '''
  149. return self.get_power_state() == 'Halted'
  150. def is_paused(self):
  151. '''Check whether this domain is paused.
  152. :returns: :py:obj:`True` if this domain is paused, \
  153. :py:obj:`False` otherwise.
  154. :rtype: bool
  155. '''
  156. return self.get_power_state() == 'Paused'
  157. def is_running(self):
  158. '''Check whether this domain is running.
  159. :returns: :py:obj:`True` if this domain is started, \
  160. :py:obj:`False` otherwise.
  161. :rtype: bool
  162. '''
  163. return self.get_power_state() != 'Halted'
  164. def is_networked(self):
  165. '''Check whether this VM can reach network (firewall notwithstanding).
  166. :returns: :py:obj:`True` if is machine can reach network, \
  167. :py:obj:`False` otherwise.
  168. :rtype: bool
  169. '''
  170. if self.provides_network:
  171. return True
  172. return self.netvm is not None
  173. @property
  174. def volumes(self):
  175. '''VM disk volumes'''
  176. if self._volumes is None:
  177. volumes_list = self.qubesd_call(
  178. self._method_dest, 'admin.vm.volume.List')
  179. self._volumes = {}
  180. for volname in volumes_list.decode('ascii').splitlines():
  181. if not volname:
  182. continue
  183. self._volumes[volname] = qubesadmin.storage.Volume(self.app,
  184. vm=self.name, vm_name=volname)
  185. return self._volumes
  186. def get_disk_utilization(self):
  187. '''Get total disk usage of the VM'''
  188. return sum(vol.usage for vol in self.volumes.values())
  189. def run_service(self, service, **kwargs):
  190. '''Run service on this VM
  191. :param str service: service name
  192. :rtype: subprocess.Popen
  193. '''
  194. return self.app.run_service(self._method_dest, service, **kwargs)
  195. def run_service_for_stdio(self, service, input=None, **kwargs):
  196. '''Run a service, pass an optional input and return (stdout, stderr).
  197. Raises an exception if return code != 0.
  198. *args* and *kwargs* are passed verbatim to :py:meth:`run_service`.
  199. .. warning::
  200. There are some combinations if stdio-related *kwargs*, which are
  201. not filtered for problems originating between the keyboard and the
  202. chair.
  203. ''' # pylint: disable=redefined-builtin
  204. p = self.run_service(service, **kwargs)
  205. # this one is actually a tuple, but there is no need to unpack it
  206. stdouterr = p.communicate(input=input)
  207. if p.returncode:
  208. exc = subprocess.CalledProcessError(p.returncode, service)
  209. # Python < 3.5 didn't have those
  210. exc.output, exc.stderr = stdouterr
  211. raise exc
  212. return stdouterr
  213. @staticmethod
  214. def prepare_input_for_vmshell(command, input=None):
  215. '''Prepare shell input for the given command and optional (real) input
  216. ''' # pylint: disable=redefined-builtin
  217. if input is None:
  218. input = b''
  219. return b''.join((command.rstrip('\n').encode('utf-8'),
  220. b'; exit\n', input))
  221. def run(self, command, input=None, **kwargs):
  222. '''Run a shell command inside the domain using qubes.VMShell qrexec.
  223. ''' # pylint: disable=redefined-builtin
  224. try:
  225. return self.run_service_for_stdio('qubes.VMShell',
  226. input=self.prepare_input_for_vmshell(command, input), **kwargs)
  227. except subprocess.CalledProcessError as e:
  228. e.cmd = command
  229. raise e
  230. @property
  231. def appvms(self):
  232. ''' Returns a generator containing all domains based on the current
  233. TemplateVM.
  234. Do not check vm type of self, core (including its extentions) have
  235. ultimate control what can be a template of what.
  236. '''
  237. for vm in self.app.domains:
  238. try:
  239. if vm.template == self:
  240. yield vm
  241. except AttributeError:
  242. pass
  243. @property
  244. def klass(self):
  245. ''' Qube class '''
  246. # use cached value if available
  247. if self._klass is None:
  248. # pylint: disable=no-member
  249. self._klass = super(QubesVM, self).klass
  250. return self._klass
  251. class DispVMWrapper(QubesVM):
  252. '''Wrapper class for new DispVM, supporting only service call
  253. Note that when running in dom0, one need to manually kill the DispVM after
  254. service call ends.
  255. '''
  256. def run_service(self, service, **kwargs):
  257. if self.app.qubesd_connection_type == 'socket':
  258. # create dispvm at service call
  259. if self._method_dest.startswith('$dispvm'):
  260. if self._method_dest.startswith('$dispvm:'):
  261. method_dest = self._method_dest[len('$dispvm:'):]
  262. else:
  263. method_dest = 'dom0'
  264. dispvm = self.app.qubesd_call(method_dest,
  265. 'admin.vm.CreateDisposable')
  266. dispvm = dispvm.decode('ascii')
  267. self._method_dest = dispvm
  268. return super(DispVMWrapper, self).run_service(service, **kwargs)
  269. def cleanup(self):
  270. '''Cleanup after DispVM usage'''
  271. # in 'remote' case nothing is needed, as DispVM is cleaned up
  272. # automatically
  273. if self.app.qubesd_connection_type == 'socket' and \
  274. not self._method_dest.startswith('$dispvm'):
  275. try:
  276. self.kill()
  277. except qubesadmin.exc.QubesVMNotRunningError:
  278. pass
  279. class DispVM(QubesVM):
  280. '''Disposable VM'''
  281. @classmethod
  282. def from_appvm(cls, app, appvm):
  283. '''Returns a wrapper for calling service in a new DispVM based on given
  284. AppVM. If *appvm* is none, use default DispVM template'''
  285. if appvm:
  286. method_dest = '$dispvm:' + str(appvm)
  287. else:
  288. method_dest = '$dispvm'
  289. wrapper = DispVMWrapper(app, method_dest)
  290. return wrapper