qubesutils.py 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372
  1. #!/usr/bin/python
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2011 Marek Marczykowski <marmarek@invisiblethingslab.com>
  6. #
  7. # This program is free software; you can redistribute it and/or
  8. # modify it under the terms of the GNU General Public License
  9. # as published by the Free Software Foundation; either version 2
  10. # of the License, or (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program; if not, write to the Free Software
  19. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  20. #
  21. #
  22. from qubes import QubesVm,QubesException,QubesVmCollection
  23. from qubes import QubesVmClasses
  24. from qubes import xs, xl_ctx
  25. from qubes import system_path,vm_files
  26. import sys
  27. import os
  28. import subprocess
  29. import re
  30. import time
  31. import grp,pwd
  32. from datetime import datetime
  33. from qmemman_client import QMemmanClient
  34. import xen.lowlevel.xc
  35. import xen.lowlevel.xl
  36. import xen.lowlevel.xs
  37. def mbytes_to_kmg(size):
  38. if size > 1024:
  39. return "%d GiB" % (size/1024)
  40. else:
  41. return "%d MiB" % size
  42. def kbytes_to_kmg(size):
  43. if size > 1024:
  44. return mbytes_to_kmg(size/1024)
  45. else:
  46. return "%d KiB" % size
  47. def bytes_to_kmg(size):
  48. if size > 1024:
  49. return kbytes_to_kmg(size/1024)
  50. else:
  51. return "%d B" % size
  52. def size_to_human (size):
  53. """Humane readable size, with 1/10 precission"""
  54. if size < 1024:
  55. return str (size);
  56. elif size < 1024*1024:
  57. return str(round(size/1024.0,1)) + ' KiB'
  58. elif size < 1024*1024*1024:
  59. return str(round(size/(1024.0*1024),1)) + ' MiB'
  60. else:
  61. return str(round(size/(1024.0*1024*1024),1)) + ' GiB'
  62. def parse_size(size):
  63. units = [ ('K', 1024), ('KB', 1024),
  64. ('M', 1024*1024), ('MB', 1024*1024),
  65. ('G', 1024*1024*1024), ('GB', 1024*1024*1024),
  66. ]
  67. size = size.strip().upper()
  68. if size.isdigit():
  69. return int(size)
  70. for unit, multiplier in units:
  71. if size.endswith(unit):
  72. size = size[:-len(unit)].strip()
  73. return int(size)*multiplier
  74. raise QubesException("Invalid size: {0}.".format(size))
  75. def print_stdout(text):
  76. print (text)
  77. def print_stderr(text):
  78. print >> sys.stderr, (text)
  79. ###### Block devices ########
  80. def block_devid_to_name(devid):
  81. major = devid / 256
  82. minor = devid % 256
  83. dev_class = ""
  84. if major == 202:
  85. dev_class = "xvd"
  86. elif major == 8:
  87. dev_class = "sd"
  88. else:
  89. raise QubesException("Unknown device class %d" % major)
  90. if minor % 16 == 0:
  91. return "%s%c" % (dev_class, ord('a')+minor/16)
  92. else:
  93. return "%s%c%d" % (dev_class, ord('a')+minor/16, minor%16)
  94. def block_name_to_majorminor(name):
  95. # check if it is already devid
  96. if isinstance(name, int):
  97. return (name / 256, name % 256)
  98. if name.isdigit():
  99. return (int(name) / 256, int(name) % 256)
  100. major = 0
  101. minor = 0
  102. dXpY_style = False
  103. disk = True
  104. if name.startswith("xvd"):
  105. major = 202
  106. elif name.startswith("sd"):
  107. major = 8
  108. elif name.startswith("mmcblk"):
  109. dXpY_style = True
  110. major = 179
  111. elif name.startswith("scd"):
  112. disk = False
  113. major = 11
  114. elif name.startswith("sr"):
  115. disk = False
  116. major = 11
  117. elif name.startswith("loop"):
  118. disk = False
  119. major = 7
  120. elif name.startswith("md"):
  121. disk = False
  122. major = 9
  123. else:
  124. # Unknown device
  125. return (0, 0)
  126. if not dXpY_style:
  127. name_match = re.match(r"^([a-z]+)([a-z])([0-9]*)$", name)
  128. else:
  129. name_match = re.match(r"^([a-z]+)([0-9]*)(?:p([0-9]+))?$", name)
  130. if not name_match:
  131. raise QubesException("Invalid device name: %s" % name)
  132. if disk:
  133. if dXpY_style:
  134. minor = int(name_match.group(2))*8
  135. else:
  136. minor = (ord(name_match.group(2))-ord('a')) * 16
  137. else:
  138. minor = 0
  139. if name_match.group(3):
  140. minor += int(name_match.group(3))
  141. return (major, minor)
  142. def block_name_to_devid(name):
  143. # check if it is already devid
  144. if isinstance(name, int):
  145. return name
  146. if name.isdigit():
  147. return int(name)
  148. (major, minor) = block_name_to_majorminor(name)
  149. return major << 8 | minor
  150. def block_find_unused_frontend(vm = None):
  151. assert vm is not None
  152. assert vm.is_running()
  153. vbd_list = xs.ls('', '/local/domain/%d/device/vbd' % vm.xid)
  154. # xvd* devices
  155. major = 202
  156. # prefer xvdi
  157. for minor in range(8*16,254,16)+range(0,8*16,16):
  158. if vbd_list is None or str(major << 8 | minor) not in vbd_list:
  159. return block_devid_to_name(major << 8 | minor)
  160. return None
  161. def block_list(vm = None, system_disks = False):
  162. device_re = re.compile(r"^[a-z0-9]{1,12}$")
  163. # FIXME: any better idea of desc_re?
  164. desc_re = re.compile(r"^.{1,255}$")
  165. mode_re = re.compile(r"^[rw]$")
  166. xs_trans = xs.transaction_start()
  167. vm_list = []
  168. if vm is not None:
  169. if not vm.is_running():
  170. xs.transaction_end(xs_trans)
  171. return []
  172. else:
  173. vm_list = [ str(vm.xid) ]
  174. else:
  175. vm_list = xs.ls(xs_trans, '/local/domain')
  176. devices_list = {}
  177. for xid in vm_list:
  178. vm_name = xs.read(xs_trans, '/local/domain/%s/name' % xid)
  179. vm_devices = xs.ls(xs_trans, '/local/domain/%s/qubes-block-devices' % xid)
  180. if vm_devices is None:
  181. continue
  182. for device in vm_devices:
  183. # Sanitize device name
  184. if not device_re.match(device):
  185. print >> sys.stderr, "Invalid device name in VM '%s'" % vm_name
  186. continue
  187. device_size = xs.read(xs_trans, '/local/domain/%s/qubes-block-devices/%s/size' % (xid, device))
  188. device_desc = xs.read(xs_trans, '/local/domain/%s/qubes-block-devices/%s/desc' % (xid, device))
  189. device_mode = xs.read(xs_trans, '/local/domain/%s/qubes-block-devices/%s/mode' % (xid, device))
  190. if device_size is None or device_desc is None or device_mode is None:
  191. print >> sys.stderr, "Missing field in %s device parameters" % device
  192. continue
  193. if not device_size.isdigit():
  194. print >> sys.stderr, "Invalid %s device size in VM '%s'" % (device, vm_name)
  195. continue
  196. if not desc_re.match(device_desc):
  197. print >> sys.stderr, "Invalid %s device desc in VM '%s'" % (device, vm_name)
  198. continue
  199. if not mode_re.match(device_mode):
  200. print >> sys.stderr, "Invalid %s device mode in VM '%s'" % (device, vm_name)
  201. continue
  202. # Check if we know major number for this device; attach will work without this, but detach and check_attached don't
  203. if block_name_to_majorminor(device) == (0, 0):
  204. print >> sys.stderr, "Unsupported device %s:%s" % (vm_name, device)
  205. continue
  206. if not system_disks:
  207. if xid == '0' and device_desc.startswith(system_path["qubes_base_dir"]):
  208. continue
  209. visible_name = "%s:%s" % (vm_name, device)
  210. devices_list[visible_name] = {"name": visible_name, "xid":int(xid),
  211. "vm": vm_name, "device":device, "size":int(device_size),
  212. "desc":device_desc, "mode":device_mode}
  213. xs.transaction_end(xs_trans)
  214. return devices_list
  215. def block_check_attached(backend_vm, device, backend_xid = None):
  216. if backend_xid is None:
  217. backend_xid = backend_vm.xid
  218. xs_trans = xs.transaction_start()
  219. vm_list = xs.ls(xs_trans, '/local/domain/%d/backend/vbd' % backend_xid)
  220. if vm_list is None:
  221. xs.transaction_end(xs_trans)
  222. return None
  223. device_majorminor = None
  224. try:
  225. device_majorminor = block_name_to_majorminor(device)
  226. except:
  227. # Unknown devices will be compared directly - perhaps it is a filename?
  228. pass
  229. for vm_xid in vm_list:
  230. for devid in xs.ls(xs_trans, '/local/domain/%d/backend/vbd/%s' % (backend_xid, vm_xid)):
  231. (tmp_major, tmp_minor) = (0, 0)
  232. phys_device = xs.read(xs_trans, '/local/domain/%d/backend/vbd/%s/%s/physical-device' % (backend_xid, vm_xid, devid))
  233. dev_params = xs.read(xs_trans, '/local/domain/%d/backend/vbd/%s/%s/params' % (backend_xid, vm_xid, devid))
  234. if phys_device and phys_device.find(':'):
  235. (tmp_major, tmp_minor) = phys_device.split(":")
  236. tmp_major = int(tmp_major, 16)
  237. tmp_minor = int(tmp_minor, 16)
  238. else:
  239. # perhaps not ready yet - check params
  240. if not dev_params:
  241. # Skip not-phy devices
  242. continue
  243. elif not dev_params.startswith('/dev/'):
  244. # will compare params directly
  245. pass
  246. else:
  247. (tmp_major, tmp_minor) = block_name_to_majorminor(dev_params.lstrip('/dev/'))
  248. if (device_majorminor and (tmp_major, tmp_minor) == device_majorminor) or \
  249. (device_majorminor is None and dev_params == device):
  250. vm_name = xl_ctx.domid_to_name(int(vm_xid))
  251. frontend = block_devid_to_name(int(devid))
  252. xs.transaction_end(xs_trans)
  253. return {"xid":int(vm_xid), "frontend": frontend, "devid": int(devid), "vm": vm_name}
  254. xs.transaction_end(xs_trans)
  255. return None
  256. def block_attach(vm, backend_vm, device, frontend=None, mode="w", auto_detach=False, wait=True):
  257. device_attach_check(vm, backend_vm, device, frontend)
  258. do_block_attach(vm, backend_vm, device, frontend, mode, auto_detach, wait)
  259. def device_attach_check(vm, backend_vm, device, frontend):
  260. """ Checks all the parameters, dies on errors """
  261. if not vm.is_running():
  262. raise QubesException("VM %s not running" % vm.name)
  263. if not backend_vm.is_running():
  264. raise QubesException("VM %s not running" % backend_vm.name)
  265. def do_block_attach(vm, backend_vm, device, frontend, mode, auto_detach, wait):
  266. if frontend is None:
  267. frontend = block_find_unused_frontend(vm)
  268. if frontend is None:
  269. raise QubesException("No unused frontend found")
  270. else:
  271. # Check if any device attached at this frontend
  272. if xs.read('', '/local/domain/%d/device/vbd/%d/state' % (vm.xid, block_name_to_devid(frontend))) == '4':
  273. raise QubesException("Frontend %s busy in VM %s, detach it first" % (frontend, vm.name))
  274. # Check if this device is attached to some domain
  275. attached_vm = block_check_attached(backend_vm, device)
  276. if attached_vm:
  277. if auto_detach:
  278. block_detach(None, attached_vm['devid'], vm_xid=attached_vm['xid'])
  279. else:
  280. raise QubesException("Device %s from %s already connected to VM %s as %s" % (device, backend_vm.name, attached_vm['vm'], attached_vm['frontend']))
  281. if device.startswith('/'):
  282. backend_dev = 'script:file:' + device
  283. else:
  284. backend_dev = 'phy:/dev/' + device
  285. xl_cmd = [ '/usr/sbin/xl', 'block-attach', vm.name, backend_dev, frontend, mode, str(backend_vm.xid) ]
  286. subprocess.check_call(xl_cmd)
  287. if wait:
  288. be_path = '/local/domain/%d/backend/vbd/%d/%d' % (backend_vm.xid, vm.xid, block_name_to_devid(frontend))
  289. # There is no way to use xenstore watch with a timeout, so must check in a loop
  290. interval = 0.100
  291. # 5sec timeout
  292. timeout = 5/interval
  293. while timeout > 0:
  294. be_state = xs.read('', be_path + '/state')
  295. hotplug_state = xs.read('', be_path + '/hotplug-status')
  296. if be_state is None:
  297. raise QubesException("Backend device disappeared, something weird happened")
  298. elif int(be_state) == 4:
  299. # Ok
  300. return
  301. elif int(be_state) > 4:
  302. # Error
  303. error = xs.read('', '/local/domain/%d/error/backend/vbd/%d/%d/error' % (backend_vm.xid, vm.xid, block_name_to_devid(frontend)))
  304. if error is not None:
  305. raise QubesException("Error while connecting block device: " + error)
  306. else:
  307. raise QubesException("Unknown error while connecting block device")
  308. elif hotplug_state == 'error':
  309. hotplug_error = xs.read('', be_path + '/hotplug-error')
  310. if hotplug_error:
  311. raise QubesException("Error while connecting block device: " + hotplug_error)
  312. else:
  313. raise QubesException("Unknown hotplug error while connecting block device")
  314. time.sleep(interval)
  315. timeout -= interval
  316. raise QubesException("Timeout while waiting for block defice connection")
  317. def block_detach(vm, frontend = "xvdi", vm_xid = None):
  318. # Get XID if not provided already
  319. if vm_xid is None:
  320. if not vm.is_running():
  321. raise QubesException("VM %s not running" % vm.name)
  322. # FIXME: potential race
  323. vm_xid = vm.xid
  324. # Check if this device is really connected
  325. if not xs.read('', '/local/domain/%d/device/vbd/%d/state' % (vm_xid, block_name_to_devid(frontend))) == '4':
  326. # Do nothing - device already detached
  327. return
  328. xl_cmd = [ '/usr/sbin/xl', 'block-detach', str(vm_xid), str(frontend)]
  329. subprocess.check_call(xl_cmd)
  330. def block_detach_all(vm, vm_xid = None):
  331. """ Detach all non-system devices"""
  332. # Get XID if not provided already
  333. if vm_xid is None:
  334. if not vm.is_running():
  335. raise QubesException("VM %s not running" % vm.name)
  336. # FIXME: potential race
  337. vm_xid = vm.xid
  338. xs_trans = xs.transaction_start()
  339. devices = xs.ls(xs_trans, '/local/domain/%d/device/vbd' % vm_xid)
  340. if devices is None:
  341. return
  342. devices_to_detach = []
  343. for devid in devices:
  344. # check if this is system disk
  345. be_path = xs.read(xs_trans, '/local/domain/%d/device/vbd/%s/backend' % (vm_xid, devid))
  346. assert be_path is not None
  347. be_params = xs.read(xs_trans, be_path + '/params')
  348. if be_path.startswith('/local/domain/0/') and be_params is not None and be_params.startswith(system_path["qubes_base_dir"]):
  349. # system disk
  350. continue
  351. devices_to_detach.append(devid)
  352. xs.transaction_end(xs_trans)
  353. for devid in devices_to_detach:
  354. xl_cmd = [ '/usr/sbin/xl', 'block-detach', str(vm_xid), devid]
  355. subprocess.check_call(xl_cmd)
  356. ####### USB devices ######
  357. usb_ver_re = re.compile(r"^(1|2)$")
  358. usb_device_re = re.compile(r"^[0-9]+-[0-9]+(_[0-9]+)?$")
  359. usb_port_re = re.compile(r"^$|^[0-9]+-[0-9]+(\.[0-9]+)?$")
  360. def usb_setup(backend_vm_xid, vm_xid, devid, usb_ver):
  361. """
  362. Attach frontend to the backend.
  363. backend_vm_xid - id of the backend domain
  364. vm_xid - id of the frontend domain
  365. devid - id of the pvusb controller
  366. """
  367. num_ports = 8
  368. trans = xs.transaction_start()
  369. be_path = "/local/domain/%d/backend/vusb/%d/%d" % (backend_vm_xid, vm_xid, devid)
  370. fe_path = "/local/domain/%d/device/vusb/%d" % (vm_xid, devid)
  371. be_perm = [{'dom': backend_vm_xid}, {'dom': vm_xid, 'read': True} ]
  372. fe_perm = [{'dom': vm_xid}, {'dom': backend_vm_xid, 'read': True} ]
  373. # Create directories and set permissions
  374. xs.write(trans, be_path, "")
  375. xs.set_permissions(trans, be_path, be_perm)
  376. xs.write(trans, fe_path, "")
  377. xs.set_permissions(trans, fe_path, fe_perm)
  378. # Write backend information into the location that frontend looks for
  379. xs.write(trans, "%s/backend-id" % fe_path, str(backend_vm_xid))
  380. xs.write(trans, "%s/backend" % fe_path, be_path)
  381. # Write frontend information into the location that backend looks for
  382. xs.write(trans, "%s/frontend-id" % be_path, str(vm_xid))
  383. xs.write(trans, "%s/frontend" % be_path, fe_path)
  384. # Write USB Spec version field.
  385. xs.write(trans, "%s/usb-ver" % be_path, usb_ver)
  386. # Write virtual root hub field.
  387. xs.write(trans, "%s/num-ports" % be_path, str(num_ports))
  388. for port in range(1, num_ports+1):
  389. # Set all port to disconnected state
  390. xs.write(trans, "%s/port/%d" % (be_path, port), "")
  391. # Set state to XenbusStateInitialising
  392. xs.write(trans, "%s/state" % fe_path, "1")
  393. xs.write(trans, "%s/state" % be_path, "1")
  394. xs.write(trans, "%s/online" % be_path, "1")
  395. xs.transaction_end(trans)
  396. def usb_decode_device_from_xs(xs_encoded_device):
  397. """ recover actual device name (xenstore doesn't allow dot in key names, so it was translated to underscore) """
  398. return xs_encoded_device.replace('_', '.')
  399. def usb_encode_device_for_xs(device):
  400. """ encode actual device name (xenstore doesn't allow dot in key names, so translated it into underscore) """
  401. return device.replace('.', '_')
  402. def usb_list():
  403. """
  404. Returns a dictionary of USB devices (for PVUSB backends running in all VM).
  405. The dictionary is keyed by 'name' (see below), each element is a dictionary itself:
  406. vm = name of the backend domain
  407. xid = xid of the backend domain
  408. device = <frontend device number>-<frontend port number>
  409. name = <name of backend domain>:<frontend device number>-<frontend port number>
  410. desc = description
  411. """
  412. # FIXME: any better idea of desc_re?
  413. desc_re = re.compile(r"^.{1,255}$")
  414. devices_list = {}
  415. xs_trans = xs.transaction_start()
  416. vm_list = xs.ls(xs_trans, '/local/domain')
  417. for xid in vm_list:
  418. vm_name = xs.read(xs_trans, '/local/domain/%s/name' % xid)
  419. vm_devices = xs.ls(xs_trans, '/local/domain/%s/qubes-usb-devices' % xid)
  420. if vm_devices is None:
  421. continue
  422. # when listing devices in xenstore we get encoded names
  423. for xs_encoded_device in vm_devices:
  424. # Sanitize device id
  425. if not usb_device_re.match(xs_encoded_device):
  426. print >> sys.stderr, "Invalid device id in backend VM '%s'" % vm_name
  427. continue
  428. device = usb_decode_device_from_xs(xs_encoded_device)
  429. device_desc = xs.read(xs_trans, '/local/domain/%s/qubes-usb-devices/%s/desc' % (xid, xs_encoded_device))
  430. if not desc_re.match(device_desc):
  431. print >> sys.stderr, "Invalid %s device desc in VM '%s'" % (device, vm_name)
  432. continue
  433. visible_name = "%s:%s" % (vm_name, device)
  434. # grab version
  435. usb_ver = xs.read(xs_trans, '/local/domain/%s/qubes-usb-devices/%s/usb-ver' % (xid, xs_encoded_device))
  436. if usb_ver is None or not usb_ver_re.match(usb_ver):
  437. print >> sys.stderr, "Invalid %s device USB version in VM '%s'" % (device, vm_name)
  438. continue
  439. devices_list[visible_name] = {"name": visible_name, "xid":int(xid),
  440. "vm": vm_name, "device":device,
  441. "desc":device_desc,
  442. "usb_ver":usb_ver}
  443. xs.transaction_end(xs_trans)
  444. return devices_list
  445. def usb_check_attached(xs_trans, backend_vm, device):
  446. """
  447. Checks if the given device in the given backend attached to any frontend.
  448. Parameters:
  449. backend_vm - xid of the backend domain
  450. device - device name in the backend domain
  451. Returns None or a dictionary:
  452. vm - the name of the frontend domain
  453. xid - xid of the frontend domain
  454. frontend - frontend device number FIXME
  455. devid - frontend port number FIXME
  456. """
  457. # sample xs content: /local/domain/0/backend/vusb/4/0/port/1 = "7-5"
  458. attached_dev = None
  459. vms = xs.ls(xs_trans, '/local/domain/%d/backend/vusb' % backend_vm)
  460. if vms is None:
  461. return None
  462. for vm in vms:
  463. if not vm.isdigit():
  464. print >> sys.stderr, "Invalid VM id"
  465. continue
  466. frontend_devs = xs.ls(xs_trans, '/local/domain/%d/backend/vusb/%s' % (backend_vm, vm))
  467. if frontend_devs is None:
  468. continue
  469. for frontend_dev in frontend_devs:
  470. if not frontend_dev.isdigit():
  471. print >> sys.stderr, "Invalid frontend in VM %s" % vm
  472. continue
  473. ports = xs.ls(xs_trans, '/local/domain/%d/backend/vusb/%s/%s/port' % (backend_vm, vm, frontend_dev))
  474. if ports is None:
  475. continue
  476. for port in ports:
  477. # FIXME: refactor, see similar loop in usb_find_unused_frontend(), use usb_list() instead?
  478. if not port.isdigit():
  479. print >> sys.stderr, "Invalid port in VM %s frontend %s" % (vm, frontend)
  480. continue
  481. dev = xs.read(xs_trans, '/local/domain/%d/backend/vusb/%s/%s/port/%s' % (backend_vm, vm, frontend_dev, port))
  482. if dev == "":
  483. continue
  484. # Sanitize device id
  485. if not usb_port_re.match(dev):
  486. print >> sys.stderr, "Invalid device id in backend VM %d @ %s/%s/port/%s" % \
  487. (backend_vm, vm, frontend_dev, port)
  488. continue
  489. if dev == device:
  490. frontend = "%s-%s" % (frontend_dev, port)
  491. vm_name = xl_ctx.domid_to_name(int(vm))
  492. if vm_name is None:
  493. # FIXME: should we wipe references to frontends running on nonexistent VMs?
  494. continue
  495. attached_dev = {"xid":int(vm), "frontend": frontend, "devid": device, "vm": vm_name}
  496. break
  497. return attached_dev
  498. #def usb_check_frontend_busy(vm, front_dev, port):
  499. # devport = frontend.split("-")
  500. # if len(devport) != 2:
  501. # raise QubesException("Malformed frontend syntax, must be in device-port format")
  502. # # FIXME:
  503. # # return xs.read('', '/local/domain/%d/device/vusb/%d/state' % (vm.xid, frontend)) == '4'
  504. # return False
  505. def usb_find_unused_frontend(xs_trans, backend_vm_xid, vm_xid, usb_ver):
  506. """
  507. Find an unused frontend/port to link the given backend with the given frontend.
  508. Creates new frontend if needed.
  509. Returns frontend specification in <device>-<port> format.
  510. """
  511. # This variable holds an index of last frontend scanned by the loop below.
  512. # If nothing found, this value will be used to derive the index of a new frontend.
  513. last_frontend_dev = -1
  514. frontend_devs = xs.ls(xs_trans, "/local/domain/%d/device/vusb" % vm_xid)
  515. if frontend_devs is not None:
  516. for frontend_dev in frontend_devs:
  517. if not frontend_dev.isdigit():
  518. print >> sys.stderr, "Invalid frontend_dev in VM %d" % vm_xid
  519. continue
  520. frontend_dev = int(frontend_dev)
  521. fe_path = "/local/domain/%d/device/vusb/%d" % (vm_xid, frontend_dev)
  522. if xs.read(xs_trans, "%s/backend-id" % fe_path) == str(backend_vm_xid):
  523. if xs.read(xs_trans, '/local/domain/%d/backend/vusb/%d/%d/usb-ver' % (backend_vm_xid, vm_xid, frontend_dev)) != usb_ver:
  524. last_frontend_dev = frontend_dev
  525. continue
  526. # here: found an existing frontend already connected to right backend using an appropriate USB version
  527. ports = xs.ls(xs_trans, '/local/domain/%d/backend/vusb/%d/%d/port' % (backend_vm_xid, vm_xid, frontend_dev))
  528. if ports is None:
  529. print >> sys.stderr, "No ports in VM %d frontend_dev %d?" % (vm_xid, frontend_dev)
  530. last_frontend_dev = frontend_dev
  531. continue
  532. for port in ports:
  533. # FIXME: refactor, see similar loop in usb_check_attached(), use usb_list() instead?
  534. if not port.isdigit():
  535. print >> sys.stderr, "Invalid port in VM %d frontend_dev %d" % (vm_xid, frontend_dev)
  536. continue
  537. port = int(port)
  538. dev = xs.read(xs_trans, '/local/domain/%d/backend/vusb/%d/%s/port/%s' % (backend_vm_xid, vm_xid, frontend_dev, port))
  539. # Sanitize device id
  540. if not usb_port_re.match(dev):
  541. print >> sys.stderr, "Invalid device id in backend VM %d @ %d/%d/port/%d" % \
  542. (backend_vm_xid, vm_xid, frontend_dev, port)
  543. continue
  544. if dev == "":
  545. return '%d-%d' % (frontend_dev, port)
  546. last_frontend_dev = frontend_dev
  547. # create a new frontend_dev and link it to the backend
  548. frontend_dev = last_frontend_dev + 1
  549. usb_setup(backend_vm_xid, vm_xid, frontend_dev, usb_ver)
  550. return '%d-%d' % (frontend_dev, 1)
  551. def usb_attach(vm, backend_vm, device, frontend=None, auto_detach=False, wait=True):
  552. device_attach_check(vm, backend_vm, device, frontend)
  553. xs_trans = xs.transaction_start()
  554. xs_encoded_device = usb_encode_device_for_xs(device)
  555. usb_ver = xs.read(xs_trans, '/local/domain/%s/qubes-usb-devices/%s/usb-ver' % (backend_vm.xid, xs_encoded_device))
  556. if usb_ver is None or not usb_ver_re.match(usb_ver):
  557. xs.transaction_end(xs_trans)
  558. raise QubesException("Invalid %s device USB version in VM '%s'" % (device, backend_vm.name))
  559. if frontend is None:
  560. frontend = usb_find_unused_frontend(xs_trans, backend_vm.xid, vm.xid, usb_ver)
  561. else:
  562. # Check if any device attached at this frontend
  563. #if usb_check_frontend_busy(vm, frontend):
  564. # raise QubesException("Frontend %s busy in VM %s, detach it first" % (frontend, vm.name))
  565. xs.transaction_end(xs_trans)
  566. raise NotImplementedError("Explicit USB frontend specification is not implemented yet")
  567. # Check if this device is attached to some domain
  568. attached_vm = usb_check_attached(xs_trans, backend_vm.xid, device)
  569. xs.transaction_end(xs_trans)
  570. if attached_vm:
  571. if auto_detach:
  572. usb_detach(backend_vm, attached_vm)
  573. else:
  574. raise QubesException("Device %s from %s already connected to VM %s as %s" % (device, backend_vm.name, attached_vm['vm'], attached_vm['frontend']))
  575. # Run helper script
  576. xl_cmd = [ '/usr/lib/qubes/xl-qvm-usb-attach.py', str(vm.xid), device, frontend, str(backend_vm.xid) ]
  577. subprocess.check_call(xl_cmd)
  578. def usb_detach(backend_vm, attachment):
  579. xl_cmd = [ '/usr/lib/qubes/xl-qvm-usb-detach.py', str(attachment['xid']), attachment['devid'], attachment['frontend'], str(backend_vm.xid) ]
  580. subprocess.check_call(xl_cmd)
  581. def usb_detach_all(vm):
  582. raise NotImplementedError("Detaching all devices from a given VM is not implemented yet")
  583. ####### QubesWatch ######
  584. def only_in_first_list(l1, l2):
  585. ret=[]
  586. for i in l1:
  587. if not i in l2:
  588. ret.append(i)
  589. return ret
  590. class QubesWatch(object):
  591. class WatchType(object):
  592. def __init__(self, fn, param):
  593. self.fn = fn
  594. self.param = param
  595. def __init__(self):
  596. self.xs = xen.lowlevel.xs.xs()
  597. self.watch_tokens_block = {}
  598. self.watch_tokens_vbd = {}
  599. self.block_callback = None
  600. self.domain_callback = None
  601. self.xs.watch('@introduceDomain', QubesWatch.WatchType(self.domain_list_changed, None))
  602. self.xs.watch('@releaseDomain', QubesWatch.WatchType(self.domain_list_changed, None))
  603. def setup_block_watch(self, callback):
  604. old_block_callback = self.block_callback
  605. self.block_callback = callback
  606. if old_block_callback is not None and callback is None:
  607. # remove watches
  608. self.update_watches_vbd([])
  609. self.update_watches_block([])
  610. else:
  611. # possibly add watches
  612. self.domain_list_changed(None)
  613. def setup_domain_watch(self, callback):
  614. self.domain_callback = callback
  615. def get_block_key(self, xid):
  616. return '/local/domain/%s/qubes-block-devices' % xid
  617. def get_vbd_key(self, xid):
  618. return '/local/domain/%s/device/vbd' % xid
  619. def update_watches_block(self, xid_list):
  620. for i in only_in_first_list(xid_list, self.watch_tokens_block.keys()):
  621. #new domain has been created
  622. watch = QubesWatch.WatchType(self.block_callback, i)
  623. self.watch_tokens_block[i] = watch
  624. self.xs.watch(self.get_block_key(i), watch)
  625. for i in only_in_first_list(self.watch_tokens_block.keys(), xid_list):
  626. #domain destroyed
  627. self.xs.unwatch(self.get_block_key(i), self.watch_tokens_block[i])
  628. self.watch_tokens_block.pop(i)
  629. def update_watches_vbd(self, xid_list):
  630. for i in only_in_first_list(xid_list, self.watch_tokens_vbd.keys()):
  631. #new domain has been created
  632. watch = QubesWatch.WatchType(self.block_callback, i)
  633. self.watch_tokens_vbd[i] = watch
  634. self.xs.watch(self.get_vbd_key(i), watch)
  635. for i in only_in_first_list(self.watch_tokens_vbd.keys(), xid_list):
  636. #domain destroyed
  637. self.xs.unwatch(self.get_vbd_key(i), self.watch_tokens_vbd[i])
  638. self.watch_tokens_vbd.pop(i)
  639. def domain_list_changed(self, param):
  640. curr = self.xs.ls('', '/local/domain')
  641. if curr == None:
  642. return
  643. if self.domain_callback:
  644. self.domain_callback()
  645. if self.block_callback:
  646. self.update_watches_block(curr)
  647. self.update_watches_vbd(curr)
  648. def watch_single(self):
  649. result = self.xs.read_watch()
  650. token = result[1]
  651. token.fn(token.param)
  652. def watch_loop(self):
  653. while True:
  654. self.watch_single()
  655. ######## Backups #########
  656. def get_disk_usage(file_or_dir):
  657. if not os.path.exists(file_or_dir):
  658. return 0
  659. p = subprocess.Popen (["du", "-s", "--block-size=1", file_or_dir],
  660. stdout=subprocess.PIPE)
  661. result = p.communicate()
  662. m = re.match(r"^(\d+)\s.*", result[0])
  663. sz = int(m.group(1)) if m is not None else 0
  664. return sz
  665. def file_to_backup (file_path, sz = None):
  666. if sz is None:
  667. sz = os.path.getsize (system_path["qubes_store_filename"])
  668. abs_file_path = os.path.abspath (file_path)
  669. abs_base_dir = os.path.abspath (system_path["qubes_base_dir"]) + '/'
  670. abs_file_dir = os.path.dirname (abs_file_path) + '/'
  671. (nothing, dir, subdir) = abs_file_dir.partition (abs_base_dir)
  672. assert nothing == ""
  673. assert dir == abs_base_dir
  674. return [ { "path" : file_path, "size": sz, "subdir": subdir} ]
  675. def backup_prepare(base_backup_dir, vms_list = None, exclude_list = [], print_callback = print_stdout):
  676. """If vms = None, include all (sensible) VMs; exclude_list is always applied"""
  677. if not os.path.exists (base_backup_dir):
  678. raise QubesException("The target directory doesn't exist!")
  679. files_to_backup = file_to_backup (system_path["qubes_store_filename"])
  680. if exclude_list is None:
  681. exclude_list = []
  682. if vms_list is None:
  683. qvm_collection = QubesVmCollection()
  684. qvm_collection.lock_db_for_reading()
  685. qvm_collection.load()
  686. # FIXME: should be after backup completed
  687. qvm_collection.unlock_db()
  688. all_vms = [vm for vm in qvm_collection.values()]
  689. selected_vms = [vm for vm in all_vms if vm.include_in_backups]
  690. appvms_to_backup = [vm for vm in selected_vms if vm.is_appvm() and not vm.internal]
  691. netvms_to_backup = [vm for vm in selected_vms if vm.is_netvm() and not vm.qid == 0]
  692. template_vms_worth_backingup = [vm for vm in selected_vms if (vm.is_template() and not vm.installed_by_rpm)]
  693. vms_list = appvms_to_backup + netvms_to_backup + template_vms_worth_backingup
  694. vms_for_backup = vms_list
  695. # Apply exclude list
  696. if exclude_list:
  697. vms_for_backup = [vm for vm in vms_list if vm.name not in exclude_list]
  698. no_vms = len (vms_for_backup)
  699. there_are_running_vms = False
  700. fields_to_display = [
  701. { "name": "VM", "width": 16},
  702. { "name": "type","width": 12 },
  703. { "name": "size", "width": 12}
  704. ]
  705. # Display the header
  706. s = ""
  707. for f in fields_to_display:
  708. fmt="{{0:-^{0}}}-+".format(f["width"] + 1)
  709. s += fmt.format('-')
  710. print_callback(s)
  711. s = ""
  712. for f in fields_to_display:
  713. fmt="{{0:>{0}}} |".format(f["width"] + 1)
  714. s += fmt.format(f["name"])
  715. print_callback(s)
  716. s = ""
  717. for f in fields_to_display:
  718. fmt="{{0:-^{0}}}-+".format(f["width"] + 1)
  719. s += fmt.format('-')
  720. print_callback(s)
  721. for vm in vms_for_backup:
  722. if vm.is_template():
  723. # handle templates later
  724. continue
  725. if vm.private_img is not None:
  726. vm_sz = vm.get_disk_usage (vm.private_img)
  727. files_to_backup += file_to_backup(vm.private_img, vm_sz )
  728. if vm.is_appvm():
  729. files_to_backup += file_to_backup(vm.icon_path)
  730. if vm.updateable:
  731. if os.path.exists(vm.dir_path + "/apps.templates"):
  732. # template
  733. files_to_backup += file_to_backup(vm.dir_path + "/apps.templates")
  734. else:
  735. # standaloneVM
  736. files_to_backup += file_to_backup(vm.dir_path + "/apps")
  737. if os.path.exists(vm.dir_path + "/kernels"):
  738. files_to_backup += file_to_backup(vm.dir_path + "/kernels")
  739. if os.path.exists (vm.firewall_conf):
  740. files_to_backup += file_to_backup(vm.firewall_conf)
  741. if 'appmenus_whitelist' in vm_files and \
  742. os.path.exists(vm.dir_path + vm_files['appmenus_whitelist']):
  743. files_to_backup += file_to_backup(vm.dir_path + vm_files['appmenus_whitelist'])
  744. if vm.updateable:
  745. sz = vm.get_disk_usage(vm.root_img)
  746. files_to_backup += file_to_backup(vm.root_img, sz)
  747. vm_sz += sz
  748. s = ""
  749. fmt="{{0:>{0}}} |".format(fields_to_display[0]["width"] + 1)
  750. s += fmt.format(vm.name)
  751. fmt="{{0:>{0}}} |".format(fields_to_display[1]["width"] + 1)
  752. if vm.is_netvm():
  753. s += fmt.format("NetVM" + (" + Sys" if vm.updateable else ""))
  754. else:
  755. s += fmt.format("AppVM" + (" + Sys" if vm.updateable else ""))
  756. fmt="{{0:>{0}}} |".format(fields_to_display[2]["width"] + 1)
  757. s += fmt.format(size_to_human(vm_sz))
  758. if vm.is_running():
  759. s += " <-- The VM is running, please shut it down before proceeding with the backup!"
  760. there_are_running_vms = True
  761. print_callback(s)
  762. for vm in vms_for_backup:
  763. if not vm.is_template():
  764. # already handled
  765. continue
  766. vm_sz = vm.get_disk_utilization()
  767. files_to_backup += file_to_backup (vm.dir_path, vm_sz)
  768. s = ""
  769. fmt="{{0:>{0}}} |".format(fields_to_display[0]["width"] + 1)
  770. s += fmt.format(vm.name)
  771. fmt="{{0:>{0}}} |".format(fields_to_display[1]["width"] + 1)
  772. s += fmt.format("Template VM")
  773. fmt="{{0:>{0}}} |".format(fields_to_display[2]["width"] + 1)
  774. s += fmt.format(size_to_human(vm_sz))
  775. if vm.is_running():
  776. s += " <-- The VM is running, please shut it down before proceeding with the backup!"
  777. there_are_running_vms = True
  778. print_callback(s)
  779. # Dom0 user home
  780. if not 'dom0' in exclude_list:
  781. local_user = grp.getgrnam('qubes').gr_mem[0]
  782. home_dir = pwd.getpwnam(local_user).pw_dir
  783. # Home dir should have only user-owned files, so fix it now to prevent
  784. # permissions problems - some root-owned files can left after
  785. # 'sudo bash' and similar commands
  786. subprocess.check_call(['sudo', 'chown', '-R', local_user, home_dir])
  787. home_sz = get_disk_usage(home_dir)
  788. home_to_backup = [ { "path" : home_dir, "size": home_sz, "subdir": 'dom0-home'} ]
  789. files_to_backup += home_to_backup
  790. s = ""
  791. fmt="{{0:>{0}}} |".format(fields_to_display[0]["width"] + 1)
  792. s += fmt.format('Dom0')
  793. fmt="{{0:>{0}}} |".format(fields_to_display[1]["width"] + 1)
  794. s += fmt.format("User home")
  795. fmt="{{0:>{0}}} |".format(fields_to_display[2]["width"] + 1)
  796. s += fmt.format(size_to_human(home_sz))
  797. print_callback(s)
  798. total_backup_sz = 0
  799. for file in files_to_backup:
  800. total_backup_sz += file["size"]
  801. s = ""
  802. for f in fields_to_display:
  803. fmt="{{0:-^{0}}}-+".format(f["width"] + 1)
  804. s += fmt.format('-')
  805. print_callback(s)
  806. s = ""
  807. fmt="{{0:>{0}}} |".format(fields_to_display[0]["width"] + 1)
  808. s += fmt.format("Total size:")
  809. fmt="{{0:>{0}}} |".format(fields_to_display[1]["width"] + 1 + 2 + fields_to_display[2]["width"] + 1)
  810. s += fmt.format(size_to_human(total_backup_sz))
  811. print_callback(s)
  812. s = ""
  813. for f in fields_to_display:
  814. fmt="{{0:-^{0}}}-+".format(f["width"] + 1)
  815. s += fmt.format('-')
  816. print_callback(s)
  817. stat = os.statvfs(base_backup_dir)
  818. backup_fs_free_sz = stat.f_bsize * stat.f_bavail
  819. print_callback("")
  820. if (total_backup_sz > backup_fs_free_sz):
  821. raise QubesException("Not enough space available on the backup filesystem!")
  822. if (there_are_running_vms):
  823. raise QubesException("Please shutdown all VMs before proceeding.")
  824. print_callback("-> Available space: {0}".format(size_to_human(backup_fs_free_sz)))
  825. return files_to_backup
  826. def backup_do(base_backup_dir, files_to_backup, progress_callback = None):
  827. total_backup_sz = 0
  828. for file in files_to_backup:
  829. total_backup_sz += file["size"]
  830. backup_dir = base_backup_dir + "/qubes-{0}".format (time.strftime("%Y-%m-%d-%H%M%S"))
  831. if os.path.exists (backup_dir):
  832. raise QubesException("ERROR: the path {0} already exists?!".format(backup_dir))
  833. os.mkdir (backup_dir)
  834. if not os.path.exists (backup_dir):
  835. raise QubesException("Strange: couldn't create backup dir: {0}?!".format(backup_dir))
  836. bytes_backedup = 0
  837. for file in files_to_backup:
  838. # We prefer to use Linux's cp, because it nicely handles sparse files
  839. progress = bytes_backedup * 100 / total_backup_sz
  840. progress_callback(progress)
  841. dest_dir = backup_dir + '/' + file["subdir"]
  842. if file["subdir"] != "":
  843. retcode = subprocess.call (["mkdir", "-p", dest_dir])
  844. if retcode != 0:
  845. raise QubesException("Cannot create directory: {0}?!".format(dest_dir))
  846. retcode = subprocess.call (["cp", "-rp", file["path"], dest_dir])
  847. if retcode != 0:
  848. raise QubesException("Error while copying file {0} to {1}".format(file["path"], dest_dir))
  849. bytes_backedup += file["size"]
  850. progress = bytes_backedup * 100 / total_backup_sz
  851. progress_callback(progress)
  852. def backup_restore_set_defaults(options):
  853. if 'use-default-netvm' not in options:
  854. options['use-default-netvm'] = False
  855. if 'use-none-netvm' not in options:
  856. options['use-none-netvm'] = False
  857. if 'use-default-template' not in options:
  858. options['use-default-template'] = False
  859. if 'dom0-home' not in options:
  860. options['dom0-home'] = True
  861. if 'replace-template' not in options:
  862. options['replace-template'] = []
  863. return options
  864. def backup_restore_prepare(backup_dir, options = {}, host_collection = None):
  865. # Defaults
  866. backup_restore_set_defaults(options)
  867. #### Private functions begin
  868. def is_vm_included_in_backup (backup_dir, vm):
  869. if vm.qid == 0:
  870. # Dom0 is not included, obviously
  871. return False
  872. backup_vm_dir_path = vm.dir_path.replace (system_path["qubes_base_dir"], backup_dir)
  873. if os.path.exists (backup_vm_dir_path):
  874. return True
  875. else:
  876. return False
  877. def find_template_name(template, replaces):
  878. rx_replace = re.compile("(.*):(.*)")
  879. for r in replaces:
  880. m = rx_replace.match(r)
  881. if m.group(1) == template:
  882. return m.group(2)
  883. return template
  884. #### Private functions end
  885. if not os.path.exists (backup_dir):
  886. raise QubesException("The backup directory doesn't exist!")
  887. backup_collection = QubesVmCollection(store_filename = backup_dir + "/qubes.xml")
  888. backup_collection.lock_db_for_reading()
  889. backup_collection.load()
  890. if host_collection is None:
  891. host_collection = QubesVmCollection()
  892. host_collection.lock_db_for_reading()
  893. host_collection.load()
  894. host_collection.unlock_db()
  895. backup_vms_list = [vm for vm in backup_collection.values()]
  896. host_vms_list = [vm for vm in host_collection.values()]
  897. vms_to_restore = {}
  898. there_are_conflicting_vms = False
  899. there_are_missing_templates = False
  900. there_are_missing_netvms = False
  901. dom0_username_mismatch = False
  902. restore_home = False
  903. # ... and the actual data
  904. for vm in backup_vms_list:
  905. if is_vm_included_in_backup (backup_dir, vm):
  906. vms_to_restore[vm.name] = {}
  907. vms_to_restore[vm.name]['vm'] = vm;
  908. if 'exclude' in options.keys():
  909. vms_to_restore[vm.name]['excluded'] = vm.name in options['exclude']
  910. vms_to_restore[vm.name]['good-to-go'] = False
  911. if host_collection.get_vm_by_name (vm.name) is not None:
  912. vms_to_restore[vm.name]['already-exists'] = True
  913. vms_to_restore[vm.name]['good-to-go'] = False
  914. if vm.template is None:
  915. vms_to_restore[vm.name]['template'] = None
  916. else:
  917. templatevm_name = find_template_name(vm.template.name, options['replace-template'])
  918. vms_to_restore[vm.name]['template'] = templatevm_name
  919. template_vm_on_host = host_collection.get_vm_by_name (templatevm_name)
  920. # No template on the host?
  921. if not ((template_vm_on_host is not None) and template_vm_on_host.is_template()):
  922. # Maybe the (custom) template is in the backup?
  923. template_vm_on_backup = backup_collection.get_vm_by_name (templatevm_name)
  924. if template_vm_on_backup is None or not \
  925. (is_vm_included_in_backup(backup_dir, template_vm_on_backup) and \
  926. template_vm_on_backup.is_template()):
  927. if options['use-default-template']:
  928. vms_to_restore[vm.name]['orig-template'] = templatevm_name
  929. vms_to_restore[vm.name]['template'] = host_collection.get_default_template().name
  930. else:
  931. vms_to_restore[vm.name]['missing-template'] = True
  932. vms_to_restore[vm.name]['good-to-go'] = False
  933. if vm.netvm is None:
  934. vms_to_restore[vm.name]['netvm'] = None
  935. else:
  936. netvm_name = vm.netvm.name
  937. vms_to_restore[vm.name]['netvm'] = netvm_name
  938. # Set to None to not confuse QubesVm object from backup
  939. # collection with host collection (further in clone_attrs). Set
  940. # directly _netvm to suppress setter action, especially
  941. # modifying firewall
  942. vm._netvm = None
  943. netvm_on_host = host_collection.get_vm_by_name (netvm_name)
  944. # No netvm on the host?
  945. if not ((netvm_on_host is not None) and netvm_on_host.is_netvm()):
  946. # Maybe the (custom) netvm is in the backup?
  947. netvm_on_backup = backup_collection.get_vm_by_name (netvm_name)
  948. if not ((netvm_on_backup is not None) and netvm_on_backup.is_netvm() and is_vm_included_in_backup(backup_dir, netvm_on_backup)):
  949. if options['use-default-netvm']:
  950. vms_to_restore[vm.name]['netvm'] = host_collection.get_default_netvm().name
  951. vm.uses_default_netvm = True
  952. elif options['use-none-netvm']:
  953. vms_to_restore[vm.name]['netvm'] = None
  954. else:
  955. vms_to_restore[vm.name]['missing-netvm'] = True
  956. vms_to_restore[vm.name]['good-to-go'] = False
  957. if 'good-to-go' not in vms_to_restore[vm.name].keys():
  958. vms_to_restore[vm.name]['good-to-go'] = True
  959. # ...and dom0 home
  960. if options['dom0-home'] and os.path.exists(backup_dir + '/dom0-home'):
  961. vms_to_restore['dom0'] = {}
  962. local_user = grp.getgrnam('qubes').gr_mem[0]
  963. dom0_homes = os.listdir(backup_dir + '/dom0-home')
  964. if len(dom0_homes) > 1:
  965. raise QubesException("More than one dom0 homedir in backup")
  966. vms_to_restore['dom0']['username'] = dom0_homes[0]
  967. if dom0_homes[0] != local_user:
  968. vms_to_restore['dom0']['username-mismatch'] = True
  969. if not options['ignore-dom0-username-mismatch']:
  970. vms_to_restore['dom0']['good-to-go'] = False
  971. if 'good-to-go' not in vms_to_restore['dom0']:
  972. vms_to_restore['dom0']['good-to-go'] = True
  973. return vms_to_restore
  974. def backup_restore_print_summary(restore_info, print_callback = print_stdout):
  975. fields = {
  976. "qid": {"func": "vm.qid"},
  977. "name": {"func": "('[' if vm.is_template() else '')\
  978. + ('{' if vm.is_netvm() else '')\
  979. + vm.name \
  980. + (']' if vm.is_template() else '')\
  981. + ('}' if vm.is_netvm() else '')"},
  982. "type": {"func": "'Tpl' if vm.is_template() else \
  983. 'HVM' if vm.type == 'HVM' else \
  984. vm.type.replace('VM','')"},
  985. "updbl" : {"func": "'Yes' if vm.updateable else ''"},
  986. "template": {"func": "'n/a' if vm.is_template() or vm.template is None else\
  987. vm_info['template']"},
  988. "netvm": {"func": "'n/a' if vm.is_netvm() and not vm.is_proxyvm() else\
  989. ('*' if vm.uses_default_netvm else '') +\
  990. vm_info['netvm'] if vm_info['netvm'] is not None else '-'"},
  991. "label" : {"func" : "vm.label.name"},
  992. }
  993. fields_to_display = ["name", "type", "template", "updbl", "netvm", "label" ]
  994. # First calculate the maximum width of each field we want to display
  995. total_width = 0;
  996. for f in fields_to_display:
  997. fields[f]["max_width"] = len(f)
  998. for vm_info in restore_info.values():
  999. if 'vm' in vm_info.keys():
  1000. vm = vm_info['vm']
  1001. l = len(str(eval(fields[f]["func"])))
  1002. if l > fields[f]["max_width"]:
  1003. fields[f]["max_width"] = l
  1004. total_width += fields[f]["max_width"]
  1005. print_callback("")
  1006. print_callback("The following VMs are included in the backup:")
  1007. print_callback("")
  1008. # Display the header
  1009. s = ""
  1010. for f in fields_to_display:
  1011. fmt="{{0:-^{0}}}-+".format(fields[f]["max_width"] + 1)
  1012. s += fmt.format('-')
  1013. print_callback(s)
  1014. s = ""
  1015. for f in fields_to_display:
  1016. fmt="{{0:>{0}}} |".format(fields[f]["max_width"] + 1)
  1017. s += fmt.format(f)
  1018. print_callback(s)
  1019. s = ""
  1020. for f in fields_to_display:
  1021. fmt="{{0:-^{0}}}-+".format(fields[f]["max_width"] + 1)
  1022. s += fmt.format('-')
  1023. print_callback(s)
  1024. for vm_info in restore_info.values():
  1025. # Skip non-VM here
  1026. if not 'vm' in vm_info:
  1027. continue
  1028. vm = vm_info['vm']
  1029. s = ""
  1030. for f in fields_to_display:
  1031. fmt="{{0:>{0}}} |".format(fields[f]["max_width"] + 1)
  1032. s += fmt.format(eval(fields[f]["func"]))
  1033. if 'excluded' in vm_info and vm_info['excluded']:
  1034. s += " <-- Excluded from restore"
  1035. elif 'already-exists' in vm_info:
  1036. s += " <-- A VM with the same name already exists on the host!"
  1037. elif 'missing-template' in vm_info:
  1038. s += " <-- No matching template on the host or in the backup found!"
  1039. elif 'missing-netvm' in vm_info:
  1040. s += " <-- No matching netvm on the host or in the backup found!"
  1041. elif 'orig-template' in vm_info:
  1042. s += " <-- Original template was '%s'" % (vm_info['orig-template'])
  1043. print_callback(s)
  1044. if 'dom0' in restore_info.keys():
  1045. s = ""
  1046. for f in fields_to_display:
  1047. fmt="{{0:>{0}}} |".format(fields[f]["max_width"] + 1)
  1048. if f == "name":
  1049. s += fmt.format("Dom0")
  1050. elif f == "type":
  1051. s += fmt.format("Home")
  1052. else:
  1053. s += fmt.format("")
  1054. if 'username-mismatch' in restore_info['dom0']:
  1055. s += " <-- username in backup and dom0 mismatch"
  1056. print_callback(s)
  1057. def backup_restore_do(backup_dir, restore_info, host_collection = None, print_callback = print_stdout, error_callback = print_stderr):
  1058. ### Private functions begin
  1059. def restore_vm_dir (backup_dir, src_dir, dst_dir):
  1060. backup_src_dir = src_dir.replace (system_path["qubes_base_dir"], backup_dir)
  1061. # We prefer to use Linux's cp, because it nicely handles sparse files
  1062. retcode = subprocess.call (["cp", "-rp", backup_src_dir, dst_dir])
  1063. if retcode != 0:
  1064. raise QubesException("*** Error while copying file {0} to {1}".format(backup_src_dir, dest_dir))
  1065. ### Private functions end
  1066. lock_obtained = False
  1067. if host_collection is None:
  1068. host_collection = QubesVmCollection()
  1069. host_collection.lock_db_for_writing()
  1070. host_collection.load()
  1071. lock_obtained = True
  1072. # Add VM in right order
  1073. for (vm_class_name, vm_class) in sorted(QubesVmClasses.items(),
  1074. key=lambda _x: _x[1].load_order):
  1075. for vm_info in restore_info.values():
  1076. if not vm_info['good-to-go']:
  1077. continue
  1078. if 'vm' not in vm_info:
  1079. continue
  1080. vm = vm_info['vm']
  1081. if not vm.__class__ == vm_class:
  1082. continue
  1083. print_callback("-> Restoring {type} {0}...".format(vm.name, type=vm_class_name))
  1084. retcode = subprocess.call (["mkdir", "-p", vm.dir_path])
  1085. if retcode != 0:
  1086. error_callback("*** Cannot create directory: {0}?!".format(dest_dir))
  1087. error_callback("Skipping...")
  1088. continue
  1089. template = None
  1090. if vm.template is not None:
  1091. template_name = vm_info['template']
  1092. template = host_collection.get_vm_by_name(template_name)
  1093. new_vm = None
  1094. try:
  1095. new_vm = host_collection.add_new_vm(vm_class_name, name=vm.name,
  1096. conf_file=vm.conf_file,
  1097. dir_path=vm.dir_path,
  1098. template=template,
  1099. installed_by_rpm=False)
  1100. restore_vm_dir (backup_dir, vm.dir_path, os.path.dirname(new_vm.dir_path));
  1101. new_vm.verify_files()
  1102. except Exception as err:
  1103. error_callback("ERROR: {0}".format(err))
  1104. error_callback("*** Skipping VM: {0}".format(vm.name))
  1105. if new_vm:
  1106. host_collection.pop(new_vm.qid)
  1107. continue
  1108. try:
  1109. new_vm.clone_attrs(vm)
  1110. except Exception as err:
  1111. error_callback("ERROR: {0}".format(err))
  1112. error_callback("*** Some VM property will not be restored")
  1113. try:
  1114. new_vm.appmenus_create(verbose=True)
  1115. except Exception as err:
  1116. error_callback("ERROR during appmenu restore: {0}".format(err))
  1117. error_callback("*** VM '{0}' will not have appmenus".format(vm.name))
  1118. # Set network dependencies - only non-default netvm setting
  1119. for vm_info in restore_info.values():
  1120. if not vm_info['good-to-go']:
  1121. continue
  1122. if 'vm' not in vm_info:
  1123. continue
  1124. vm = vm_info['vm']
  1125. host_vm = host_collection.get_vm_by_name(vm.name)
  1126. if host_vm is None:
  1127. # Failed/skipped VM
  1128. continue
  1129. if not vm.uses_default_netvm:
  1130. host_vm.netvm = host_collection.get_vm_by_name (vm_info['netvm']) if vm_info['netvm'] is not None else None
  1131. host_collection.save()
  1132. if lock_obtained:
  1133. host_collection.unlock_db()
  1134. # ... and dom0 home as last step
  1135. if 'dom0' in restore_info.keys() and restore_info['dom0']['good-to-go']:
  1136. backup_info = restore_info['dom0']
  1137. local_user = grp.getgrnam('qubes').gr_mem[0]
  1138. home_dir = pwd.getpwnam(local_user).pw_dir
  1139. backup_dom0_home_dir = backup_dir + '/dom0-home/' + backup_info['username']
  1140. restore_home_backupdir = "home-pre-restore-{0}".format (time.strftime("%Y-%m-%d-%H%M%S"))
  1141. print_callback("-> Restoring home of user '{0}'...".format(local_user))
  1142. print_callback("--> Existing files/dirs backed up in '{0}' dir".format(restore_home_backupdir))
  1143. os.mkdir(home_dir + '/' + restore_home_backupdir)
  1144. for f in os.listdir(backup_dom0_home_dir):
  1145. home_file = home_dir + '/' + f
  1146. if os.path.exists(home_file):
  1147. os.rename(home_file, home_dir + '/' + restore_home_backupdir + '/' + f)
  1148. retcode = subprocess.call (["cp", "-nrp", backup_dom0_home_dir + '/' + f, home_file])
  1149. if retcode != 0:
  1150. error_callback("*** Error while copying file {0} to {1}".format(backup_dom0_home_dir + '/' + f, home_file))
  1151. retcode = subprocess.call(['sudo', 'chown', '-R', local_user, home_dir])
  1152. if retcode != 0:
  1153. error_callback("*** Error while setting home directory owner")
  1154. # vim:sw=4:et: