admin.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2017 Wojtek Porczyk <woju@invisiblethingslab.com>
  5. #
  6. # This library is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU Lesser General Public
  8. # License as published by the Free Software Foundation; either
  9. # version 2.1 of the License, or (at your option) any later version.
  10. #
  11. # This library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. # Lesser General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Lesser General Public
  17. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  18. #
  19. '''
  20. Qubes OS Management API
  21. '''
  22. import asyncio
  23. import functools
  24. import itertools
  25. import os
  26. import string
  27. import subprocess
  28. import libvirt
  29. import pkg_resources
  30. import yaml
  31. import qubes.api
  32. import qubes.backup
  33. import qubes.config
  34. import qubes.devices
  35. import qubes.firewall
  36. import qubes.storage
  37. import qubes.utils
  38. import qubes.vm
  39. import qubes.vm.adminvm
  40. import qubes.vm.qubesvm
  41. class QubesMgmtEventsDispatcher(object):
  42. def __init__(self, filters, send_event):
  43. self.filters = filters
  44. self.send_event = send_event
  45. def vm_handler(self, subject, event, **kwargs):
  46. # do not send internal events
  47. if event.startswith('admin-permission:'):
  48. return
  49. if event.startswith('device-get:'):
  50. return
  51. if event.startswith('device-list:'):
  52. return
  53. if event.startswith('device-list-attached:'):
  54. return
  55. if event in ('domain-is-fully-usable',):
  56. return
  57. if not list(qubes.api.apply_filters([(subject, event, kwargs)],
  58. self.filters)):
  59. return
  60. self.send_event(subject, event, **kwargs)
  61. def app_handler(self, subject, event, **kwargs):
  62. if not list(qubes.api.apply_filters([(subject, event, kwargs)],
  63. self.filters)):
  64. return
  65. self.send_event(subject, event, **kwargs)
  66. def on_domain_add(self, subject, event, vm):
  67. # pylint: disable=unused-argument
  68. vm.add_handler('*', self.vm_handler)
  69. def on_domain_delete(self, subject, event, vm):
  70. # pylint: disable=unused-argument
  71. vm.remove_handler('*', self.vm_handler)
  72. class QubesAdminAPI(qubes.api.AbstractQubesAPI):
  73. '''Implementation of Qubes Management API calls
  74. This class contains all the methods available in the main API.
  75. .. seealso::
  76. https://www.qubes-os.org/doc/mgmt1/
  77. '''
  78. SOCKNAME = '/var/run/qubesd.sock'
  79. @qubes.api.method('admin.vmclass.List', no_payload=True,
  80. scope='global', read=True)
  81. @asyncio.coroutine
  82. def vmclass_list(self):
  83. '''List all VM classes'''
  84. assert not self.arg
  85. assert self.dest.name == 'dom0'
  86. entrypoints = self.fire_event_for_filter(
  87. pkg_resources.iter_entry_points(qubes.vm.VM_ENTRY_POINT))
  88. return ''.join('{}\n'.format(ep.name)
  89. for ep in entrypoints)
  90. @qubes.api.method('admin.vm.List', no_payload=True,
  91. scope='global', read=True)
  92. @asyncio.coroutine
  93. def vm_list(self):
  94. '''List all the domains'''
  95. assert not self.arg
  96. if self.dest.name == 'dom0':
  97. domains = self.fire_event_for_filter(self.app.domains)
  98. else:
  99. domains = self.fire_event_for_filter([self.dest])
  100. return ''.join('{} class={} state={}\n'.format(
  101. vm.name,
  102. vm.__class__.__name__,
  103. vm.get_power_state())
  104. for vm in sorted(domains))
  105. @qubes.api.method('admin.vm.property.List', no_payload=True,
  106. scope='local', read=True)
  107. @asyncio.coroutine
  108. def vm_property_list(self):
  109. '''List all properties on a qube'''
  110. return self._property_list(self.dest)
  111. @qubes.api.method('admin.property.List', no_payload=True,
  112. scope='global', read=True)
  113. @asyncio.coroutine
  114. def property_list(self):
  115. '''List all global properties'''
  116. assert self.dest.name == 'dom0'
  117. return self._property_list(self.app)
  118. def _property_list(self, dest):
  119. assert not self.arg
  120. properties = self.fire_event_for_filter(dest.property_list())
  121. return ''.join('{}\n'.format(prop.__name__) for prop in properties)
  122. @qubes.api.method('admin.vm.property.Get', no_payload=True,
  123. scope='local', read=True)
  124. @asyncio.coroutine
  125. def vm_property_get(self):
  126. '''Get a value of one property'''
  127. return self._property_get(self.dest)
  128. @qubes.api.method('admin.property.Get', no_payload=True,
  129. scope='global', read=True)
  130. @asyncio.coroutine
  131. def property_get(self):
  132. '''Get a value of one global property'''
  133. assert self.dest.name == 'dom0'
  134. return self._property_get(self.app)
  135. def _property_get(self, dest):
  136. if self.arg not in dest.property_list():
  137. raise qubes.exc.QubesNoSuchPropertyError(dest, self.arg)
  138. self.fire_event_for_permission()
  139. property_def = dest.property_get_def(self.arg)
  140. # explicit list to be sure that it matches protocol spec
  141. if isinstance(property_def, qubes.vm.VMProperty):
  142. property_type = 'vm'
  143. elif property_def.type is int:
  144. property_type = 'int'
  145. elif property_def.type is bool:
  146. property_type = 'bool'
  147. elif self.arg == 'label':
  148. property_type = 'label'
  149. else:
  150. property_type = 'str'
  151. try:
  152. value = getattr(dest, self.arg)
  153. except AttributeError:
  154. return 'default=True type={} '.format(property_type)
  155. else:
  156. return 'default={} type={} {}'.format(
  157. str(dest.property_is_default(self.arg)),
  158. property_type,
  159. str(value) if value is not None else '')
  160. @qubes.api.method('admin.vm.property.Set',
  161. scope='local', write=True)
  162. @asyncio.coroutine
  163. def vm_property_set(self, untrusted_payload):
  164. '''Set property value'''
  165. return self._property_set(self.dest,
  166. untrusted_payload=untrusted_payload)
  167. @qubes.api.method('admin.property.Set',
  168. scope='global', write=True)
  169. @asyncio.coroutine
  170. def property_set(self, untrusted_payload):
  171. '''Set property value'''
  172. assert self.dest.name == 'dom0'
  173. return self._property_set(self.app,
  174. untrusted_payload=untrusted_payload)
  175. def _property_set(self, dest, untrusted_payload):
  176. if self.arg not in dest.property_list():
  177. raise qubes.exc.QubesNoSuchPropertyError(dest, self.arg)
  178. property_def = dest.property_get_def(self.arg)
  179. newvalue = property_def.sanitize(untrusted_newvalue=untrusted_payload)
  180. self.fire_event_for_permission(newvalue=newvalue)
  181. setattr(dest, self.arg, newvalue)
  182. self.app.save()
  183. @qubes.api.method('admin.vm.property.Help', no_payload=True,
  184. scope='local', read=True)
  185. @asyncio.coroutine
  186. def vm_property_help(self):
  187. '''Get help for one property'''
  188. return self._property_help(self.dest)
  189. @qubes.api.method('admin.property.Help', no_payload=True,
  190. scope='global', read=True)
  191. @asyncio.coroutine
  192. def property_help(self):
  193. '''Get help for one property'''
  194. assert self.dest.name == 'dom0'
  195. return self._property_help(self.app)
  196. def _property_help(self, dest):
  197. if self.arg not in dest.property_list():
  198. raise qubes.exc.QubesNoSuchPropertyError(dest, self.arg)
  199. self.fire_event_for_permission()
  200. try:
  201. doc = dest.property_get_def(self.arg).__doc__
  202. except AttributeError:
  203. return ''
  204. return qubes.utils.format_doc(doc)
  205. @qubes.api.method('admin.vm.property.Reset', no_payload=True,
  206. scope='local', write=True)
  207. @asyncio.coroutine
  208. def vm_property_reset(self):
  209. '''Reset a property to a default value'''
  210. return self._property_reset(self.dest)
  211. @qubes.api.method('admin.property.Reset', no_payload=True,
  212. scope='global', write=True)
  213. @asyncio.coroutine
  214. def property_reset(self):
  215. '''Reset a property to a default value'''
  216. assert self.dest.name == 'dom0'
  217. return self._property_reset(self.app)
  218. def _property_reset(self, dest):
  219. if self.arg not in dest.property_list():
  220. raise qubes.exc.QubesNoSuchPropertyError(dest, self.arg)
  221. self.fire_event_for_permission()
  222. delattr(dest, self.arg)
  223. self.app.save()
  224. @qubes.api.method('admin.vm.volume.List', no_payload=True,
  225. scope='local', read=True)
  226. @asyncio.coroutine
  227. def vm_volume_list(self):
  228. assert not self.arg
  229. volume_names = self.fire_event_for_filter(self.dest.volumes.keys())
  230. return ''.join('{}\n'.format(name) for name in volume_names)
  231. @qubes.api.method('admin.vm.volume.Info', no_payload=True,
  232. scope='local', read=True)
  233. @asyncio.coroutine
  234. def vm_volume_info(self):
  235. assert self.arg in self.dest.volumes.keys()
  236. self.fire_event_for_permission()
  237. volume = self.dest.volumes[self.arg]
  238. # properties defined in API
  239. volume_properties = [
  240. 'pool', 'vid', 'size', 'usage', 'rw', 'source',
  241. 'save_on_stop', 'snap_on_start']
  242. return ''.join('{}={}\n'.format(key, getattr(volume, key)) for key in
  243. volume_properties)
  244. @qubes.api.method('admin.vm.volume.ListSnapshots', no_payload=True,
  245. scope='local', read=True)
  246. @asyncio.coroutine
  247. def vm_volume_listsnapshots(self):
  248. assert self.arg in self.dest.volumes.keys()
  249. volume = self.dest.volumes[self.arg]
  250. revisions = [revision for revision in volume.revisions]
  251. revisions = self.fire_event_for_filter(revisions)
  252. return ''.join('{}\n'.format(revision) for revision in revisions)
  253. @qubes.api.method('admin.vm.volume.Revert',
  254. scope='local', write=True)
  255. @asyncio.coroutine
  256. def vm_volume_revert(self, untrusted_payload):
  257. assert self.arg in self.dest.volumes.keys()
  258. untrusted_revision = untrusted_payload.decode('ascii').strip()
  259. del untrusted_payload
  260. volume = self.dest.volumes[self.arg]
  261. snapshots = volume.revisions
  262. assert untrusted_revision in snapshots
  263. revision = untrusted_revision
  264. self.fire_event_for_permission(volume=volume, revision=revision)
  265. ret = volume.revert(revision)
  266. if asyncio.iscoroutine(ret):
  267. yield from ret
  268. self.app.save()
  269. # write=True because this allow to clone VM - and most likely modify that
  270. # one - still having the same data
  271. @qubes.api.method('admin.vm.volume.CloneFrom', no_payload=True,
  272. scope='local', write=True)
  273. @asyncio.coroutine
  274. def vm_volume_clone_from(self):
  275. assert self.arg in self.dest.volumes.keys()
  276. volume = self.dest.volumes[self.arg]
  277. self.fire_event_for_permission(volume=volume)
  278. token = qubes.utils.random_string(32)
  279. # save token on self.app, as self is not persistent
  280. if not hasattr(self.app, 'api_admin_pending_clone'):
  281. self.app.api_admin_pending_clone = {}
  282. # don't handle collisions any better - if someone is so much out of
  283. # luck, can try again anyway
  284. assert token not in self.app.api_admin_pending_clone
  285. self.app.api_admin_pending_clone[token] = volume
  286. return token
  287. @qubes.api.method('admin.vm.volume.CloneTo',
  288. scope='local', write=True)
  289. @asyncio.coroutine
  290. def vm_volume_clone_to(self, untrusted_payload):
  291. assert self.arg in self.dest.volumes.keys()
  292. untrusted_token = untrusted_payload.decode('ascii').strip()
  293. del untrusted_payload
  294. assert untrusted_token in getattr(self.app,
  295. 'api_admin_pending_clone', {})
  296. token = untrusted_token
  297. del untrusted_token
  298. src_volume = self.app.api_admin_pending_clone[token]
  299. del self.app.api_admin_pending_clone[token]
  300. # make sure the volume still exists, but invalidate token anyway
  301. assert str(src_volume.pool) in self.app.pools
  302. assert src_volume in self.app.pools[str(src_volume.pool)].volumes
  303. dst_volume = self.dest.volumes[self.arg]
  304. self.fire_event_for_permission(src_volume=src_volume,
  305. dst_volume=dst_volume)
  306. op_retval = dst_volume.import_volume(src_volume)
  307. # clone/import functions may be either synchronous or asynchronous
  308. # in the later case, we need to wait for them to finish
  309. if asyncio.iscoroutine(op_retval):
  310. op_retval = yield from op_retval
  311. self.dest.volumes[self.arg] = op_retval
  312. self.app.save()
  313. @qubes.api.method('admin.vm.volume.Resize',
  314. scope='local', write=True)
  315. @asyncio.coroutine
  316. def vm_volume_resize(self, untrusted_payload):
  317. assert self.arg in self.dest.volumes.keys()
  318. untrusted_size = untrusted_payload.decode('ascii').strip()
  319. del untrusted_payload
  320. assert untrusted_size.isdigit() # only digits, forbid '-' too
  321. assert len(untrusted_size) <= 20 # limit to about 2^64
  322. size = int(untrusted_size)
  323. self.fire_event_for_permission(size=size)
  324. yield from self.dest.storage.resize(self.arg, size)
  325. self.app.save()
  326. @qubes.api.method('admin.vm.volume.Import', no_payload=True,
  327. scope='local', write=True)
  328. @asyncio.coroutine
  329. def vm_volume_import(self):
  330. '''Import volume data.
  331. Note that this function only returns a path to where data should be
  332. written, actual importing is done by a script in /etc/qubes-rpc
  333. When the script finish importing, it will trigger
  334. internal.vm.volume.ImportEnd (with either b'ok' or b'fail' as a
  335. payload) and response from that call will be actually send to the
  336. caller.
  337. '''
  338. assert self.arg in self.dest.volumes.keys()
  339. self.fire_event_for_permission()
  340. if not self.dest.is_halted():
  341. raise qubes.exc.QubesVMNotHaltedError(self.dest)
  342. path = self.dest.storage.import_data(self.arg)
  343. assert ' ' not in path
  344. size = self.dest.volumes[self.arg].size
  345. # when we know the action is allowed, inform extensions that it will
  346. # be performed
  347. self.dest.fire_event('domain-volume-import-begin', volume=self.arg)
  348. return '{} {}'.format(size, path)
  349. @qubes.api.method('admin.vm.tag.List', no_payload=True,
  350. scope='local', read=True)
  351. @asyncio.coroutine
  352. def vm_tag_list(self):
  353. assert not self.arg
  354. tags = self.dest.tags
  355. tags = self.fire_event_for_filter(tags)
  356. return ''.join('{}\n'.format(tag) for tag in sorted(tags))
  357. @qubes.api.method('admin.vm.tag.Get', no_payload=True,
  358. scope='local', read=True)
  359. @asyncio.coroutine
  360. def vm_tag_get(self):
  361. qubes.vm.Tags.validate_tag(self.arg)
  362. self.fire_event_for_permission()
  363. return '1' if self.arg in self.dest.tags else '0'
  364. @qubes.api.method('admin.vm.tag.Set', no_payload=True,
  365. scope='local', write=True)
  366. @asyncio.coroutine
  367. def vm_tag_set(self):
  368. qubes.vm.Tags.validate_tag(self.arg)
  369. self.fire_event_for_permission()
  370. self.dest.tags.add(self.arg)
  371. self.app.save()
  372. @qubes.api.method('admin.vm.tag.Remove', no_payload=True,
  373. scope='local', write=True)
  374. @asyncio.coroutine
  375. def vm_tag_remove(self):
  376. qubes.vm.Tags.validate_tag(self.arg)
  377. self.fire_event_for_permission()
  378. try:
  379. self.dest.tags.remove(self.arg)
  380. except KeyError:
  381. raise qubes.exc.QubesTagNotFoundError(self.dest, self.arg)
  382. self.app.save()
  383. @qubes.api.method('admin.pool.List', no_payload=True,
  384. scope='global', read=True)
  385. @asyncio.coroutine
  386. def pool_list(self):
  387. assert not self.arg
  388. assert self.dest.name == 'dom0'
  389. pools = self.fire_event_for_filter(self.app.pools)
  390. return ''.join('{}\n'.format(pool) for pool in pools)
  391. @qubes.api.method('admin.pool.ListDrivers', no_payload=True,
  392. scope='global', read=True)
  393. @asyncio.coroutine
  394. def pool_listdrivers(self):
  395. assert self.dest.name == 'dom0'
  396. assert not self.arg
  397. drivers = self.fire_event_for_filter(qubes.storage.pool_drivers())
  398. return ''.join('{} {}\n'.format(
  399. driver,
  400. ' '.join(qubes.storage.driver_parameters(driver)))
  401. for driver in drivers)
  402. @qubes.api.method('admin.pool.Info', no_payload=True,
  403. scope='global', read=True)
  404. @asyncio.coroutine
  405. def pool_info(self):
  406. assert self.dest.name == 'dom0'
  407. assert self.arg in self.app.pools.keys()
  408. pool = self.app.pools[self.arg]
  409. self.fire_event_for_permission(pool=pool)
  410. return ''.join('{}={}\n'.format(prop, val)
  411. for prop, val in sorted(pool.config.items()))
  412. @qubes.api.method('admin.pool.Add',
  413. scope='global', write=True)
  414. @asyncio.coroutine
  415. def pool_add(self, untrusted_payload):
  416. assert self.dest.name == 'dom0'
  417. drivers = qubes.storage.pool_drivers()
  418. assert self.arg in drivers
  419. untrusted_pool_config = untrusted_payload.decode('ascii').splitlines()
  420. del untrusted_payload
  421. assert all(('=' in line) for line in untrusted_pool_config)
  422. # pairs of (option, value)
  423. untrusted_pool_config = [line.split('=', 1)
  424. for line in untrusted_pool_config]
  425. # reject duplicated options
  426. assert len(set(x[0] for x in untrusted_pool_config)) == \
  427. len([x[0] for x in untrusted_pool_config])
  428. # and convert to dict
  429. untrusted_pool_config = dict(untrusted_pool_config)
  430. assert 'name' in untrusted_pool_config
  431. untrusted_pool_name = untrusted_pool_config.pop('name')
  432. allowed_chars = string.ascii_letters + string.digits + '-_.'
  433. assert all(c in allowed_chars for c in untrusted_pool_name)
  434. pool_name = untrusted_pool_name
  435. assert pool_name not in self.app.pools
  436. driver_parameters = qubes.storage.driver_parameters(self.arg)
  437. assert all(key in driver_parameters for key in untrusted_pool_config)
  438. pool_config = untrusted_pool_config
  439. self.fire_event_for_permission(name=pool_name,
  440. pool_config=pool_config)
  441. self.app.add_pool(name=pool_name, driver=self.arg, **pool_config)
  442. self.app.save()
  443. @qubes.api.method('admin.pool.Remove', no_payload=True,
  444. scope='global', write=True)
  445. @asyncio.coroutine
  446. def pool_remove(self):
  447. assert self.dest.name == 'dom0'
  448. assert self.arg in self.app.pools.keys()
  449. self.fire_event_for_permission()
  450. self.app.remove_pool(self.arg)
  451. self.app.save()
  452. @qubes.api.method('admin.label.List', no_payload=True,
  453. scope='global', read=True)
  454. @asyncio.coroutine
  455. def label_list(self):
  456. assert self.dest.name == 'dom0'
  457. assert not self.arg
  458. labels = self.fire_event_for_filter(self.app.labels.values())
  459. return ''.join('{}\n'.format(label.name) for label in labels)
  460. @qubes.api.method('admin.label.Get', no_payload=True,
  461. scope='global', read=True)
  462. @asyncio.coroutine
  463. def label_get(self):
  464. assert self.dest.name == 'dom0'
  465. try:
  466. label = self.app.get_label(self.arg)
  467. except KeyError:
  468. raise qubes.exc.QubesValueError
  469. self.fire_event_for_permission(label=label)
  470. return label.color
  471. @qubes.api.method('admin.label.Index', no_payload=True,
  472. scope='global', read=True)
  473. @asyncio.coroutine
  474. def label_index(self):
  475. assert self.dest.name == 'dom0'
  476. try:
  477. label = self.app.get_label(self.arg)
  478. except KeyError:
  479. raise qubes.exc.QubesValueError
  480. self.fire_event_for_permission(label=label)
  481. return str(label.index)
  482. @qubes.api.method('admin.label.Create',
  483. scope='global', write=True)
  484. @asyncio.coroutine
  485. def label_create(self, untrusted_payload):
  486. assert self.dest.name == 'dom0'
  487. # don't confuse label name with label index
  488. assert not self.arg.isdigit()
  489. allowed_chars = string.ascii_letters + string.digits + '-_.'
  490. assert all(c in allowed_chars for c in self.arg)
  491. try:
  492. self.app.get_label(self.arg)
  493. except KeyError:
  494. # ok, no such label yet
  495. pass
  496. else:
  497. raise qubes.exc.QubesValueError('label already exists')
  498. untrusted_payload = untrusted_payload.decode('ascii').strip()
  499. assert len(untrusted_payload) == 8
  500. assert untrusted_payload.startswith('0x')
  501. # besides prefix, only hex digits are allowed
  502. assert all(x in string.hexdigits for x in untrusted_payload[2:])
  503. # SEE: #2732
  504. color = untrusted_payload
  505. self.fire_event_for_permission(color=color)
  506. # allocate new index, but make sure it's outside of default labels set
  507. new_index = max(
  508. qubes.config.max_default_label, *self.app.labels.keys()) + 1
  509. label = qubes.Label(new_index, color, self.arg)
  510. self.app.labels[new_index] = label
  511. self.app.save()
  512. @qubes.api.method('admin.label.Remove', no_payload=True,
  513. scope='global', write=True)
  514. @asyncio.coroutine
  515. def label_remove(self):
  516. assert self.dest.name == 'dom0'
  517. try:
  518. label = self.app.get_label(self.arg)
  519. except KeyError:
  520. raise qubes.exc.QubesValueError
  521. # don't allow removing default labels
  522. assert label.index > qubes.config.max_default_label
  523. # FIXME: this should be in app.add_label()
  524. for vm in self.app.domains:
  525. if vm.label == label:
  526. raise qubes.exc.QubesException('label still in use')
  527. self.fire_event_for_permission(label=label)
  528. del self.app.labels[label.index]
  529. self.app.save()
  530. @qubes.api.method('admin.vm.Start', no_payload=True,
  531. scope='local', execute=True)
  532. @asyncio.coroutine
  533. def vm_start(self):
  534. assert not self.arg
  535. self.fire_event_for_permission()
  536. try:
  537. yield from self.dest.start()
  538. except libvirt.libvirtError as e:
  539. # change to QubesException, so will be reported to the user
  540. raise qubes.exc.QubesException('Start failed: ' + str(e))
  541. @qubes.api.method('admin.vm.Shutdown', no_payload=True,
  542. scope='local', execute=True)
  543. @asyncio.coroutine
  544. def vm_shutdown(self):
  545. assert not self.arg
  546. self.fire_event_for_permission()
  547. yield from self.dest.shutdown()
  548. @qubes.api.method('admin.vm.Pause', no_payload=True,
  549. scope='local', execute=True)
  550. @asyncio.coroutine
  551. def vm_pause(self):
  552. assert not self.arg
  553. self.fire_event_for_permission()
  554. yield from self.dest.pause()
  555. @qubes.api.method('admin.vm.Unpause', no_payload=True,
  556. scope='local', execute=True)
  557. @asyncio.coroutine
  558. def vm_unpause(self):
  559. assert not self.arg
  560. self.fire_event_for_permission()
  561. yield from self.dest.unpause()
  562. @qubes.api.method('admin.vm.Kill', no_payload=True,
  563. scope='local', execute=True)
  564. @asyncio.coroutine
  565. def vm_kill(self):
  566. assert not self.arg
  567. self.fire_event_for_permission()
  568. yield from self.dest.kill()
  569. @qubes.api.method('admin.Events', no_payload=True,
  570. scope='global', read=True)
  571. @asyncio.coroutine
  572. def events(self):
  573. assert not self.arg
  574. # run until client connection is terminated
  575. self.cancellable = True
  576. wait_for_cancel = asyncio.get_event_loop().create_future()
  577. # cache event filters, to not call an event each time an event arrives
  578. event_filters = self.fire_event_for_permission()
  579. dispatcher = QubesMgmtEventsDispatcher(event_filters, self.send_event)
  580. if self.dest.name == 'dom0':
  581. self.app.add_handler('*', dispatcher.app_handler)
  582. self.app.add_handler('domain-add', dispatcher.on_domain_add)
  583. self.app.add_handler('domain-delete', dispatcher.on_domain_delete)
  584. for vm in self.app.domains:
  585. vm.add_handler('*', dispatcher.vm_handler)
  586. else:
  587. self.dest.add_handler('*', dispatcher.vm_handler)
  588. # send artificial event as a confirmation that connection is established
  589. self.send_event(self.app, 'connection-established')
  590. try:
  591. yield from wait_for_cancel
  592. except asyncio.CancelledError:
  593. # the above waiting was already interrupted, this is all we need
  594. pass
  595. if self.dest.name == 'dom0':
  596. self.app.remove_handler('*', dispatcher.app_handler)
  597. self.app.remove_handler('domain-add', dispatcher.on_domain_add)
  598. self.app.remove_handler('domain-delete',
  599. dispatcher.on_domain_delete)
  600. for vm in self.app.domains:
  601. vm.remove_handler('*', dispatcher.vm_handler)
  602. else:
  603. self.dest.remove_handler('*', dispatcher.vm_handler)
  604. @qubes.api.method('admin.vm.feature.List', no_payload=True,
  605. scope='local', read=True)
  606. @asyncio.coroutine
  607. def vm_feature_list(self):
  608. assert not self.arg
  609. features = self.fire_event_for_filter(self.dest.features.keys())
  610. return ''.join('{}\n'.format(feature) for feature in features)
  611. @qubes.api.method('admin.vm.feature.Get', no_payload=True,
  612. scope='local', read=True)
  613. @asyncio.coroutine
  614. def vm_feature_get(self):
  615. # validation of self.arg done by qrexec-policy is enough
  616. self.fire_event_for_permission()
  617. try:
  618. value = self.dest.features[self.arg]
  619. except KeyError:
  620. raise qubes.exc.QubesFeatureNotFoundError(self.dest, self.arg)
  621. return value
  622. @qubes.api.method('admin.vm.feature.CheckWithTemplate', no_payload=True,
  623. scope='local', read=True)
  624. @asyncio.coroutine
  625. def vm_feature_checkwithtemplate(self):
  626. # validation of self.arg done by qrexec-policy is enough
  627. self.fire_event_for_permission()
  628. try:
  629. value = self.dest.features.check_with_template(self.arg)
  630. except KeyError:
  631. raise qubes.exc.QubesFeatureNotFoundError(self.dest, self.arg)
  632. return value
  633. @qubes.api.method('admin.vm.feature.Remove', no_payload=True,
  634. scope='local', write=True)
  635. @asyncio.coroutine
  636. def vm_feature_remove(self):
  637. # validation of self.arg done by qrexec-policy is enough
  638. self.fire_event_for_permission()
  639. try:
  640. del self.dest.features[self.arg]
  641. except KeyError:
  642. raise qubes.exc.QubesFeatureNotFoundError(self.dest, self.arg)
  643. self.app.save()
  644. @qubes.api.method('admin.vm.feature.Set',
  645. scope='local', write=True)
  646. @asyncio.coroutine
  647. def vm_feature_set(self, untrusted_payload):
  648. # validation of self.arg done by qrexec-policy is enough
  649. value = untrusted_payload.decode('ascii', errors='strict')
  650. del untrusted_payload
  651. self.fire_event_for_permission(value=value)
  652. self.dest.features[self.arg] = value
  653. self.app.save()
  654. @qubes.api.method('admin.vm.Create.{endpoint}', endpoints=(ep.name
  655. for ep in pkg_resources.iter_entry_points(qubes.vm.VM_ENTRY_POINT)),
  656. scope='global', write=True)
  657. @asyncio.coroutine
  658. def vm_create(self, endpoint, untrusted_payload=None):
  659. return self._vm_create(endpoint, allow_pool=False,
  660. untrusted_payload=untrusted_payload)
  661. @qubes.api.method('admin.vm.CreateInPool.{endpoint}', endpoints=(ep.name
  662. for ep in pkg_resources.iter_entry_points(qubes.vm.VM_ENTRY_POINT)),
  663. scope='global', write=True)
  664. @asyncio.coroutine
  665. def vm_create_in_pool(self, endpoint, untrusted_payload=None):
  666. return self._vm_create(endpoint, allow_pool=True,
  667. untrusted_payload=untrusted_payload)
  668. def _vm_create(self, vm_type, allow_pool=False, untrusted_payload=None):
  669. assert self.dest.name == 'dom0'
  670. kwargs = {}
  671. pool = None
  672. pools = {}
  673. # this will raise exception if none is found
  674. vm_class = qubes.utils.get_entry_point_one(qubes.vm.VM_ENTRY_POINT,
  675. vm_type)
  676. # if argument is given, it needs to be a valid template, and only
  677. # when given VM class do need a template
  678. if hasattr(vm_class, 'template'):
  679. if self.arg:
  680. assert self.arg in self.app.domains
  681. kwargs['template'] = self.app.domains[self.arg]
  682. else:
  683. assert not self.arg
  684. for untrusted_param in untrusted_payload.decode('ascii',
  685. errors='strict').split(' '):
  686. untrusted_key, untrusted_value = untrusted_param.split('=', 1)
  687. if untrusted_key in kwargs:
  688. raise qubes.api.ProtocolError('duplicated parameters')
  689. if untrusted_key == 'name':
  690. qubes.vm.validate_name(None, None, untrusted_value)
  691. kwargs['name'] = untrusted_value
  692. elif untrusted_key == 'label':
  693. # don't confuse label name with label index
  694. assert not untrusted_value.isdigit()
  695. allowed_chars = string.ascii_letters + string.digits + '-_.'
  696. assert all(c in allowed_chars for c in untrusted_value)
  697. try:
  698. kwargs['label'] = self.app.get_label(untrusted_value)
  699. except KeyError:
  700. raise qubes.exc.QubesValueError
  701. elif untrusted_key == 'pool' and allow_pool:
  702. if pool is not None:
  703. raise qubes.api.ProtocolError('duplicated pool parameter')
  704. pool = self.app.get_pool(untrusted_value)
  705. elif untrusted_key.startswith('pool:') and allow_pool:
  706. untrusted_volume = untrusted_key.split(':', 1)[1]
  707. # kind of ugly, but actual list of volumes is available only
  708. # after creating a VM
  709. assert untrusted_volume in ['root', 'private', 'volatile',
  710. 'kernel']
  711. volume = untrusted_volume
  712. if volume in pools:
  713. raise qubes.api.ProtocolError(
  714. 'duplicated pool:{} parameter'.format(volume))
  715. pools[volume] = self.app.get_pool(untrusted_value)
  716. else:
  717. raise qubes.api.ProtocolError('Invalid param name')
  718. del untrusted_payload
  719. if 'name' not in kwargs or 'label' not in kwargs:
  720. raise qubes.api.ProtocolError('Missing name or label')
  721. if pool and pools:
  722. raise qubes.api.ProtocolError(
  723. 'Only one of \'pool=\' and \'pool:volume=\' can be used')
  724. if kwargs['name'] in self.app.domains:
  725. raise qubes.exc.QubesValueError(
  726. 'VM {} already exists'.format(kwargs['name']))
  727. self.fire_event_for_permission(pool=pool, pools=pools, **kwargs)
  728. vm = self.app.add_new_vm(vm_class, **kwargs)
  729. # TODO: move this to extension (in race-free fashion)
  730. vm.tags.add('created-by-' + str(self.src))
  731. try:
  732. yield from vm.create_on_disk(pool=pool, pools=pools)
  733. except:
  734. del self.app.domains[vm]
  735. raise
  736. self.app.save()
  737. @qubes.api.method('admin.vm.CreateDisposable', no_payload=True,
  738. scope='global', write=True)
  739. @asyncio.coroutine
  740. def create_disposable(self):
  741. assert not self.arg
  742. if self.dest.name == 'dom0':
  743. dispvm_template = self.src.default_dispvm
  744. else:
  745. dispvm_template = self.dest
  746. self.fire_event_for_permission(dispvm_template=dispvm_template)
  747. dispvm = yield from qubes.vm.dispvm.DispVM.from_appvm(dispvm_template)
  748. # TODO: move this to extension (in race-free fashion, better than here)
  749. dispvm.tags.add('disp-created-by-' + str(self.src))
  750. return dispvm.name
  751. @qubes.api.method('admin.vm.Remove', no_payload=True,
  752. scope='global', write=True)
  753. @asyncio.coroutine
  754. def vm_remove(self):
  755. assert not self.arg
  756. self.fire_event_for_permission()
  757. if not self.dest.is_halted():
  758. raise qubes.exc.QubesVMNotHaltedError(self.dest)
  759. del self.app.domains[self.dest]
  760. try:
  761. yield from self.dest.remove_from_disk()
  762. except: # pylint: disable=bare-except
  763. self.app.log.exception('Error wile removing VM \'%s\' files',
  764. self.dest.name)
  765. self.app.save()
  766. @qubes.api.method('admin.vm.device.{endpoint}.Available', endpoints=(ep.name
  767. for ep in pkg_resources.iter_entry_points('qubes.devices')),
  768. no_payload=True,
  769. scope='local', read=True)
  770. @asyncio.coroutine
  771. def vm_device_available(self, endpoint):
  772. devclass = endpoint
  773. devices = self.dest.devices[devclass].available()
  774. if self.arg:
  775. devices = [dev for dev in devices if dev.ident == self.arg]
  776. # no duplicated devices, but device may not exists, in which case
  777. # the list is empty
  778. assert len(devices) <= 1
  779. devices = self.fire_event_for_filter(devices, devclass=devclass)
  780. dev_info = {}
  781. for dev in devices:
  782. non_default_attrs = set(attr for attr in dir(dev) if
  783. not attr.startswith('_')).difference((
  784. 'backend_domain', 'ident', 'frontend_domain',
  785. 'description', 'options'))
  786. properties_txt = ' '.join(
  787. '{}={!s}'.format(prop, value) for prop, value
  788. in itertools.chain(
  789. ((key, getattr(dev, key)) for key in non_default_attrs),
  790. # keep description as the last one, according to API
  791. # specification
  792. (('description', dev.description),)
  793. ))
  794. assert '\n' not in properties_txt
  795. dev_info[dev.ident] = properties_txt
  796. return ''.join('{} {}\n'.format(ident, dev_info[ident])
  797. for ident in sorted(dev_info))
  798. @qubes.api.method('admin.vm.device.{endpoint}.List', endpoints=(ep.name
  799. for ep in pkg_resources.iter_entry_points('qubes.devices')),
  800. no_payload=True,
  801. scope='local', read=True)
  802. @asyncio.coroutine
  803. def vm_device_list(self, endpoint):
  804. devclass = endpoint
  805. device_assignments = self.dest.devices[devclass].assignments()
  806. if self.arg:
  807. select_backend, select_ident = self.arg.split('+', 1)
  808. device_assignments = [dev for dev in device_assignments
  809. if (str(dev.backend_domain), dev.ident)
  810. == (select_backend, select_ident)]
  811. # no duplicated devices, but device may not exists, in which case
  812. # the list is empty
  813. assert len(device_assignments) <= 1
  814. device_assignments = self.fire_event_for_filter(device_assignments,
  815. devclass=devclass)
  816. dev_info = {}
  817. for dev in device_assignments:
  818. properties_txt = ' '.join(
  819. '{}={!s}'.format(opt, value) for opt, value
  820. in itertools.chain(
  821. dev.options.items(),
  822. (('persistent', 'yes' if dev.persistent else 'no'),)
  823. ))
  824. assert '\n' not in properties_txt
  825. ident = '{!s}+{!s}'.format(dev.backend_domain, dev.ident)
  826. dev_info[ident] = properties_txt
  827. return ''.join('{} {}\n'.format(ident, dev_info[ident])
  828. for ident in sorted(dev_info))
  829. # Attach/Detach action can both modify persistent state (with
  830. # persistent=True) and volatile state of running VM (with persistent=False).
  831. # For this reason, write=True + execute=True
  832. @qubes.api.method('admin.vm.device.{endpoint}.Attach', endpoints=(ep.name
  833. for ep in pkg_resources.iter_entry_points('qubes.devices')),
  834. scope='local', write=True, execute=True)
  835. @asyncio.coroutine
  836. def vm_device_attach(self, endpoint, untrusted_payload):
  837. devclass = endpoint
  838. options = {}
  839. persistent = False
  840. for untrusted_option in untrusted_payload.decode('ascii').split():
  841. try:
  842. untrusted_key, untrusted_value = untrusted_option.split('=', 1)
  843. except ValueError:
  844. raise qubes.api.ProtocolError('Invalid options format')
  845. if untrusted_key == 'persistent':
  846. persistent = qubes.property.bool(None, None, untrusted_value)
  847. else:
  848. allowed_chars_key = string.digits + string.ascii_letters + '-_.'
  849. allowed_chars_value = allowed_chars_key + ',+:'
  850. if any(x not in allowed_chars_key for x in untrusted_key):
  851. raise qubes.api.ProtocolError(
  852. 'Invalid chars in option name')
  853. if any(x not in allowed_chars_value for x in untrusted_value):
  854. raise qubes.api.ProtocolError(
  855. 'Invalid chars in option value')
  856. options[untrusted_key] = untrusted_value
  857. # qrexec already verified that no strange characters are in self.arg
  858. backend_domain, ident = self.arg.split('+', 1)
  859. # may raise KeyError, either on domain or ident
  860. dev = self.app.domains[backend_domain].devices[devclass][ident]
  861. self.fire_event_for_permission(device=dev,
  862. devclass=devclass, persistent=persistent,
  863. options=options)
  864. assignment = qubes.devices.DeviceAssignment(
  865. dev.backend_domain, dev.ident,
  866. options=options, persistent=persistent)
  867. yield from self.dest.devices[devclass].attach(assignment)
  868. self.app.save()
  869. # Attach/Detach action can both modify persistent state (with
  870. # persistent=True) and volatile state of running VM (with persistent=False).
  871. # For this reason, write=True + execute=True
  872. @qubes.api.method('admin.vm.device.{endpoint}.Detach', endpoints=(ep.name
  873. for ep in pkg_resources.iter_entry_points('qubes.devices')),
  874. no_payload=True,
  875. scope='local', write=True, execute=True)
  876. @asyncio.coroutine
  877. def vm_device_detach(self, endpoint):
  878. devclass = endpoint
  879. # qrexec already verified that no strange characters are in self.arg
  880. backend_domain, ident = self.arg.split('+', 1)
  881. # may raise KeyError; if device isn't found, it will be UnknownDevice
  882. # instance - but allow it, otherwise it will be impossible to detach
  883. # already removed device
  884. dev = self.app.domains[backend_domain].devices[devclass][ident]
  885. self.fire_event_for_permission(device=dev,
  886. devclass=devclass)
  887. assignment = qubes.devices.DeviceAssignment(
  888. dev.backend_domain, dev.ident)
  889. yield from self.dest.devices[devclass].detach(assignment)
  890. self.app.save()
  891. # Attach/Detach action can both modify persistent state (with
  892. # persistent=True) and volatile state of running VM (with persistent=False).
  893. # For this reason, write=True + execute=True
  894. @qubes.api.method('admin.vm.device.{endpoint}.Set.persistent',
  895. endpoints=(ep.name
  896. for ep in pkg_resources.iter_entry_points('qubes.devices')),
  897. scope='local', write=True, execute=True)
  898. @asyncio.coroutine
  899. def vm_device_set_persistent(self, endpoint, untrusted_payload):
  900. devclass = endpoint
  901. assert untrusted_payload in (b'True', b'False')
  902. persistent = untrusted_payload == b'True'
  903. del untrusted_payload
  904. # qrexec already verified that no strange characters are in self.arg
  905. backend_domain, ident = self.arg.split('+', 1)
  906. # device must be already attached
  907. matching_devices = [dev for dev
  908. in self.dest.devices[devclass].attached()
  909. if dev.backend_domain.name == backend_domain and dev.ident == ident]
  910. assert len(matching_devices) == 1
  911. dev = matching_devices[0]
  912. self.fire_event_for_permission(device=dev,
  913. persistent=persistent)
  914. self.dest.devices[devclass].update_persistent(dev, persistent)
  915. self.app.save()
  916. @qubes.api.method('admin.vm.firewall.Get', no_payload=True,
  917. scope='local', read=True)
  918. @asyncio.coroutine
  919. def vm_firewall_get(self):
  920. assert not self.arg
  921. self.fire_event_for_permission()
  922. return ''.join('{}\n'.format(rule.api_rule)
  923. for rule in self.dest.firewall.rules)
  924. @qubes.api.method('admin.vm.firewall.Set',
  925. scope='local', write=True)
  926. @asyncio.coroutine
  927. def vm_firewall_set(self, untrusted_payload):
  928. assert not self.arg
  929. rules = []
  930. for untrusted_line in untrusted_payload.decode('ascii',
  931. errors='strict').splitlines():
  932. rule = qubes.firewall.Rule.from_api_string(
  933. untrusted_rule=untrusted_line)
  934. rules.append(rule)
  935. self.fire_event_for_permission(rules=rules)
  936. self.dest.firewall.rules = rules
  937. self.dest.firewall.save()
  938. @qubes.api.method('admin.vm.firewall.Reload', no_payload=True,
  939. scope='local', execute=True)
  940. @asyncio.coroutine
  941. def vm_firewall_reload(self):
  942. assert not self.arg
  943. self.fire_event_for_permission()
  944. self.dest.fire_event('firewall-changed')
  945. @asyncio.coroutine
  946. def _load_backup_profile(self, profile_name, skip_passphrase=False):
  947. '''Load backup profile and return :py:class:`qubes.backup.Backup`
  948. instance
  949. :param profile_name: name of the profile
  950. :param skip_passphrase: do not load passphrase - only backup summary
  951. can be retrieved when this option is in use
  952. '''
  953. profile_path = os.path.join(
  954. qubes.config.backup_profile_dir, profile_name + '.conf')
  955. with open(profile_path) as profile_file:
  956. profile_data = yaml.safe_load(profile_file)
  957. try:
  958. dest_vm = profile_data['destination_vm']
  959. dest_path = profile_data['destination_path']
  960. include_vms = profile_data['include']
  961. exclude_vms = profile_data.get('exclude', [])
  962. compression = profile_data.get('compression', True)
  963. except KeyError as err:
  964. raise qubes.exc.QubesException(
  965. 'Invalid backup profile - missing {}'.format(err))
  966. try:
  967. dest_vm = self.app.domains[dest_vm]
  968. except KeyError:
  969. raise qubes.exc.QubesException(
  970. 'Invalid destination_vm specified in backup profile')
  971. if isinstance(dest_vm, qubes.vm.adminvm.AdminVM):
  972. dest_vm = None
  973. if skip_passphrase:
  974. passphrase = None
  975. elif 'passphrase_text' in profile_data:
  976. passphrase = profile_data['passphrase_text']
  977. elif 'passphrase_vm' in profile_data:
  978. passphrase_vm_name = profile_data['passphrase_vm']
  979. try:
  980. passphrase_vm = self.app.domains[passphrase_vm_name]
  981. except KeyError:
  982. raise qubes.exc.QubesException(
  983. 'Invalid backup profile - invalid passphrase_vm')
  984. try:
  985. passphrase, _ = yield from passphrase_vm.run_service_for_stdio(
  986. 'qubes.BackupPassphrase+' + self.arg)
  987. # make it foolproof against "echo passphrase" implementation
  988. passphrase = passphrase.strip()
  989. assert b'\n' not in passphrase
  990. except subprocess.CalledProcessError:
  991. raise qubes.exc.QubesException(
  992. 'Failed to retrieve passphrase from \'{}\' VM'.format(
  993. passphrase_vm_name))
  994. else:
  995. raise qubes.exc.QubesException(
  996. 'Invalid backup profile - you need to '
  997. 'specify passphrase_text or passphrase_vm')
  998. # handle include
  999. vms_to_backup = set(vm for vm in self.app.domains
  1000. if any(qubes.utils.match_vm_name_with_special(vm, name)
  1001. for name in include_vms))
  1002. # handle exclude
  1003. vms_to_backup.difference_update(vm for vm in self.app.domains
  1004. if any(qubes.utils.match_vm_name_with_special(vm, name)
  1005. for name in exclude_vms))
  1006. kwargs = {
  1007. 'target_vm': dest_vm,
  1008. 'target_dir': dest_path,
  1009. 'compressed': bool(compression),
  1010. 'passphrase': passphrase,
  1011. }
  1012. if isinstance(compression, str):
  1013. kwargs['compression_filter'] = compression
  1014. backup = qubes.backup.Backup(self.app, vms_to_backup, **kwargs)
  1015. return backup
  1016. def _backup_progress_callback(self, profile_name, progress):
  1017. self.app.fire_event('backup-progress', backup_profile=profile_name,
  1018. progress=progress)
  1019. @qubes.api.method('admin.backup.Execute', no_payload=True,
  1020. scope='global', read=True, execute=True)
  1021. @asyncio.coroutine
  1022. def backup_execute(self):
  1023. assert self.dest.name == 'dom0'
  1024. assert self.arg
  1025. assert '/' not in self.arg
  1026. self.fire_event_for_permission()
  1027. profile_path = os.path.join(qubes.config.backup_profile_dir,
  1028. self.arg + '.conf')
  1029. if not os.path.exists(profile_path):
  1030. raise qubes.api.PermissionDenied(
  1031. 'Backup profile {} does not exist'.format(self.arg))
  1032. if not hasattr(self.app, 'api_admin_running_backups'):
  1033. self.app.api_admin_running_backups = {}
  1034. backup = yield from self._load_backup_profile(self.arg)
  1035. backup.progress_callback = functools.partial(
  1036. self._backup_progress_callback, self.arg)
  1037. # forbid running the same backup operation twice at the time
  1038. assert self.arg not in self.app.api_admin_running_backups
  1039. backup_task = asyncio.ensure_future(backup.backup_do())
  1040. self.app.api_admin_running_backups[self.arg] = backup_task
  1041. try:
  1042. yield from backup_task
  1043. except asyncio.CancelledError:
  1044. raise qubes.exc.QubesException('Backup cancelled')
  1045. finally:
  1046. del self.app.api_admin_running_backups[self.arg]
  1047. @qubes.api.method('admin.backup.Cancel', no_payload=True,
  1048. scope='global', execute=True)
  1049. @asyncio.coroutine
  1050. def backup_cancel(self):
  1051. assert self.dest.name == 'dom0'
  1052. assert self.arg
  1053. assert '/' not in self.arg
  1054. self.fire_event_for_permission()
  1055. if not hasattr(self.app, 'api_admin_running_backups'):
  1056. self.app.api_admin_running_backups = {}
  1057. if self.arg not in self.app.api_admin_running_backups:
  1058. raise qubes.exc.QubesException('Backup operation not running')
  1059. self.app.api_admin_running_backups[self.arg].cancel()
  1060. @qubes.api.method('admin.backup.Info', no_payload=True,
  1061. scope='local', read=True)
  1062. @asyncio.coroutine
  1063. def backup_info(self):
  1064. assert self.dest.name == 'dom0'
  1065. assert self.arg
  1066. assert '/' not in self.arg
  1067. self.fire_event_for_permission()
  1068. profile_path = os.path.join(qubes.config.backup_profile_dir,
  1069. self.arg + '.conf')
  1070. if not os.path.exists(profile_path):
  1071. raise qubes.api.PermissionDenied(
  1072. 'Backup profile {} does not exist'.format(self.arg))
  1073. backup = yield from self._load_backup_profile(self.arg,
  1074. skip_passphrase=True)
  1075. return backup.get_backup_summary()
  1076. def _send_stats_single(self, info_time, info, only_vm, filters,
  1077. id_to_name_map):
  1078. '''A single iteration of sending VM stats
  1079. :param info_time: time of previous iteration
  1080. :param info: information retrieved in previous iteration
  1081. :param only_vm: send information only about this VM
  1082. :param filters: filters to apply on stats before sending
  1083. :param id_to_name_map: ID->VM name map, may be modified
  1084. :return: tuple(info_time, info) - new information (to be passed to
  1085. the next iteration)
  1086. '''
  1087. (info_time, info) = self.app.host.get_vm_stats(info_time, info,
  1088. only_vm=only_vm)
  1089. for vm_id, vm_info in info.items():
  1090. if vm_id not in id_to_name_map:
  1091. try:
  1092. name = \
  1093. self.app.vmm.libvirt_conn.lookupByID(vm_id).name()
  1094. except libvirt.libvirtError as err:
  1095. if err.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  1096. # stubdomain or so
  1097. name = None
  1098. else:
  1099. raise
  1100. id_to_name_map[vm_id] = name
  1101. else:
  1102. name = id_to_name_map[vm_id]
  1103. # skip VMs with unknown name
  1104. if name is None:
  1105. continue
  1106. if not list(qubes.api.apply_filters([name], filters)):
  1107. continue
  1108. self.send_event(name, 'vm-stats',
  1109. memory_kb=int(vm_info['memory_kb']),
  1110. cpu_time=int(vm_info['cpu_time'] / 1000000),
  1111. cpu_usage=int(vm_info['cpu_usage']))
  1112. return info_time, info
  1113. @qubes.api.method('admin.vm.Stats', no_payload=True,
  1114. scope='global', read=True)
  1115. @asyncio.coroutine
  1116. def vm_stats(self):
  1117. assert not self.arg
  1118. # run until client connection is terminated
  1119. self.cancellable = True
  1120. # cache event filters, to not call an event each time an event arrives
  1121. stats_filters = self.fire_event_for_permission()
  1122. only_vm = None
  1123. if self.dest.name != 'dom0':
  1124. only_vm = self.dest
  1125. self.send_event(self.app, 'connection-established')
  1126. info_time = None
  1127. info = None
  1128. id_to_name_map = {0: 'dom0'}
  1129. try:
  1130. while True:
  1131. info_time, info = self._send_stats_single(info_time, info,
  1132. only_vm, stats_filters, id_to_name_map)
  1133. yield from asyncio.sleep(self.app.stats_interval)
  1134. except asyncio.CancelledError:
  1135. # valid method to terminate this loop
  1136. pass