qubesutils.py 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371
  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. appvms_to_backup = [vm for vm in all_vms if vm.is_appvm() and not vm.internal]
  690. netvms_to_backup = [vm for vm in all_vms if vm.is_netvm() and not vm.qid == 0]
  691. template_vms_worth_backingup = [vm for vm in all_vms if (vm.is_template() and not vm.installed_by_rpm)]
  692. vms_list = appvms_to_backup + netvms_to_backup + template_vms_worth_backingup
  693. vms_for_backup = vms_list
  694. # Apply exclude list
  695. if exclude_list:
  696. vms_for_backup = [vm for vm in vms_list if vm.name not in exclude_list]
  697. no_vms = len (vms_for_backup)
  698. there_are_running_vms = False
  699. fields_to_display = [
  700. { "name": "VM", "width": 16},
  701. { "name": "type","width": 12 },
  702. { "name": "size", "width": 12}
  703. ]
  704. # Display the header
  705. s = ""
  706. for f in fields_to_display:
  707. fmt="{{0:-^{0}}}-+".format(f["width"] + 1)
  708. s += fmt.format('-')
  709. print_callback(s)
  710. s = ""
  711. for f in fields_to_display:
  712. fmt="{{0:>{0}}} |".format(f["width"] + 1)
  713. s += fmt.format(f["name"])
  714. print_callback(s)
  715. s = ""
  716. for f in fields_to_display:
  717. fmt="{{0:-^{0}}}-+".format(f["width"] + 1)
  718. s += fmt.format('-')
  719. print_callback(s)
  720. for vm in vms_for_backup:
  721. if vm.is_template():
  722. # handle templates later
  723. continue
  724. if vm.private_img is not None:
  725. vm_sz = vm.get_disk_usage (vm.private_img)
  726. files_to_backup += file_to_backup(vm.private_img, vm_sz )
  727. if vm.is_appvm():
  728. files_to_backup += file_to_backup(vm.icon_path)
  729. if vm.updateable:
  730. if os.path.exists(vm.dir_path + "/apps.templates"):
  731. # template
  732. files_to_backup += file_to_backup(vm.dir_path + "/apps.templates")
  733. else:
  734. # standaloneVM
  735. files_to_backup += file_to_backup(vm.dir_path + "/apps")
  736. if os.path.exists(vm.dir_path + "/kernels"):
  737. files_to_backup += file_to_backup(vm.dir_path + "/kernels")
  738. if os.path.exists (vm.firewall_conf):
  739. files_to_backup += file_to_backup(vm.firewall_conf)
  740. if 'appmenus_whitelist' in vm_files and \
  741. os.path.exists(vm.dir_path + vm_files['appmenus_whitelist']):
  742. files_to_backup += file_to_backup(vm.dir_path + vm_files['appmenus_whitelist'])
  743. if vm.updateable:
  744. sz = vm.get_disk_usage(vm.root_img)
  745. files_to_backup += file_to_backup(vm.root_img, sz)
  746. vm_sz += sz
  747. s = ""
  748. fmt="{{0:>{0}}} |".format(fields_to_display[0]["width"] + 1)
  749. s += fmt.format(vm.name)
  750. fmt="{{0:>{0}}} |".format(fields_to_display[1]["width"] + 1)
  751. if vm.is_netvm():
  752. s += fmt.format("NetVM" + (" + Sys" if vm.updateable else ""))
  753. else:
  754. s += fmt.format("AppVM" + (" + Sys" if vm.updateable else ""))
  755. fmt="{{0:>{0}}} |".format(fields_to_display[2]["width"] + 1)
  756. s += fmt.format(size_to_human(vm_sz))
  757. if vm.is_running():
  758. s += " <-- The VM is running, please shut it down before proceeding with the backup!"
  759. there_are_running_vms = True
  760. print_callback(s)
  761. for vm in vms_for_backup:
  762. if not vm.is_template():
  763. # already handled
  764. continue
  765. vm_sz = vm.get_disk_utilization()
  766. files_to_backup += file_to_backup (vm.dir_path, vm_sz)
  767. s = ""
  768. fmt="{{0:>{0}}} |".format(fields_to_display[0]["width"] + 1)
  769. s += fmt.format(vm.name)
  770. fmt="{{0:>{0}}} |".format(fields_to_display[1]["width"] + 1)
  771. s += fmt.format("Template VM")
  772. fmt="{{0:>{0}}} |".format(fields_to_display[2]["width"] + 1)
  773. s += fmt.format(size_to_human(vm_sz))
  774. if vm.is_running():
  775. s += " <-- The VM is running, please shut it down before proceeding with the backup!"
  776. there_are_running_vms = True
  777. print_callback(s)
  778. # Dom0 user home
  779. if not 'dom0' in exclude_list:
  780. local_user = grp.getgrnam('qubes').gr_mem[0]
  781. home_dir = pwd.getpwnam(local_user).pw_dir
  782. # Home dir should have only user-owned files, so fix it now to prevent
  783. # permissions problems - some root-owned files can left after
  784. # 'sudo bash' and similar commands
  785. subprocess.check_call(['sudo', 'chown', '-R', local_user, home_dir])
  786. home_sz = get_disk_usage(home_dir)
  787. home_to_backup = [ { "path" : home_dir, "size": home_sz, "subdir": 'dom0-home'} ]
  788. files_to_backup += home_to_backup
  789. s = ""
  790. fmt="{{0:>{0}}} |".format(fields_to_display[0]["width"] + 1)
  791. s += fmt.format('Dom0')
  792. fmt="{{0:>{0}}} |".format(fields_to_display[1]["width"] + 1)
  793. s += fmt.format("User home")
  794. fmt="{{0:>{0}}} |".format(fields_to_display[2]["width"] + 1)
  795. s += fmt.format(size_to_human(home_sz))
  796. print_callback(s)
  797. total_backup_sz = 0
  798. for file in files_to_backup:
  799. total_backup_sz += file["size"]
  800. s = ""
  801. for f in fields_to_display:
  802. fmt="{{0:-^{0}}}-+".format(f["width"] + 1)
  803. s += fmt.format('-')
  804. print_callback(s)
  805. s = ""
  806. fmt="{{0:>{0}}} |".format(fields_to_display[0]["width"] + 1)
  807. s += fmt.format("Total size:")
  808. fmt="{{0:>{0}}} |".format(fields_to_display[1]["width"] + 1 + 2 + fields_to_display[2]["width"] + 1)
  809. s += fmt.format(size_to_human(total_backup_sz))
  810. print_callback(s)
  811. s = ""
  812. for f in fields_to_display:
  813. fmt="{{0:-^{0}}}-+".format(f["width"] + 1)
  814. s += fmt.format('-')
  815. print_callback(s)
  816. stat = os.statvfs(base_backup_dir)
  817. backup_fs_free_sz = stat.f_bsize * stat.f_bavail
  818. print_callback("")
  819. if (total_backup_sz > backup_fs_free_sz):
  820. raise QubesException("Not enough space available on the backup filesystem!")
  821. if (there_are_running_vms):
  822. raise QubesException("Please shutdown all VMs before proceeding.")
  823. print_callback("-> Available space: {0}".format(size_to_human(backup_fs_free_sz)))
  824. return files_to_backup
  825. def backup_do(base_backup_dir, files_to_backup, progress_callback = None):
  826. total_backup_sz = 0
  827. for file in files_to_backup:
  828. total_backup_sz += file["size"]
  829. backup_dir = base_backup_dir + "/qubes-{0}".format (time.strftime("%Y-%m-%d-%H%M%S"))
  830. if os.path.exists (backup_dir):
  831. raise QubesException("ERROR: the path {0} already exists?!".format(backup_dir))
  832. os.mkdir (backup_dir)
  833. if not os.path.exists (backup_dir):
  834. raise QubesException("Strange: couldn't create backup dir: {0}?!".format(backup_dir))
  835. bytes_backedup = 0
  836. for file in files_to_backup:
  837. # We prefer to use Linux's cp, because it nicely handles sparse files
  838. progress = bytes_backedup * 100 / total_backup_sz
  839. progress_callback(progress)
  840. dest_dir = backup_dir + '/' + file["subdir"]
  841. if file["subdir"] != "":
  842. retcode = subprocess.call (["mkdir", "-p", dest_dir])
  843. if retcode != 0:
  844. raise QubesException("Cannot create directory: {0}?!".format(dest_dir))
  845. retcode = subprocess.call (["cp", "-rp", file["path"], dest_dir])
  846. if retcode != 0:
  847. raise QubesException("Error while copying file {0} to {1}".format(file["path"], dest_dir))
  848. bytes_backedup += file["size"]
  849. progress = bytes_backedup * 100 / total_backup_sz
  850. progress_callback(progress)
  851. def backup_restore_set_defaults(options):
  852. if 'use-default-netvm' not in options:
  853. options['use-default-netvm'] = False
  854. if 'use-none-netvm' not in options:
  855. options['use-none-netvm'] = False
  856. if 'use-default-template' not in options:
  857. options['use-default-template'] = False
  858. if 'dom0-home' not in options:
  859. options['dom0-home'] = True
  860. if 'replace-template' not in options:
  861. options['replace-template'] = []
  862. return options
  863. def backup_restore_prepare(backup_dir, options = {}, host_collection = None):
  864. # Defaults
  865. backup_restore_set_defaults(options)
  866. #### Private functions begin
  867. def is_vm_included_in_backup (backup_dir, vm):
  868. if vm.qid == 0:
  869. # Dom0 is not included, obviously
  870. return False
  871. backup_vm_dir_path = vm.dir_path.replace (system_path["qubes_base_dir"], backup_dir)
  872. if os.path.exists (backup_vm_dir_path):
  873. return True
  874. else:
  875. return False
  876. def find_template_name(template, replaces):
  877. rx_replace = re.compile("(.*):(.*)")
  878. for r in replaces:
  879. m = rx_replace.match(r)
  880. if m.group(1) == template:
  881. return m.group(2)
  882. return template
  883. #### Private functions end
  884. if not os.path.exists (backup_dir):
  885. raise QubesException("The backup directory doesn't exist!")
  886. backup_collection = QubesVmCollection(store_filename = backup_dir + "/qubes.xml")
  887. backup_collection.lock_db_for_reading()
  888. backup_collection.load()
  889. if host_collection is None:
  890. host_collection = QubesVmCollection()
  891. host_collection.lock_db_for_reading()
  892. host_collection.load()
  893. host_collection.unlock_db()
  894. backup_vms_list = [vm for vm in backup_collection.values()]
  895. host_vms_list = [vm for vm in host_collection.values()]
  896. vms_to_restore = {}
  897. there_are_conflicting_vms = False
  898. there_are_missing_templates = False
  899. there_are_missing_netvms = False
  900. dom0_username_mismatch = False
  901. restore_home = False
  902. # ... and the actual data
  903. for vm in backup_vms_list:
  904. if is_vm_included_in_backup (backup_dir, vm):
  905. vms_to_restore[vm.name] = {}
  906. vms_to_restore[vm.name]['vm'] = vm;
  907. if 'exclude' in options.keys():
  908. vms_to_restore[vm.name]['excluded'] = vm.name in options['exclude']
  909. vms_to_restore[vm.name]['good-to-go'] = False
  910. if host_collection.get_vm_by_name (vm.name) is not None:
  911. vms_to_restore[vm.name]['already-exists'] = True
  912. vms_to_restore[vm.name]['good-to-go'] = False
  913. if vm.template is None:
  914. vms_to_restore[vm.name]['template'] = None
  915. else:
  916. templatevm_name = find_template_name(vm.template.name, options['replace-template'])
  917. vms_to_restore[vm.name]['template'] = templatevm_name
  918. template_vm_on_host = host_collection.get_vm_by_name (templatevm_name)
  919. # No template on the host?
  920. if not ((template_vm_on_host is not None) and template_vm_on_host.is_template()):
  921. # Maybe the (custom) template is in the backup?
  922. template_vm_on_backup = backup_collection.get_vm_by_name (templatevm_name)
  923. if template_vm_on_backup is None or not \
  924. (is_vm_included_in_backup(backup_dir, template_vm_on_backup) and \
  925. template_vm_on_backup.is_template()):
  926. if options['use-default-template']:
  927. vms_to_restore[vm.name]['orig-template'] = templatevm_name
  928. vms_to_restore[vm.name]['template'] = host_collection.get_default_template().name
  929. else:
  930. vms_to_restore[vm.name]['missing-template'] = True
  931. vms_to_restore[vm.name]['good-to-go'] = False
  932. if vm.netvm is None:
  933. vms_to_restore[vm.name]['netvm'] = None
  934. else:
  935. netvm_name = vm.netvm.name
  936. vms_to_restore[vm.name]['netvm'] = netvm_name
  937. # Set to None to not confuse QubesVm object from backup
  938. # collection with host collection (further in clone_attrs). Set
  939. # directly _netvm to suppress setter action, especially
  940. # modifying firewall
  941. vm._netvm = None
  942. netvm_on_host = host_collection.get_vm_by_name (netvm_name)
  943. # No netvm on the host?
  944. if not ((netvm_on_host is not None) and netvm_on_host.is_netvm()):
  945. # Maybe the (custom) netvm is in the backup?
  946. netvm_on_backup = backup_collection.get_vm_by_name (netvm_name)
  947. 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)):
  948. if options['use-default-netvm']:
  949. vms_to_restore[vm.name]['netvm'] = host_collection.get_default_netvm().name
  950. vm.uses_default_netvm = True
  951. elif options['use-none-netvm']:
  952. vms_to_restore[vm.name]['netvm'] = None
  953. else:
  954. vms_to_restore[vm.name]['missing-netvm'] = True
  955. vms_to_restore[vm.name]['good-to-go'] = False
  956. if 'good-to-go' not in vms_to_restore[vm.name].keys():
  957. vms_to_restore[vm.name]['good-to-go'] = True
  958. # ...and dom0 home
  959. if options['dom0-home'] and os.path.exists(backup_dir + '/dom0-home'):
  960. vms_to_restore['dom0'] = {}
  961. local_user = grp.getgrnam('qubes').gr_mem[0]
  962. dom0_homes = os.listdir(backup_dir + '/dom0-home')
  963. if len(dom0_homes) > 1:
  964. raise QubesException("More than one dom0 homedir in backup")
  965. vms_to_restore['dom0']['username'] = dom0_homes[0]
  966. if dom0_homes[0] != local_user:
  967. vms_to_restore['dom0']['username-mismatch'] = True
  968. if not options['ignore-dom0-username-mismatch']:
  969. vms_to_restore['dom0']['good-to-go'] = False
  970. if 'good-to-go' not in vms_to_restore['dom0']:
  971. vms_to_restore['dom0']['good-to-go'] = True
  972. return vms_to_restore
  973. def backup_restore_print_summary(restore_info, print_callback = print_stdout):
  974. fields = {
  975. "qid": {"func": "vm.qid"},
  976. "name": {"func": "('[' if vm.is_template() else '')\
  977. + ('{' if vm.is_netvm() else '')\
  978. + vm.name \
  979. + (']' if vm.is_template() else '')\
  980. + ('}' if vm.is_netvm() else '')"},
  981. "type": {"func": "'Tpl' if vm.is_template() else \
  982. 'HVM' if vm.type == 'HVM' else \
  983. vm.type.replace('VM','')"},
  984. "updbl" : {"func": "'Yes' if vm.updateable else ''"},
  985. "template": {"func": "'n/a' if vm.is_template() or vm.template is None else\
  986. vm_info['template']"},
  987. "netvm": {"func": "'n/a' if vm.is_netvm() and not vm.is_proxyvm() else\
  988. ('*' if vm.uses_default_netvm else '') +\
  989. vm_info['netvm'] if vm_info['netvm'] is not None else '-'"},
  990. "label" : {"func" : "vm.label.name"},
  991. }
  992. fields_to_display = ["name", "type", "template", "updbl", "netvm", "label" ]
  993. # First calculate the maximum width of each field we want to display
  994. total_width = 0;
  995. for f in fields_to_display:
  996. fields[f]["max_width"] = len(f)
  997. for vm_info in restore_info.values():
  998. if 'vm' in vm_info.keys():
  999. vm = vm_info['vm']
  1000. l = len(str(eval(fields[f]["func"])))
  1001. if l > fields[f]["max_width"]:
  1002. fields[f]["max_width"] = l
  1003. total_width += fields[f]["max_width"]
  1004. print_callback("")
  1005. print_callback("The following VMs are included in the backup:")
  1006. print_callback("")
  1007. # Display the header
  1008. s = ""
  1009. for f in fields_to_display:
  1010. fmt="{{0:-^{0}}}-+".format(fields[f]["max_width"] + 1)
  1011. s += fmt.format('-')
  1012. print_callback(s)
  1013. s = ""
  1014. for f in fields_to_display:
  1015. fmt="{{0:>{0}}} |".format(fields[f]["max_width"] + 1)
  1016. s += fmt.format(f)
  1017. print_callback(s)
  1018. s = ""
  1019. for f in fields_to_display:
  1020. fmt="{{0:-^{0}}}-+".format(fields[f]["max_width"] + 1)
  1021. s += fmt.format('-')
  1022. print_callback(s)
  1023. for vm_info in restore_info.values():
  1024. # Skip non-VM here
  1025. if not 'vm' in vm_info:
  1026. continue
  1027. vm = vm_info['vm']
  1028. s = ""
  1029. for f in fields_to_display:
  1030. fmt="{{0:>{0}}} |".format(fields[f]["max_width"] + 1)
  1031. s += fmt.format(eval(fields[f]["func"]))
  1032. if 'excluded' in vm_info and vm_info['excluded']:
  1033. s += " <-- Excluded from restore"
  1034. elif 'already-exists' in vm_info:
  1035. s += " <-- A VM with the same name already exists on the host!"
  1036. elif 'missing-template' in vm_info:
  1037. s += " <-- No matching template on the host or in the backup found!"
  1038. elif 'missing-netvm' in vm_info:
  1039. s += " <-- No matching netvm on the host or in the backup found!"
  1040. elif 'orig-template' in vm_info:
  1041. s += " <-- Original template was '%s'" % (vm_info['orig-template'])
  1042. print_callback(s)
  1043. if 'dom0' in restore_info.keys():
  1044. s = ""
  1045. for f in fields_to_display:
  1046. fmt="{{0:>{0}}} |".format(fields[f]["max_width"] + 1)
  1047. if f == "name":
  1048. s += fmt.format("Dom0")
  1049. elif f == "type":
  1050. s += fmt.format("Home")
  1051. else:
  1052. s += fmt.format("")
  1053. if 'username-mismatch' in restore_info['dom0']:
  1054. s += " <-- username in backup and dom0 mismatch"
  1055. print_callback(s)
  1056. def backup_restore_do(backup_dir, restore_info, host_collection = None, print_callback = print_stdout, error_callback = print_stderr):
  1057. ### Private functions begin
  1058. def restore_vm_dir (backup_dir, src_dir, dst_dir):
  1059. backup_src_dir = src_dir.replace (system_path["qubes_base_dir"], backup_dir)
  1060. # We prefer to use Linux's cp, because it nicely handles sparse files
  1061. retcode = subprocess.call (["cp", "-rp", backup_src_dir, dst_dir])
  1062. if retcode != 0:
  1063. raise QubesException("*** Error while copying file {0} to {1}".format(backup_src_dir, dest_dir))
  1064. ### Private functions end
  1065. lock_obtained = False
  1066. if host_collection is None:
  1067. host_collection = QubesVmCollection()
  1068. host_collection.lock_db_for_writing()
  1069. host_collection.load()
  1070. lock_obtained = True
  1071. # Add VM in right order
  1072. for (vm_class_name, vm_class) in sorted(QubesVmClasses.items(),
  1073. key=lambda _x: _x[1].load_order):
  1074. for vm_info in restore_info.values():
  1075. if not vm_info['good-to-go']:
  1076. continue
  1077. if 'vm' not in vm_info:
  1078. continue
  1079. vm = vm_info['vm']
  1080. if not vm.__class__ == vm_class:
  1081. continue
  1082. print_callback("-> Restoring {type} {0}...".format(vm.name, type=vm_class_name))
  1083. retcode = subprocess.call (["mkdir", "-p", vm.dir_path])
  1084. if retcode != 0:
  1085. error_callback("*** Cannot create directory: {0}?!".format(dest_dir))
  1086. error_callback("Skipping...")
  1087. continue
  1088. template = None
  1089. if vm.template is not None:
  1090. template_name = vm_info['template']
  1091. template = host_collection.get_vm_by_name(template_name)
  1092. new_vm = None
  1093. try:
  1094. new_vm = host_collection.add_new_vm(vm_class_name, name=vm.name,
  1095. conf_file=vm.conf_file,
  1096. dir_path=vm.dir_path,
  1097. template=template,
  1098. installed_by_rpm=False)
  1099. restore_vm_dir (backup_dir, vm.dir_path, os.path.dirname(new_vm.dir_path));
  1100. new_vm.verify_files()
  1101. except Exception as err:
  1102. error_callback("ERROR: {0}".format(err))
  1103. error_callback("*** Skipping VM: {0}".format(vm.name))
  1104. if new_vm:
  1105. host_collection.pop(new_vm.qid)
  1106. continue
  1107. try:
  1108. new_vm.clone_attrs(vm)
  1109. except Exception as err:
  1110. error_callback("ERROR: {0}".format(err))
  1111. error_callback("*** Some VM property will not be restored")
  1112. try:
  1113. new_vm.appmenus_create(verbose=True)
  1114. except Exception as err:
  1115. error_callback("ERROR during appmenu restore: {0}".format(err))
  1116. error_callback("*** VM '{0}' will not have appmenus".format(vm.name))
  1117. # Set network dependencies - only non-default netvm setting
  1118. for vm_info in restore_info.values():
  1119. if not vm_info['good-to-go']:
  1120. continue
  1121. if 'vm' not in vm_info:
  1122. continue
  1123. vm = vm_info['vm']
  1124. host_vm = host_collection.get_vm_by_name(vm.name)
  1125. if host_vm is None:
  1126. # Failed/skipped VM
  1127. continue
  1128. if not vm.uses_default_netvm:
  1129. host_vm.netvm = host_collection.get_vm_by_name (vm_info['netvm']) if vm_info['netvm'] is not None else None
  1130. host_collection.save()
  1131. if lock_obtained:
  1132. host_collection.unlock_db()
  1133. # ... and dom0 home as last step
  1134. if 'dom0' in restore_info.keys() and restore_info['dom0']['good-to-go']:
  1135. backup_info = restore_info['dom0']
  1136. local_user = grp.getgrnam('qubes').gr_mem[0]
  1137. home_dir = pwd.getpwnam(local_user).pw_dir
  1138. backup_dom0_home_dir = backup_dir + '/dom0-home/' + backup_info['username']
  1139. restore_home_backupdir = "home-pre-restore-{0}".format (time.strftime("%Y-%m-%d-%H%M%S"))
  1140. print_callback("-> Restoring home of user '{0}'...".format(local_user))
  1141. print_callback("--> Existing files/dirs backed up in '{0}' dir".format(restore_home_backupdir))
  1142. os.mkdir(home_dir + '/' + restore_home_backupdir)
  1143. for f in os.listdir(backup_dom0_home_dir):
  1144. home_file = home_dir + '/' + f
  1145. if os.path.exists(home_file):
  1146. os.rename(home_file, home_dir + '/' + restore_home_backupdir + '/' + f)
  1147. retcode = subprocess.call (["cp", "-nrp", backup_dom0_home_dir + '/' + f, home_file])
  1148. if retcode != 0:
  1149. error_callback("*** Error while copying file {0} to {1}".format(backup_dom0_home_dir + '/' + f, home_file))
  1150. retcode = subprocess.call(['sudo', 'chown', '-R', local_user, home_dir])
  1151. if retcode != 0:
  1152. error_callback("*** Error while setting home directory owner")
  1153. # vim:sw=4:et: