backup.py 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464
  1. #
  2. # The Qubes OS Project, http://www.qubes-os.org
  3. #
  4. # Copyright (C) 2013-2015 Marek Marczykowski-Górecki
  5. # <marmarek@invisiblethingslab.com>
  6. # Copyright (C) 2013 Olivier Médoc <o_medoc@yahoo.fr>
  7. #
  8. # This program is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU General Public License
  10. # as published by the Free Software Foundation; either version 2
  11. # of the License, or (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with this program. If not, see <http://www.gnu.org/licenses/>
  20. #
  21. #
  22. from __future__ import unicode_literals
  23. import itertools
  24. import logging
  25. from qubes.utils import size_to_human
  26. import sys
  27. import stat
  28. import os
  29. import fcntl
  30. import subprocess
  31. import re
  32. import shutil
  33. import tempfile
  34. import time
  35. import grp
  36. import pwd
  37. import errno
  38. import datetime
  39. from multiprocessing import Queue, Process
  40. import qubes
  41. import qubes.core2migration
  42. import qubes.storage
  43. import qubes.storage.file
  44. QUEUE_ERROR = "ERROR"
  45. QUEUE_FINISHED = "FINISHED"
  46. HEADER_FILENAME = 'backup-header'
  47. DEFAULT_CRYPTO_ALGORITHM = 'aes-256-cbc'
  48. DEFAULT_HMAC_ALGORITHM = 'SHA512'
  49. DEFAULT_COMPRESSION_FILTER = 'gzip'
  50. CURRENT_BACKUP_FORMAT_VERSION = '4'
  51. # Maximum size of error message get from process stderr (including VM process)
  52. MAX_STDERR_BYTES = 1024
  53. # header + qubes.xml max size
  54. HEADER_QUBES_XML_MAX_SIZE = 1024 * 1024
  55. BLKSIZE = 512
  56. _re_alphanum = re.compile(r'^[A-Za-z0-9-]*$')
  57. class BackupCanceledError(qubes.exc.QubesException):
  58. def __init__(self, msg, tmpdir=None):
  59. super(BackupCanceledError, self).__init__(msg)
  60. self.tmpdir = tmpdir
  61. class BackupHeader(object):
  62. header_keys = {
  63. 'version': 'version',
  64. 'encrypted': 'encrypted',
  65. 'compressed': 'compressed',
  66. 'compression-filter': 'compression_filter',
  67. 'crypto-algorithm': 'crypto_algorithm',
  68. 'hmac-algorithm': 'hmac_algorithm',
  69. 'backup-id': 'backup_id'
  70. }
  71. bool_options = ['encrypted', 'compressed']
  72. int_options = ['version']
  73. def __init__(self,
  74. header_data=None,
  75. version=None,
  76. encrypted=None,
  77. compressed=None,
  78. compression_filter=None,
  79. hmac_algorithm=None,
  80. crypto_algorithm=None,
  81. backup_id=None):
  82. # repeat the list to help code completion...
  83. self.version = version
  84. self.encrypted = encrypted
  85. self.compressed = compressed
  86. # Options introduced in backup format 3+, which always have a header,
  87. # so no need for fallback in function parameter
  88. self.compression_filter = compression_filter
  89. self.hmac_algorithm = hmac_algorithm
  90. self.crypto_algorithm = crypto_algorithm
  91. self.backup_id = backup_id
  92. if header_data is not None:
  93. self.load(header_data)
  94. def load(self, untrusted_header_text):
  95. """Parse backup header file.
  96. :param untrusted_header_text: header content
  97. :type untrusted_header_text: basestring
  98. .. warning::
  99. This function may be exposed to not yet verified header,
  100. so is security critical.
  101. """
  102. try:
  103. untrusted_header_text = untrusted_header_text.decode('ascii')
  104. except UnicodeDecodeError:
  105. raise qubes.exc.QubesException(
  106. "Non-ASCII characters in backup header")
  107. for untrusted_line in untrusted_header_text.splitlines():
  108. if untrusted_line.count('=') != 1:
  109. raise qubes.exc.QubesException("Invalid backup header")
  110. key, value = untrusted_line.strip().split('=', 1)
  111. if not _re_alphanum.match(key):
  112. raise qubes.exc.QubesException("Invalid backup header (key)")
  113. if key not in self.header_keys.keys():
  114. # Ignoring unknown option
  115. continue
  116. if not _re_alphanum.match(value):
  117. raise qubes.exc.QubesException("Invalid backup header (value)")
  118. if getattr(self, self.header_keys[key]) is not None:
  119. raise qubes.exc.QubesException(
  120. "Duplicated header line: {}".format(key))
  121. if key in self.bool_options:
  122. value = value.lower() in ["1", "true", "yes"]
  123. elif key in self.int_options:
  124. value = int(value)
  125. setattr(self, self.header_keys[key], value)
  126. self.validate()
  127. def validate(self):
  128. if self.version == 1:
  129. # header not really present
  130. pass
  131. elif self.version in [2, 3, 4]:
  132. expected_attrs = ['version', 'encrypted', 'compressed',
  133. 'hmac_algorithm']
  134. if self.encrypted:
  135. expected_attrs += ['crypto_algorithm']
  136. if self.version >= 3 and self.compressed:
  137. expected_attrs += ['compression_filter']
  138. if self.version >= 4:
  139. expected_attrs += ['backup_id']
  140. for key in expected_attrs:
  141. if getattr(self, key) is None:
  142. raise qubes.exc.QubesException(
  143. "Backup header lack '{}' info".format(key))
  144. else:
  145. raise qubes.exc.QubesException(
  146. "Unsupported backup version {}".format(self.version))
  147. def save(self, filename):
  148. with open(filename, "w") as f:
  149. # make sure 'version' is the first key
  150. f.write('version={}\n'.format(self.version))
  151. for key, attr in self.header_keys.iteritems():
  152. if key == 'version':
  153. continue
  154. if getattr(self, attr) is None:
  155. continue
  156. f.write("{!s}={!s}\n".format(key, getattr(self, attr)))
  157. class SendWorker(Process):
  158. def __init__(self, queue, base_dir, backup_stdout):
  159. super(SendWorker, self).__init__()
  160. self.queue = queue
  161. self.base_dir = base_dir
  162. self.backup_stdout = backup_stdout
  163. self.log = logging.getLogger('qubes.backup')
  164. def run(self):
  165. self.log.debug("Started sending thread")
  166. self.log.debug("Moving to temporary dir".format(self.base_dir))
  167. os.chdir(self.base_dir)
  168. for filename in iter(self.queue.get, None):
  169. if filename in (QUEUE_FINISHED, QUEUE_ERROR):
  170. break
  171. self.log.debug("Sending file {}".format(filename))
  172. # This tar used for sending data out need to be as simple, as
  173. # simple, as featureless as possible. It will not be
  174. # verified before untaring.
  175. tar_final_cmd = ["tar", "-cO", "--posix",
  176. "-C", self.base_dir, filename]
  177. final_proc = subprocess.Popen(tar_final_cmd,
  178. stdin=subprocess.PIPE,
  179. stdout=self.backup_stdout)
  180. if final_proc.wait() >= 2:
  181. if self.queue.full():
  182. # if queue is already full, remove some entry to wake up
  183. # main thread, so it will be able to notice error
  184. self.queue.get()
  185. # handle only exit code 2 (tar fatal error) or
  186. # greater (call failed?)
  187. raise qubes.exc.QubesException(
  188. "ERROR: Failed to write the backup, out of disk space? "
  189. "Check console output or ~/.xsession-errors for details.")
  190. # Delete the file as we don't need it anymore
  191. self.log.debug("Removing file {}".format(filename))
  192. os.remove(filename)
  193. self.log.debug("Finished sending thread")
  194. class Backup(object):
  195. class FileToBackup(object):
  196. def __init__(self, file_path, subdir=None, name=None):
  197. sz = qubes.storage.file.get_disk_usage(file_path)
  198. if subdir is None:
  199. abs_file_path = os.path.abspath(file_path)
  200. abs_base_dir = os.path.abspath(
  201. qubes.config.system_path["qubes_base_dir"]) + '/'
  202. abs_file_dir = os.path.dirname(abs_file_path) + '/'
  203. (nothing, directory, subdir) = abs_file_dir.partition(abs_base_dir)
  204. assert nothing == ""
  205. assert directory == abs_base_dir
  206. else:
  207. if len(subdir) > 0 and not subdir.endswith('/'):
  208. subdir += '/'
  209. #: real path to the file
  210. self.path = file_path
  211. #: size of the file
  212. self.size = sz
  213. #: directory in backup archive where file should be placed
  214. self.subdir = subdir
  215. #: use this name in the archive (aka rename)
  216. self.name = os.path.basename(file_path)
  217. if name is not None:
  218. self.name = name
  219. class VMToBackup(object):
  220. def __init__(self, vm, files, subdir):
  221. self.vm = vm
  222. self.files = files
  223. self.subdir = subdir
  224. @property
  225. def size(self):
  226. return reduce(lambda x, y: x + y.size, self.files, 0)
  227. def __init__(self, app, vms_list=None, exclude_list=None, **kwargs):
  228. """
  229. If vms = None, include all (sensible) VMs;
  230. exclude_list is always applied
  231. """
  232. super(Backup, self).__init__()
  233. #: progress of the backup - bytes handled of the current VM
  234. self.chunk_size = 100 * 1024 * 1024
  235. self._current_vm_bytes = 0
  236. #: progress of the backup - bytes handled of finished VMs
  237. self._done_vms_bytes = 0
  238. #: total backup size (set by :py:meth:`get_files_to_backup`)
  239. self.total_backup_bytes = 0
  240. #: application object
  241. self.app = app
  242. #: directory for temporary files - set after creating the directory
  243. self.tmpdir = None
  244. # Backup settings - defaults
  245. #: should the backup be encrypted?
  246. self.encrypted = True
  247. #: should the backup be compressed?
  248. self.compressed = True
  249. #: what passphrase should be used to intergrity protect (and encrypt)
  250. #: the backup; required
  251. self.passphrase = None
  252. #: custom hmac algorithm
  253. self.hmac_algorithm = DEFAULT_HMAC_ALGORITHM
  254. #: custom encryption algorithm
  255. self.crypto_algorithm = DEFAULT_CRYPTO_ALGORITHM
  256. #: custom compression filter; a program which process stdin to stdout
  257. self.compression_filter = DEFAULT_COMPRESSION_FILTER
  258. #: VM to which backup should be sent (if any)
  259. self.target_vm = None
  260. #: directory to save backup in (either in dom0 or target VM,
  261. #: depending on :py:attr:`target_vm`
  262. self.target_dir = None
  263. #: callback for progress reporting. Will be called with one argument
  264. #: - progress in percents
  265. self.progress_callback = None
  266. #: backup ID, needs to be unique (for a given user),
  267. #: not necessary unpredictable; automatically generated
  268. self.backup_id = datetime.datetime.now().strftime(
  269. '%Y%m%dT%H%M%S-' + str(os.getpid()))
  270. for key, value in kwargs.iteritems():
  271. if hasattr(self, key):
  272. setattr(self, key, value)
  273. else:
  274. raise AttributeError(key)
  275. #: whether backup was canceled
  276. self.canceled = False
  277. #: list of PIDs to kill on backup cancel
  278. self.processes_to_kill_on_cancel = []
  279. self.log = logging.getLogger('qubes.backup')
  280. if not self.encrypted:
  281. self.log.warning('\'encrypted\' option is ignored, backup is '
  282. 'always encrypted')
  283. if exclude_list is None:
  284. exclude_list = []
  285. if vms_list is None:
  286. vms_list = [vm for vm in app.domains if vm.include_in_backups]
  287. # Apply exclude list
  288. self.vms_for_backup = [vm for vm in vms_list
  289. if vm.name not in exclude_list]
  290. self._files_to_backup = self.get_files_to_backup()
  291. def __del__(self):
  292. if self.tmpdir and os.path.exists(self.tmpdir):
  293. shutil.rmtree(self.tmpdir)
  294. def cancel(self):
  295. """Cancel running backup operation. Can be called from another thread.
  296. """
  297. self.canceled = True
  298. for proc in self.processes_to_kill_on_cancel:
  299. try:
  300. proc.terminate()
  301. except OSError:
  302. pass
  303. def get_files_to_backup(self):
  304. files_to_backup = {}
  305. for vm in self.vms_for_backup:
  306. if vm.qid == 0:
  307. # handle dom0 later
  308. continue
  309. if self.encrypted:
  310. subdir = 'vm%d/' % vm.qid
  311. else:
  312. subdir = None
  313. vm_files = []
  314. if vm.volumes['private'] is not None:
  315. path_to_private_img = vm.storage.export('private')
  316. vm_files.append(self.FileToBackup(path_to_private_img, subdir,
  317. 'private.img'))
  318. vm_files.append(self.FileToBackup(vm.icon_path, subdir))
  319. vm_files.extend(self.FileToBackup(i, subdir)
  320. for i in vm.fire_event('backup-get-files'))
  321. # TODO: drop after merging firewall.xml into qubes.xml
  322. firewall_conf = os.path.join(vm.dir_path, vm.firewall_conf)
  323. if os.path.exists(firewall_conf):
  324. vm_files.append(self.FileToBackup(firewall_conf, subdir))
  325. if vm.updateable:
  326. path_to_root_img = vm.storage.export('root')
  327. vm_files.append(self.FileToBackup(path_to_root_img, subdir,
  328. 'root.img'))
  329. files_to_backup[vm.qid] = self.VMToBackup(vm, vm_files, subdir)
  330. # Dom0 user home
  331. if 0 in [vm.qid for vm in self.vms_for_backup]:
  332. local_user = grp.getgrnam('qubes').gr_mem[0]
  333. home_dir = pwd.getpwnam(local_user).pw_dir
  334. # Home dir should have only user-owned files, so fix it now
  335. # to prevent permissions problems - some root-owned files can
  336. # left after 'sudo bash' and similar commands
  337. subprocess.check_call(['sudo', 'chown', '-R', local_user, home_dir])
  338. home_to_backup = [
  339. self.FileToBackup(home_dir, 'dom0-home/')]
  340. vm_files = home_to_backup
  341. files_to_backup[0] = self.VMToBackup(self.app.domains[0],
  342. vm_files,
  343. os.path.join('dom0-home', os.path.basename(home_dir)))
  344. self.total_backup_bytes = reduce(
  345. lambda x, y: x + y.size, files_to_backup.values(), 0)
  346. return files_to_backup
  347. def get_backup_summary(self):
  348. summary = ""
  349. fields_to_display = [
  350. {"name": "VM", "width": 16},
  351. {"name": "type", "width": 12},
  352. {"name": "size", "width": 12}
  353. ]
  354. # Display the header
  355. for f in fields_to_display:
  356. fmt = "{{0:-^{0}}}-+".format(f["width"] + 1)
  357. summary += fmt.format('-')
  358. summary += "\n"
  359. for f in fields_to_display:
  360. fmt = "{{0:>{0}}} |".format(f["width"] + 1)
  361. summary += fmt.format(f["name"])
  362. summary += "\n"
  363. for f in fields_to_display:
  364. fmt = "{{0:-^{0}}}-+".format(f["width"] + 1)
  365. summary += fmt.format('-')
  366. summary += "\n"
  367. files_to_backup = self._files_to_backup
  368. for qid, vm_info in files_to_backup.iteritems():
  369. s = ""
  370. fmt = "{{0:>{0}}} |".format(fields_to_display[0]["width"] + 1)
  371. s += fmt.format(vm_info['vm'].name)
  372. fmt = "{{0:>{0}}} |".format(fields_to_display[1]["width"] + 1)
  373. if qid == 0:
  374. s += fmt.format("User home")
  375. elif isinstance(vm_info['vm'], qubes.vm.templatevm.TemplateVM):
  376. s += fmt.format("Template VM")
  377. else:
  378. s += fmt.format("VM" + (" + Sys" if vm_info['vm'].updateable
  379. else ""))
  380. vm_size = vm_info['size']
  381. fmt = "{{0:>{0}}} |".format(fields_to_display[2]["width"] + 1)
  382. s += fmt.format(size_to_human(vm_size))
  383. if qid != 0 and vm_info['vm'].is_running():
  384. s += " <-- The VM is running, please shut it down before proceeding " \
  385. "with the backup!"
  386. summary += s + "\n"
  387. for f in fields_to_display:
  388. fmt = "{{0:-^{0}}}-+".format(f["width"] + 1)
  389. summary += fmt.format('-')
  390. summary += "\n"
  391. fmt = "{{0:>{0}}} |".format(fields_to_display[0]["width"] + 1)
  392. summary += fmt.format("Total size:")
  393. fmt = "{{0:>{0}}} |".format(
  394. fields_to_display[1]["width"] + 1 + 2 + fields_to_display[2][
  395. "width"] + 1)
  396. summary += fmt.format(size_to_human(self.total_backup_bytes))
  397. summary += "\n"
  398. for f in fields_to_display:
  399. fmt = "{{0:-^{0}}}-+".format(f["width"] + 1)
  400. summary += fmt.format('-')
  401. summary += "\n"
  402. vms_not_for_backup = [vm.name for vm in self.app.domains
  403. if vm not in self.vms_for_backup]
  404. summary += "VMs not selected for backup:\n - " + "\n - ".join(
  405. sorted(vms_not_for_backup))
  406. return summary
  407. def prepare_backup_header(self):
  408. header_file_path = os.path.join(self.tmpdir, HEADER_FILENAME)
  409. backup_header = BackupHeader(
  410. version=CURRENT_BACKUP_FORMAT_VERSION,
  411. hmac_algorithm=self.hmac_algorithm,
  412. crypto_algorithm=self.crypto_algorithm,
  413. encrypted=self.encrypted,
  414. compressed=self.compressed,
  415. compression_filter=self.compression_filter,
  416. backup_id=self.backup_id,
  417. )
  418. backup_header.save(header_file_path)
  419. hmac = subprocess.Popen(
  420. ["openssl", "dgst", "-" + self.hmac_algorithm,
  421. "-hmac", self.passphrase],
  422. stdin=open(header_file_path, "r"),
  423. stdout=open(header_file_path + ".hmac", "w"))
  424. if hmac.wait() != 0:
  425. raise qubes.exc.QubesException(
  426. "Failed to compute hmac of header file")
  427. return HEADER_FILENAME, HEADER_FILENAME + ".hmac"
  428. @staticmethod
  429. def _queue_put_with_check(proc, vmproc, queue, element):
  430. if queue.full():
  431. if not proc.is_alive():
  432. if vmproc:
  433. message = ("Failed to write the backup, VM output:\n" +
  434. vmproc.stderr.read())
  435. else:
  436. message = "Failed to write the backup. Out of disk space?"
  437. raise qubes.exc.QubesException(message)
  438. queue.put(element)
  439. def _send_progress_update(self):
  440. if callable(self.progress_callback):
  441. progress = (
  442. 100 * (self._done_vms_bytes + self._current_vm_bytes) /
  443. self.total_backup_bytes)
  444. self.progress_callback(progress)
  445. def _add_vm_progress(self, bytes_done):
  446. self._current_vm_bytes += bytes_done
  447. self._send_progress_update()
  448. def backup_do(self):
  449. if self.passphrase is None:
  450. raise qubes.exc.QubesException("No passphrase set")
  451. qubes_xml = self.app.store
  452. self.tmpdir = tempfile.mkdtemp()
  453. shutil.copy(qubes_xml, os.path.join(self.tmpdir, 'qubes.xml'))
  454. qubes_xml = os.path.join(self.tmpdir, 'qubes.xml')
  455. backup_app = qubes.Qubes(qubes_xml)
  456. files_to_backup = self._files_to_backup
  457. # make sure backup_content isn't set initially
  458. for vm in backup_app.domains:
  459. vm.features['backup-content'] = False
  460. for qid, vm_info in files_to_backup.iteritems():
  461. if qid != 0 and vm_info.vm.is_running():
  462. raise qubes.exc.QubesVMNotHaltedError(vm_info.vm)
  463. # VM is included in the backup
  464. backup_app.domains[qid].features['backup-content'] = True
  465. backup_app.domains[qid].features['backup-path'] = vm_info.subdir
  466. backup_app.domains[qid].features['backup-size'] = vm_info.size
  467. backup_app.save()
  468. vmproc = None
  469. tar_sparse = None
  470. if self.target_vm is not None:
  471. # Prepare the backup target (Qubes service call)
  472. # If APPVM, STDOUT is a PIPE
  473. vmproc = self.target_vm.run_service('qubes.Backup',
  474. passio_popen=True, passio_stderr=True)
  475. vmproc.stdin.write(self.target_dir.
  476. replace("\r", "").replace("\n", "") + "\n")
  477. backup_stdout = vmproc.stdin
  478. self.processes_to_kill_on_cancel.append(vmproc)
  479. else:
  480. # Prepare the backup target (local file)
  481. if os.path.isdir(self.target_dir):
  482. backup_target = self.target_dir + "/qubes-{0}". \
  483. format(time.strftime("%Y-%m-%dT%H%M%S"))
  484. else:
  485. backup_target = self.target_dir
  486. # Create the target directory
  487. if not os.path.exists(os.path.dirname(self.target_dir)):
  488. raise qubes.exc.QubesException(
  489. "ERROR: the backup directory for {0} does not exists".
  490. format(self.target_dir))
  491. # If not APPVM, STDOUT is a local file
  492. backup_stdout = open(backup_target, 'wb')
  493. # Tar with tape length does not deals well with stdout
  494. # (close stdout between two tapes)
  495. # For this reason, we will use named pipes instead
  496. self.log.debug("Working in {}".format(self.tmpdir))
  497. backup_pipe = os.path.join(self.tmpdir, "backup_pipe")
  498. self.log.debug("Creating pipe in: {}".format(backup_pipe))
  499. os.mkfifo(backup_pipe)
  500. self.log.debug("Will backup: {}".format(files_to_backup))
  501. header_files = self.prepare_backup_header()
  502. # Setup worker to send encrypted data chunks to the backup_target
  503. to_send = Queue(10)
  504. send_proc = SendWorker(to_send, self.tmpdir, backup_stdout)
  505. send_proc.start()
  506. for f in header_files:
  507. to_send.put(f)
  508. qubes_xml_info = self.VMToBackup(
  509. None,
  510. [self.FileToBackup(qubes_xml, '')],
  511. ''
  512. )
  513. for vm_info in itertools.chain([qubes_xml_info],
  514. files_to_backup.itervalues()):
  515. for file_info in vm_info.files:
  516. self.log.debug("Backing up {}".format(file_info))
  517. backup_tempfile = os.path.join(
  518. self.tmpdir, file_info.subdir,
  519. file_info.name)
  520. self.log.debug("Using temporary location: {}".format(
  521. backup_tempfile))
  522. # Ensure the temporary directory exists
  523. if not os.path.isdir(os.path.dirname(backup_tempfile)):
  524. os.makedirs(os.path.dirname(backup_tempfile))
  525. # The first tar cmd can use any complex feature as we want.
  526. # Files will be verified before untaring this.
  527. # Prefix the path in archive with filename["subdir"] to have it
  528. # verified during untar
  529. tar_cmdline = (["tar", "-Pc", '--sparse',
  530. "-f", backup_pipe,
  531. '-C', os.path.dirname(file_info.path)] +
  532. (['--dereference'] if
  533. file_info.subdir != "dom0-home/" else []) +
  534. ['--xform=s:^%s:%s\\0:' % (
  535. os.path.basename(file_info.path),
  536. file_info.subdir),
  537. os.path.basename(file_info.path)
  538. ])
  539. file_stat = os.stat(file_info.path)
  540. if stat.S_ISBLK(file_stat.st_mode) or \
  541. file_info.name != os.path.basename(file_info.path):
  542. # tar doesn't handle content of block device, use our
  543. # writer
  544. # also use our tar writer when renaming file
  545. assert not stat.S_ISDIR(file_stat.st_mode),\
  546. "Renaming directories not supported"
  547. tar_cmdline = ['python', '-m', 'qubes.tarwriter',
  548. '--override-name=%s' % (
  549. os.path.join(file_info.subdir, os.path.basename(
  550. file_info.name))),
  551. file_info.path,
  552. backup_pipe]
  553. if self.compressed:
  554. tar_cmdline.insert(-2,
  555. "--use-compress-program=%s" % self.compression_filter)
  556. self.log.debug(" ".join(tar_cmdline))
  557. # Tips: Popen(bufsize=0)
  558. # Pipe: tar-sparse | encryptor [| hmac] | tar | backup_target
  559. # Pipe: tar-sparse [| hmac] | tar | backup_target
  560. # TODO: log handle stderr
  561. tar_sparse = subprocess.Popen(
  562. tar_cmdline, stdin=subprocess.PIPE)
  563. self.processes_to_kill_on_cancel.append(tar_sparse)
  564. # Wait for compressor (tar) process to finish or for any
  565. # error of other subprocesses
  566. i = 0
  567. run_error = "paused"
  568. encryptor = None
  569. if self.encrypted:
  570. # Start encrypt
  571. # If no cipher is provided,
  572. # the data is forwarded unencrypted !!!
  573. encryptor = subprocess.Popen([
  574. "openssl", "enc",
  575. "-e", "-" + self.crypto_algorithm,
  576. "-pass", "pass:" + passphrase],
  577. stdin=open(backup_pipe, 'rb'),
  578. stdout=subprocess.PIPE)
  579. pipe = encryptor.stdout
  580. else:
  581. pipe = open(backup_pipe, 'rb')
  582. while run_error == "paused":
  583. # Start HMAC
  584. hmac = subprocess.Popen([
  585. "openssl", "dgst", "-" + self.hmac_algorithm,
  586. "-hmac", passphrase],
  587. stdin=subprocess.PIPE,
  588. stdout=subprocess.PIPE)
  589. # Prepare a first chunk
  590. chunkfile = backup_tempfile + "." + "%03d" % i
  591. i += 1
  592. chunkfile_p = open(chunkfile, 'wb')
  593. run_error = handle_streams(
  594. pipe,
  595. {'hmac_data': hmac.stdin,
  596. 'backup_target': chunkfile_p,
  597. },
  598. {'hmac': hmac,
  599. 'vmproc': vmproc,
  600. 'addproc': tar_sparse,
  601. 'streamproc': encryptor,
  602. },
  603. self.chunk_size,
  604. self._add_vm_progress
  605. )
  606. chunkfile_p.close()
  607. self.log.debug(
  608. "12 returned: {}".format(run_error))
  609. if self.canceled:
  610. try:
  611. tar_sparse.terminate()
  612. except OSError:
  613. pass
  614. try:
  615. hmac.terminate()
  616. except OSError:
  617. pass
  618. tar_sparse.wait()
  619. hmac.wait()
  620. to_send.put(QUEUE_ERROR)
  621. send_proc.join()
  622. shutil.rmtree(self.tmpdir)
  623. raise BackupCanceledError("Backup canceled")
  624. if run_error and run_error != "size_limit":
  625. send_proc.terminate()
  626. if run_error == "VM" and vmproc:
  627. raise qubes.exc.QubesException(
  628. "Failed to write the backup, VM output:\n" +
  629. vmproc.stderr.read(MAX_STDERR_BYTES))
  630. else:
  631. raise qubes.exc.QubesException(
  632. "Failed to perform backup: error in " +
  633. run_error)
  634. # Send the chunk to the backup target
  635. self._queue_put_with_check(
  636. send_proc, vmproc, to_send,
  637. os.path.relpath(chunkfile, self.tmpdir))
  638. # Close HMAC
  639. hmac.stdin.close()
  640. hmac.wait()
  641. self.log.debug("HMAC proc return code: {}".format(
  642. hmac.poll()))
  643. # Write HMAC data next to the chunk file
  644. hmac_data = hmac.stdout.read()
  645. self.log.debug(
  646. "Writing hmac to {}.hmac".format(chunkfile))
  647. with open(chunkfile + ".hmac", 'w') as hmac_file:
  648. hmac_file.write(hmac_data)
  649. # Send the HMAC to the backup target
  650. self._queue_put_with_check(
  651. send_proc, vmproc, to_send,
  652. os.path.relpath(chunkfile, self.tmpdir) + ".hmac")
  653. if tar_sparse.poll() is None or run_error == "size_limit":
  654. run_error = "paused"
  655. else:
  656. self.processes_to_kill_on_cancel.remove(tar_sparse)
  657. self.log.debug(
  658. "Finished tar sparse with exit code {}".format(
  659. tar_sparse.poll()))
  660. pipe.close()
  661. # This VM done, update progress
  662. self._done_vms_bytes += vm_info.size
  663. self._current_vm_bytes = 0
  664. self._send_progress_update()
  665. # Save date of last backup
  666. if vm_info.vm:
  667. vm_info.vm.backup_timestamp = datetime.datetime.now()
  668. self._queue_put_with_check(send_proc, vmproc, to_send, QUEUE_FINISHED)
  669. send_proc.join()
  670. shutil.rmtree(self.tmpdir)
  671. if self.canceled:
  672. raise BackupCanceledError("Backup canceled")
  673. if send_proc.exitcode != 0:
  674. raise qubes.exc.QubesException(
  675. "Failed to send backup: error in the sending process")
  676. if vmproc:
  677. self.log.debug("VMProc1 proc return code: {}".format(vmproc.poll()))
  678. if tar_sparse is not None:
  679. self.log.debug("Sparse1 proc return code: {}".format(
  680. tar_sparse.poll()))
  681. vmproc.stdin.close()
  682. self.app.save()
  683. def handle_streams(stream_in, streams_out, processes, size_limit=None,
  684. progress_callback=None):
  685. '''
  686. Copy stream_in to all streams_out and monitor all mentioned processes.
  687. If any of them terminate with non-zero code, interrupt the process. Copy
  688. at most `size_limit` data (if given).
  689. :param stream_in: file-like object to read data from
  690. :param streams_out: dict of file-like objects to write data to
  691. :param processes: dict of subprocess.Popen objects to monitor
  692. :param size_limit: int maximum data amount to process
  693. :param progress_callback: callable function to report progress, will be
  694. given copied data size (it should accumulate internally)
  695. :return: failed process name, failed stream name, "size_limit" or None (
  696. no error)
  697. '''
  698. buffer_size = 409600
  699. bytes_copied = 0
  700. while True:
  701. if size_limit:
  702. to_copy = min(buffer_size, size_limit - bytes_copied)
  703. if to_copy <= 0:
  704. return "size_limit"
  705. else:
  706. to_copy = buffer_size
  707. buf = stream_in.read(to_copy)
  708. if not len(buf):
  709. # done
  710. return None
  711. if callable(progress_callback):
  712. progress_callback(len(buf))
  713. for name, stream in streams_out.items():
  714. if stream is None:
  715. continue
  716. try:
  717. stream.write(buf)
  718. except IOError:
  719. return name
  720. bytes_copied += len(buf)
  721. for name, proc in processes.items():
  722. if proc is None:
  723. continue
  724. if proc.poll():
  725. return name
  726. class ExtractWorker2(Process):
  727. def __init__(self, queue, base_dir, passphrase, encrypted,
  728. progress_callback, vmproc=None,
  729. compressed=False, crypto_algorithm=DEFAULT_CRYPTO_ALGORITHM,
  730. verify_only=False, relocate=None):
  731. super(ExtractWorker2, self).__init__()
  732. #: queue with files to extract
  733. self.queue = queue
  734. #: paths on the queue are relative to this dir
  735. self.base_dir = base_dir
  736. #: passphrase to decrypt/authenticate data
  737. self.passphrase = passphrase
  738. #: extract those files/directories to alternative locations (truncate,
  739. # but not unlink target beforehand); if specific file is in the map,
  740. # redirect it accordingly, otherwise check if the whole directory is
  741. # there
  742. self.relocate = relocate
  743. #: is the backup encrypted?
  744. self.encrypted = encrypted
  745. #: is the backup compressed?
  746. self.compressed = compressed
  747. #: what crypto algorithm is used for encryption?
  748. self.crypto_algorithm = crypto_algorithm
  749. #: only verify integrity, don't extract anything
  750. self.verify_only = verify_only
  751. #: progress
  752. self.blocks_backedup = 0
  753. #: inner tar layer extraction (subprocess.Popen instance)
  754. self.tar2_process = None
  755. #: current inner tar archive name
  756. self.tar2_current_file = None
  757. #: set size of this file when tar report it on stderr (adjust LVM
  758. # volume size)
  759. self.adjust_output_size = None
  760. #: decompressor subprocess.Popen instance
  761. self.decompressor_process = None
  762. #: decryptor subprocess.Popen instance
  763. self.decryptor_process = None
  764. #: callback reporting progress to UI
  765. self.progress_callback = progress_callback
  766. #: process (subprocess.Popen instance) feeding the data into
  767. # extraction tool
  768. self.vmproc = vmproc
  769. #: pipe to feed the data into tar (use pipe instead of stdin,
  770. # as stdin is used for tar control commands)
  771. self.restore_pipe = os.path.join(self.base_dir, "restore_pipe")
  772. self.log = logging.getLogger('qubes.backup.extract')
  773. self.log.debug("Creating pipe in: {}".format(self.restore_pipe))
  774. os.mkfifo(self.restore_pipe)
  775. self.stderr_encoding = sys.stderr.encoding or 'utf-8'
  776. def collect_tar_output(self):
  777. if not self.tar2_process.stderr:
  778. return
  779. if self.tar2_process.poll() is None:
  780. try:
  781. new_lines = self.tar2_process.stderr \
  782. .read(MAX_STDERR_BYTES).splitlines()
  783. except IOError as e:
  784. if e.errno == errno.EAGAIN:
  785. return
  786. else:
  787. raise
  788. else:
  789. new_lines = self.tar2_process.stderr.readlines()
  790. new_lines = map(lambda x: x.decode(self.stderr_encoding), new_lines)
  791. msg_re = re.compile(r".*#[0-9].*restore_pipe")
  792. debug_msg = filter(msg_re.match, new_lines)
  793. self.log.debug('tar2_stderr: {}'.format('\n'.join(debug_msg)))
  794. new_lines = filter(lambda x: not msg_re.match(x), new_lines)
  795. if self.adjust_output_size:
  796. # search for first file size reported by tar, after setting
  797. # self.adjust_output_size (so don't look at self.tar2_stderr)
  798. # this is used only when extracting single-file archive, so don't
  799. # bother with checking file name
  800. file_size_re = re.compile(r"^[^ ]+ [^ ]+/[^ ]+ *([0-9]+) .*")
  801. for line in new_lines:
  802. match = file_size_re.match(line)
  803. if match:
  804. file_size = match.groups()[0]
  805. self.resize_lvm(self.adjust_output_size, file_size)
  806. self.adjust_output_size = None
  807. self.tar2_stderr += new_lines
  808. def resize_lvm(self, dev, size):
  809. # FIXME: HACK
  810. try:
  811. subprocess.check_call(
  812. ['sudo', 'lvresize', '-f', '-L', str(size) + 'B', dev],
  813. stdout=open(os.devnull, 'w'), stderr=subprocess.STDOUT)
  814. except subprocess.CalledProcessError as e:
  815. if e.returncode == 3:
  816. # already at the right size
  817. pass
  818. else:
  819. raise
  820. def run(self):
  821. try:
  822. self.__run__()
  823. except Exception as e:
  824. exc_type, exc_value, exc_traceback = sys.exc_info()
  825. # Cleanup children
  826. for process in [self.decompressor_process,
  827. self.decryptor_process,
  828. self.tar2_process]:
  829. if process:
  830. try:
  831. process.terminate()
  832. except OSError:
  833. pass
  834. process.wait()
  835. self.log.error("ERROR: " + unicode(e))
  836. raise
  837. def handle_dir_relocations(self, dirname):
  838. ''' Relocate files in given director when it's already extracted
  839. :param dirname: directory path to handle (relative to backup root),
  840. without trailing slash
  841. '''
  842. for old, new in self.relocate:
  843. if not old.startswith(dirname + '/'):
  844. continue
  845. # if directory is relocated too (most likely is), the file
  846. # is extracted there
  847. if dirname in self.relocate:
  848. old = old.replace(dirname, self.relocate[dirname], 1)
  849. try:
  850. stat_buf = os.stat(new)
  851. if stat.S_ISBLK(stat_buf.st_mode):
  852. # output file is block device (LVM) - adjust its
  853. # size, otherwise it may fail
  854. # from lack of space
  855. self.resize_lvm(new, stat_buf.st_size)
  856. except OSError: # ENOENT
  857. pass
  858. subprocess.check_call(
  859. ['dd', 'if='+old, 'of='+new, 'conv=sparse'])
  860. os.unlink(old)
  861. def cleanup_tar2(self, wait=True, terminate=False):
  862. if self.tar2_process is None:
  863. return
  864. if terminate:
  865. self.tar2_process.terminate()
  866. if wait:
  867. self.tar2_process.wait()
  868. elif self.tar2_process.poll() is None:
  869. return
  870. if self.tar2_process.returncode != 0:
  871. self.collect_tar_output()
  872. self.log.error(
  873. "ERROR: unable to extract files for {0}, tar "
  874. "output:\n {1}".
  875. format(self.tar2_current_file,
  876. "\n ".join(self.tar2_stderr)))
  877. else:
  878. # Finished extracting the tar file
  879. self.collect_tar_output()
  880. self.tar2_process = None
  881. # if that was whole-directory archive, handle
  882. # relocated files now
  883. inner_name = os.path.splitext(self.tar2_current_file)[0]\
  884. .replace(self.base_dir + '/', '')
  885. if os.path.basename(inner_name) == '.':
  886. self.handle_dir_relocations(
  887. os.path.dirname(inner_name))
  888. self.tar2_current_file = None
  889. self.adjust_output_size = None
  890. def __run__(self):
  891. self.log.debug("Started sending thread")
  892. self.log.debug("Moving to dir " + self.base_dir)
  893. os.chdir(self.base_dir)
  894. filename = None
  895. for filename in iter(self.queue.get, None):
  896. if filename in (QUEUE_FINISHED, QUEUE_ERROR):
  897. break
  898. self.log.debug("Extracting file " + filename)
  899. if filename.endswith('.000'):
  900. # next file
  901. self.cleanup_tar2(wait=True, terminate=False)
  902. inner_name = filename.rstrip('.000').replace(
  903. self.base_dir + '/', '')
  904. redirect_stdout = None
  905. if self.relocate and inner_name in self.relocate:
  906. # TODO: add `dd conv=sparse` when removing tar layer
  907. tar2_cmdline = ['tar',
  908. '-%sMvvOf' % ("t" if self.verify_only else "x"),
  909. self.restore_pipe,
  910. inner_name]
  911. output_file = self.relocate[inner_name]
  912. try:
  913. stat_buf = os.stat(output_file)
  914. if stat.S_ISBLK(stat_buf.st_mode):
  915. # output file is block device (LVM) - adjust its
  916. # size during extraction, otherwise it may fail
  917. # from lack of space
  918. self.adjust_output_size = output_file
  919. except OSError: # ENOENT
  920. pass
  921. redirect_stdout = open(output_file, 'w')
  922. elif self.relocate and \
  923. os.path.dirname(inner_name) in self.relocate:
  924. tar2_cmdline = ['tar',
  925. '-%sMf' % ("t" if self.verify_only else "x"),
  926. self.restore_pipe,
  927. '-C', self.relocate[os.path.dirname(inner_name)],
  928. # strip all directories - leave only final filename
  929. '--strip-components', str(inner_name.count(os.sep)),
  930. inner_name]
  931. else:
  932. tar2_cmdline = ['tar',
  933. '-%sMkf' % ("t" if self.verify_only else "x"),
  934. self.restore_pipe,
  935. inner_name]
  936. self.log.debug("Running command " + unicode(tar2_cmdline))
  937. self.tar2_process = subprocess.Popen(tar2_cmdline,
  938. stdin=subprocess.PIPE, stderr=subprocess.PIPE,
  939. stdout=redirect_stdout)
  940. fcntl.fcntl(self.tar2_process.stderr.fileno(), fcntl.F_SETFL,
  941. fcntl.fcntl(self.tar2_process.stderr.fileno(),
  942. fcntl.F_GETFL) | os.O_NONBLOCK)
  943. self.tar2_stderr = []
  944. elif not self.tar2_process:
  945. # Extracting of the current archive failed, skip to the next
  946. # archive
  947. os.remove(filename)
  948. continue
  949. else:
  950. self.collect_tar_output()
  951. self.log.debug("Releasing next chunck")
  952. self.tar2_process.stdin.write("\n")
  953. self.tar2_process.stdin.flush()
  954. self.tar2_current_file = filename
  955. pipe = open(self.restore_pipe, 'wb')
  956. monitor_processes = {
  957. 'vmproc': self.vmproc,
  958. 'addproc': self.tar2_process,
  959. }
  960. common_args = {
  961. 'backup_target': pipe,
  962. 'hmac': None,
  963. 'vmproc': self.vmproc,
  964. 'addproc': self.tar2_process
  965. }
  966. if self.encrypted:
  967. # Start decrypt
  968. self.decryptor_process = subprocess.Popen(
  969. ["openssl", "enc",
  970. "-d",
  971. "-" + self.crypto_algorithm,
  972. "-pass",
  973. "pass:" + self.passphrase] +
  974. (["-z"] if self.compressed else []),
  975. stdin=open(filename, 'rb'),
  976. stdout=subprocess.PIPE)
  977. in_stream = self.decryptor_process.stdout
  978. monitor_processes['decryptor'] = self.decryptor_process
  979. elif self.compressed:
  980. self.decompressor_process = subprocess.Popen(
  981. ["gzip", "-d"],
  982. stdin=open(filename, 'rb'),
  983. stdout=subprocess.PIPE)
  984. in_stream = self.decompressor_process.stdout
  985. monitor_processes['decompresor'] = self.decompressor_process
  986. else:
  987. in_stream = open(filename, 'rb')
  988. run_error = handle_streams(
  989. in_stream,
  990. {'target': pipe},
  991. monitor_processes,
  992. progress_callback=self.progress_callback)
  993. try:
  994. pipe.close()
  995. except IOError as e:
  996. if e.errno == errno.EPIPE:
  997. self.log.debug(
  998. "Got EPIPE while closing pipe to "
  999. "the inner tar process")
  1000. # ignore the error
  1001. else:
  1002. raise
  1003. if run_error:
  1004. if run_error == "target":
  1005. self.collect_tar_output()
  1006. details = "\n".join(self.tar2_stderr)
  1007. else:
  1008. details = "%s failed" % run_error
  1009. self.log.error("Error while processing '{}': {}".format(
  1010. self.tar2_current_file, details))
  1011. self.cleanup_tar2(wait=True, terminate=True)
  1012. # Delete the file as we don't need it anymore
  1013. self.log.debug("Removing file " + filename)
  1014. os.remove(filename)
  1015. os.unlink(self.restore_pipe)
  1016. self.cleanup_tar2(wait=True, terminate=(filename == QUEUE_ERROR))
  1017. self.log.debug("Finished extracting thread")
  1018. class ExtractWorker3(ExtractWorker2):
  1019. def __init__(self, queue, base_dir, passphrase, encrypted,
  1020. progress_callback, vmproc=None,
  1021. compressed=False, crypto_algorithm=DEFAULT_CRYPTO_ALGORITHM,
  1022. compression_filter=None, verify_only=False, relocate=None):
  1023. super(ExtractWorker3, self).__init__(queue, base_dir, passphrase,
  1024. encrypted,
  1025. progress_callback, vmproc,
  1026. compressed, crypto_algorithm,
  1027. verify_only, relocate)
  1028. self.compression_filter = compression_filter
  1029. os.unlink(self.restore_pipe)
  1030. def __run__(self):
  1031. self.log.debug("Started sending thread")
  1032. self.log.debug("Moving to dir " + self.base_dir)
  1033. os.chdir(self.base_dir)
  1034. filename = None
  1035. input_pipe = None
  1036. for filename in iter(self.queue.get, None):
  1037. if filename in (QUEUE_FINISHED, QUEUE_ERROR):
  1038. break
  1039. self.log.debug("Extracting file " + filename)
  1040. if filename.endswith('.000'):
  1041. # next file
  1042. if self.tar2_process is not None:
  1043. input_pipe.close()
  1044. self.cleanup_tar2(wait=True, terminate=False)
  1045. inner_name = filename.rstrip('.000').replace(
  1046. self.base_dir + '/', '')
  1047. redirect_stdout = None
  1048. if self.relocate and inner_name in self.relocate:
  1049. # TODO: add dd conv=sparse when removing tar layer
  1050. tar2_cmdline = ['tar',
  1051. '-%svvO' % ("t" if self.verify_only else "x"),
  1052. inner_name]
  1053. output_file = self.relocate[inner_name]
  1054. try:
  1055. stat_buf = os.stat(output_file)
  1056. if stat.S_ISBLK(stat_buf.st_mode):
  1057. # output file is block device (LVM) - adjust its
  1058. # size during extraction, otherwise it may fail
  1059. # from lack of space
  1060. self.adjust_output_size = output_file
  1061. except OSError: # ENOENT
  1062. pass
  1063. redirect_stdout = open(output_file, 'w')
  1064. elif self.relocate and \
  1065. os.path.dirname(inner_name) in self.relocate:
  1066. tar2_cmdline = ['tar',
  1067. '-%s' % ("t" if self.verify_only else "x"),
  1068. '-C', self.relocate[os.path.dirname(inner_name)],
  1069. # strip all directories - leave only final filename
  1070. '--strip-components', str(inner_name.count(os.sep)),
  1071. inner_name]
  1072. else:
  1073. tar2_cmdline = ['tar',
  1074. '-%sk' % ("t" if self.verify_only else "x"),
  1075. inner_name]
  1076. if self.compressed:
  1077. if self.compression_filter:
  1078. tar2_cmdline.insert(-1,
  1079. "--use-compress-program=%s" %
  1080. self.compression_filter)
  1081. else:
  1082. tar2_cmdline.insert(-1, "--use-compress-program=%s" %
  1083. DEFAULT_COMPRESSION_FILTER)
  1084. self.log.debug("Running command " + unicode(tar2_cmdline))
  1085. if self.encrypted:
  1086. # Start decrypt
  1087. self.decryptor_process = subprocess.Popen(
  1088. ["openssl", "enc",
  1089. "-d",
  1090. "-" + self.crypto_algorithm,
  1091. "-pass",
  1092. "pass:" + self.passphrase],
  1093. stdin=subprocess.PIPE,
  1094. stdout=subprocess.PIPE)
  1095. self.tar2_process = subprocess.Popen(
  1096. tar2_cmdline,
  1097. stdin=self.decryptor_process.stdout,
  1098. stdout=redirect_stdout,
  1099. stderr=subprocess.PIPE)
  1100. input_pipe = self.decryptor_process.stdin
  1101. else:
  1102. self.tar2_process = subprocess.Popen(
  1103. tar2_cmdline,
  1104. stdin=subprocess.PIPE,
  1105. stdout=redirect_stdout,
  1106. stderr=subprocess.PIPE)
  1107. input_pipe = self.tar2_process.stdin
  1108. fcntl.fcntl(self.tar2_process.stderr.fileno(), fcntl.F_SETFL,
  1109. fcntl.fcntl(self.tar2_process.stderr.fileno(),
  1110. fcntl.F_GETFL) | os.O_NONBLOCK)
  1111. self.tar2_stderr = []
  1112. elif not self.tar2_process:
  1113. # Extracting of the current archive failed, skip to the next
  1114. # archive
  1115. os.remove(filename)
  1116. continue
  1117. else:
  1118. (basename, ext) = os.path.splitext(self.tar2_current_file)
  1119. previous_chunk_number = int(ext[1:])
  1120. expected_filename = basename + '.%03d' % (
  1121. previous_chunk_number+1)
  1122. if expected_filename != filename:
  1123. self.cleanup_tar2(wait=True, terminate=True)
  1124. self.log.error(
  1125. 'Unexpected file in archive: {}, expected {}'.format(
  1126. filename, expected_filename))
  1127. os.remove(filename)
  1128. continue
  1129. self.log.debug("Releasing next chunck")
  1130. self.tar2_current_file = filename
  1131. run_error = handle_streams(
  1132. open(filename, 'rb'),
  1133. {'target': input_pipe},
  1134. {'vmproc': self.vmproc,
  1135. 'addproc': self.tar2_process,
  1136. 'decryptor': self.decryptor_process,
  1137. },
  1138. progress_callback=self.progress_callback)
  1139. if run_error:
  1140. if run_error == "target":
  1141. self.collect_tar_output()
  1142. details = "\n".join(self.tar2_stderr)
  1143. else:
  1144. details = "%s failed" % run_error
  1145. if self.decryptor_process:
  1146. self.decryptor_process.terminate()
  1147. self.decryptor_process.wait()
  1148. self.decryptor_process = None
  1149. self.log.error("Error while processing '{}': {}".format(
  1150. self.tar2_current_file, details))
  1151. self.cleanup_tar2(wait=True, terminate=True)
  1152. # Delete the file as we don't need it anymore
  1153. self.log.debug("Removing file " + filename)
  1154. os.remove(filename)
  1155. if self.tar2_process is not None:
  1156. input_pipe.close()
  1157. if filename == QUEUE_ERROR:
  1158. if self.decryptor_process:
  1159. self.decryptor_process.terminate()
  1160. self.decryptor_process.wait()
  1161. self.decryptor_process = None
  1162. self.cleanup_tar2(terminate=(filename == QUEUE_ERROR))
  1163. self.log.debug("Finished extracting thread")
  1164. def get_supported_hmac_algo(hmac_algorithm=None):
  1165. # Start with provided default
  1166. if hmac_algorithm:
  1167. yield hmac_algorithm
  1168. proc = subprocess.Popen(['openssl', 'list-message-digest-algorithms'],
  1169. stdout=subprocess.PIPE)
  1170. for algo in proc.stdout.readlines():
  1171. if '=>' in algo:
  1172. continue
  1173. yield algo.strip()
  1174. proc.wait()
  1175. class BackupRestoreOptions(object):
  1176. def __init__(self):
  1177. #: use default NetVM if the one referenced in backup do not exists on
  1178. # the host
  1179. self.use_default_netvm = True
  1180. #: set NetVM to "none" if the one referenced in backup do not exists
  1181. # on the host
  1182. self.use_none_netvm = False
  1183. #: set template to default if the one referenced in backup do not
  1184. # exists on the host
  1185. self.use_default_template = True
  1186. #: use default kernel if the one referenced in backup do not exists
  1187. # on the host
  1188. self.use_default_kernel = True
  1189. #: restore dom0 home
  1190. self.dom0_home = True
  1191. #: dictionary how what templates should be used instead of those
  1192. # referenced in backup
  1193. self.replace_template = {}
  1194. #: restore dom0 home even if username is different
  1195. self.ignore_username_mismatch = False
  1196. #: do not restore data, only verify backup integrity
  1197. self.verify_only = False
  1198. #: automatically rename VM during restore, when it would conflict
  1199. # with existing one
  1200. self.rename_conflicting = True
  1201. #: list of VM names to exclude
  1202. self.exclude = []
  1203. #: restore VMs into selected storage pool
  1204. self.override_pool = None
  1205. class BackupRestore(object):
  1206. """Usage:
  1207. >>> restore_op = BackupRestore(...)
  1208. >>> # adjust restore_op.options here
  1209. >>> restore_info = restore_op.get_restore_info()
  1210. >>> # manipulate restore_info to select VMs to restore here
  1211. >>> restore_op.restore_do(restore_info)
  1212. """
  1213. class VMToRestore(object):
  1214. #: VM excluded from restore by user
  1215. EXCLUDED = object()
  1216. #: VM with such name already exists on the host
  1217. ALREADY_EXISTS = object()
  1218. #: NetVM used by the VM does not exists on the host
  1219. MISSING_NETVM = object()
  1220. #: TemplateVM used by the VM does not exists on the host
  1221. MISSING_TEMPLATE = object()
  1222. #: Kernel used by the VM does not exists on the host
  1223. MISSING_KERNEL = object()
  1224. def __init__(self, vm):
  1225. self.vm = vm
  1226. if 'backup-path' in vm.features:
  1227. self.subdir = vm.features['backup-path']
  1228. else:
  1229. self.subdir = None
  1230. if 'backup-size' in vm.features and vm.features['backup-size']:
  1231. self.size = int(vm.features['backup-size'])
  1232. else:
  1233. self.size = 0
  1234. self.problems = set()
  1235. if hasattr(vm, 'template') and vm.template:
  1236. self.template = vm.template.name
  1237. else:
  1238. self.template = None
  1239. if vm.netvm:
  1240. self.netvm = vm.netvm.name
  1241. else:
  1242. self.netvm = None
  1243. self.name = vm.name
  1244. self.orig_template = None
  1245. self.restored_vm = None
  1246. @property
  1247. def good_to_go(self):
  1248. return len(self.problems) == 0
  1249. class Dom0ToRestore(VMToRestore):
  1250. #: backup was performed on system with different dom0 username
  1251. USERNAME_MISMATCH = object()
  1252. def __init__(self, vm, subdir=None):
  1253. super(BackupRestore.Dom0ToRestore, self).__init__(vm)
  1254. if subdir:
  1255. self.subdir = subdir
  1256. self.username = os.path.basename(subdir)
  1257. def __init__(self, app, backup_location, backup_vm, passphrase):
  1258. super(BackupRestore, self).__init__()
  1259. #: qubes.Qubes instance
  1260. self.app = app
  1261. #: options how the backup should be restored
  1262. self.options = BackupRestoreOptions()
  1263. #: VM from which backup should be retrieved
  1264. self.backup_vm = backup_vm
  1265. if backup_vm and backup_vm.qid == 0:
  1266. self.backup_vm = None
  1267. #: backup path, inside VM pointed by :py:attr:`backup_vm`
  1268. self.backup_location = backup_location
  1269. #: passphrase protecting backup integrity and optionally decryption
  1270. self.passphrase = passphrase
  1271. #: temporary directory used to extract the data before moving to the
  1272. # final location; should be on the same filesystem as /var/lib/qubes
  1273. self.tmpdir = tempfile.mkdtemp(prefix="restore", dir="/var/tmp")
  1274. #: list of processes (Popen objects) to kill on cancel
  1275. self.processes_to_kill_on_cancel = []
  1276. #: is the backup operation canceled
  1277. self.canceled = False
  1278. #: report restore progress, called with one argument - percents of
  1279. # data restored
  1280. # FIXME: convert to float [0,1]
  1281. self.progress_callback = None
  1282. self.log = logging.getLogger('qubes.backup')
  1283. #: basic information about the backup
  1284. self.header_data = self._retrieve_backup_header()
  1285. #: VMs included in the backup
  1286. self.backup_app = self._process_qubes_xml()
  1287. def cancel(self):
  1288. """Cancel running backup operation. Can be called from another thread.
  1289. """
  1290. self.canceled = True
  1291. for proc in self.processes_to_kill_on_cancel:
  1292. try:
  1293. proc.terminate()
  1294. except OSError:
  1295. pass
  1296. def _start_retrieval_process(self, filelist, limit_count, limit_bytes):
  1297. """Retrieve backup stream and extract it to :py:attr:`tmpdir`
  1298. :param filelist: list of files to extract; listing directory name
  1299. will extract the whole directory; use empty list to extract the whole
  1300. archive
  1301. :param limit_count: maximum number of files to extract
  1302. :param limit_bytes: maximum size of extracted data
  1303. :return: a touple of (Popen object of started process, file-like
  1304. object for reading extracted files list, file-like object for reading
  1305. errors)
  1306. """
  1307. vmproc = None
  1308. if self.backup_vm is not None:
  1309. # If APPVM, STDOUT is a PIPE
  1310. vmproc = self.backup_vm.run_service('qubes.Restore',
  1311. passio_popen=True, passio_stderr=True)
  1312. vmproc.stdin.write(
  1313. self.backup_location.replace("\r", "").replace("\n", "") + "\n")
  1314. # Send to tar2qfile the VMs that should be extracted
  1315. vmproc.stdin.write(" ".join(filelist) + "\n")
  1316. self.processes_to_kill_on_cancel.append(vmproc)
  1317. backup_stdin = vmproc.stdout
  1318. tar1_command = ['/usr/libexec/qubes/qfile-dom0-unpacker',
  1319. str(os.getuid()), self.tmpdir, '-v']
  1320. else:
  1321. backup_stdin = open(self.backup_location, 'rb')
  1322. tar1_command = ['tar',
  1323. '-ixv',
  1324. '-C', self.tmpdir] + filelist
  1325. tar1_env = os.environ.copy()
  1326. tar1_env['UPDATES_MAX_BYTES'] = str(limit_bytes)
  1327. tar1_env['UPDATES_MAX_FILES'] = str(limit_count)
  1328. self.log.debug("Run command" + unicode(tar1_command))
  1329. command = subprocess.Popen(
  1330. tar1_command,
  1331. stdin=backup_stdin,
  1332. stdout=vmproc.stdin if vmproc else subprocess.PIPE,
  1333. stderr=subprocess.PIPE,
  1334. env=tar1_env)
  1335. self.processes_to_kill_on_cancel.append(command)
  1336. # qfile-dom0-unpacker output filelist on stderr
  1337. # and have stdout connected to the VM), while tar output filelist
  1338. # on stdout
  1339. if self.backup_vm:
  1340. filelist_pipe = command.stderr
  1341. # let qfile-dom0-unpacker hold the only open FD to the write end of
  1342. # pipe, otherwise qrexec-client will not receive EOF when
  1343. # qfile-dom0-unpacker terminates
  1344. vmproc.stdin.close()
  1345. else:
  1346. filelist_pipe = command.stdout
  1347. if self.backup_vm:
  1348. error_pipe = vmproc.stderr
  1349. else:
  1350. error_pipe = command.stderr
  1351. return command, filelist_pipe, error_pipe
  1352. def _verify_hmac(self, filename, hmacfile, algorithm=None):
  1353. def load_hmac(hmac_text):
  1354. hmac_text = hmac_text.strip().split("=")
  1355. if len(hmac_text) > 1:
  1356. hmac_text = hmac_text[1].strip()
  1357. else:
  1358. raise qubes.exc.QubesException(
  1359. "ERROR: invalid hmac file content")
  1360. return hmac_text
  1361. if algorithm is None:
  1362. algorithm = self.header_data.hmac_algorithm
  1363. passphrase = self.passphrase.encode('utf-8')
  1364. self.log.debug("Verifying file {}".format(filename))
  1365. if hmacfile != filename + ".hmac":
  1366. raise qubes.exc.QubesException(
  1367. "ERROR: expected hmac for {}, but got {}".
  1368. format(filename, hmacfile))
  1369. hmac_proc = subprocess.Popen(
  1370. ["openssl", "dgst", "-" + algorithm, "-hmac", passphrase],
  1371. stdin=open(os.path.join(self.tmpdir, filename), 'rb'),
  1372. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  1373. hmac_stdout, hmac_stderr = hmac_proc.communicate()
  1374. if len(hmac_stderr) > 0:
  1375. raise qubes.exc.QubesException(
  1376. "ERROR: verify file {0}: {1}".format(filename, hmac_stderr))
  1377. else:
  1378. self.log.debug("Loading hmac for file {}".format(filename))
  1379. hmac = load_hmac(open(os.path.join(self.tmpdir, hmacfile),
  1380. 'r').read())
  1381. if len(hmac) > 0 and load_hmac(hmac_stdout) == hmac:
  1382. os.unlink(os.path.join(self.tmpdir, hmacfile))
  1383. self.log.debug(
  1384. "File verification OK -> Sending file {}".format(filename))
  1385. return True
  1386. else:
  1387. raise qubes.exc.QubesException(
  1388. "ERROR: invalid hmac for file {0}: {1}. "
  1389. "Is the passphrase correct?".
  1390. format(filename, load_hmac(hmac_stdout)))
  1391. def _retrieve_backup_header(self):
  1392. """Retrieve backup header and qubes.xml. Only backup header is
  1393. analyzed, qubes.xml is left as-is
  1394. (not even verified/decrypted/uncompressed)
  1395. :return header_data
  1396. :rtype :py:class:`BackupHeader`
  1397. """
  1398. if not self.backup_vm and os.path.exists(
  1399. os.path.join(self.backup_location, 'qubes.xml')):
  1400. # backup format version 1 doesn't have header
  1401. header_data = BackupHeader()
  1402. header_data.version = 1
  1403. return header_data
  1404. (retrieve_proc, filelist_pipe, error_pipe) = \
  1405. self._start_retrieval_process(
  1406. ['backup-header', 'backup-header.hmac',
  1407. 'qubes.xml.000', 'qubes.xml.000.hmac'], 4, 1024 * 1024)
  1408. expect_tar_error = False
  1409. filename = filelist_pipe.readline().strip()
  1410. hmacfile = filelist_pipe.readline().strip()
  1411. # tar output filename before actually extracting it, so wait for the
  1412. # next one before trying to access it
  1413. if not self.backup_vm:
  1414. filelist_pipe.readline().strip()
  1415. self.log.debug("Got backup header and hmac: {}, {}".format(
  1416. filename, hmacfile))
  1417. if not filename or filename == "EOF" or \
  1418. not hmacfile or hmacfile == "EOF":
  1419. retrieve_proc.wait()
  1420. proc_error_msg = error_pipe.read(MAX_STDERR_BYTES)
  1421. raise qubes.exc.QubesException(
  1422. "Premature end of archive while receiving "
  1423. "backup header. Process output:\n" + proc_error_msg)
  1424. file_ok = False
  1425. hmac_algorithm = DEFAULT_HMAC_ALGORITHM
  1426. for hmac_algo in get_supported_hmac_algo(hmac_algorithm):
  1427. try:
  1428. if self._verify_hmac(filename, hmacfile, hmac_algo):
  1429. file_ok = True
  1430. hmac_algorithm = hmac_algo
  1431. break
  1432. except qubes.exc.QubesException:
  1433. # Ignore exception here, try the next algo
  1434. pass
  1435. if not file_ok:
  1436. raise qubes.exc.QubesException(
  1437. "Corrupted backup header (hmac verification "
  1438. "failed). Is the password correct?")
  1439. if os.path.basename(filename) == HEADER_FILENAME:
  1440. filename = os.path.join(self.tmpdir, filename)
  1441. header_data = BackupHeader(open(filename, 'r').read())
  1442. os.unlink(filename)
  1443. else:
  1444. # if no header found, create one with guessed HMAC algo
  1445. header_data = BackupHeader(
  1446. version=2,
  1447. hmac_algorithm=hmac_algorithm,
  1448. # place explicitly this value, because it is what format_version
  1449. # 2 have
  1450. crypto_algorithm='aes-256-cbc',
  1451. # TODO: set encrypted to something...
  1452. )
  1453. # when tar do not find expected file in archive, it exit with
  1454. # code 2. This will happen because we've requested backup-header
  1455. # file, but the archive do not contain it. Ignore this particular
  1456. # error.
  1457. if not self.backup_vm:
  1458. expect_tar_error = True
  1459. if retrieve_proc.wait() != 0 and not expect_tar_error:
  1460. raise qubes.exc.QubesException(
  1461. "unable to read the qubes backup file {0} ({1}): {2}".format(
  1462. self.backup_location,
  1463. retrieve_proc.wait(),
  1464. error_pipe.read(MAX_STDERR_BYTES)
  1465. ))
  1466. if retrieve_proc in self.processes_to_kill_on_cancel:
  1467. self.processes_to_kill_on_cancel.remove(retrieve_proc)
  1468. # wait for other processes (if any)
  1469. for proc in self.processes_to_kill_on_cancel:
  1470. if proc.wait() != 0:
  1471. raise qubes.exc.QubesException(
  1472. "Backup header retrieval failed (exit code {})".format(
  1473. proc.wait())
  1474. )
  1475. return header_data
  1476. def _start_inner_extraction_worker(self, queue, relocate):
  1477. """Start a worker process, extracting inner layer of bacup archive,
  1478. extract them to :py:attr:`tmpdir`.
  1479. End the data by pushing QUEUE_FINISHED or QUEUE_ERROR to the queue.
  1480. :param queue :py:class:`Queue` object to handle files from
  1481. """
  1482. # Setup worker to extract encrypted data chunks to the restore dirs
  1483. # Create the process here to pass it options extracted from
  1484. # backup header
  1485. extractor_params = {
  1486. 'queue': queue,
  1487. 'base_dir': self.tmpdir,
  1488. 'passphrase': self.passphrase,
  1489. 'encrypted': self.header_data.encrypted,
  1490. 'compressed': self.header_data.compressed,
  1491. 'crypto_algorithm': self.header_data.crypto_algorithm,
  1492. 'verify_only': self.options.verify_only,
  1493. 'progress_callback': self.progress_callback,
  1494. 'relocate': relocate,
  1495. }
  1496. self.log.debug('Starting extraction worker in {}, file relocation '
  1497. 'map: {!r}'.format(self.tmpdir, relocate))
  1498. format_version = self.header_data.version
  1499. if format_version == 2:
  1500. extract_proc = ExtractWorker2(**extractor_params)
  1501. elif format_version in [3, 4]:
  1502. extractor_params['compression_filter'] = \
  1503. self.header_data.compression_filter
  1504. extract_proc = ExtractWorker3(**extractor_params)
  1505. else:
  1506. raise NotImplementedError(
  1507. "Backup format version %d not supported" % format_version)
  1508. extract_proc.start()
  1509. return extract_proc
  1510. def _process_qubes_xml(self):
  1511. """Verify, unpack and load qubes.xml. Possibly convert its format if
  1512. necessary. It expect that :py:attr:`header_data` is already populated,
  1513. and :py:meth:`retrieve_backup_header` was called.
  1514. """
  1515. if self.header_data.version == 1:
  1516. backup_app = qubes.core2migration.Core2Qubes(
  1517. os.path.join(self.backup_location, 'qubes.xml'),
  1518. offline_mode=True)
  1519. return backup_app
  1520. else:
  1521. self._verify_hmac("qubes.xml.000", "qubes.xml.000.hmac")
  1522. queue = Queue()
  1523. queue.put("qubes.xml.000")
  1524. queue.put(QUEUE_FINISHED)
  1525. extract_proc = self._start_inner_extraction_worker(queue, None)
  1526. extract_proc.join()
  1527. if extract_proc.exitcode != 0:
  1528. raise qubes.exc.QubesException(
  1529. "unable to extract the qubes backup. "
  1530. "Check extracting process errors.")
  1531. if self.header_data.version in [2, 3]:
  1532. backup_app = qubes.core2migration.Core2Qubes(
  1533. os.path.join(self.tmpdir, 'qubes.xml'), offline_mode=True)
  1534. else:
  1535. backup_app = qubes.Qubes(os.path.join(self.tmpdir, 'qubes.xml'),
  1536. offline_mode=True)
  1537. # Not needed anymore - all the data stored in backup_app
  1538. os.unlink(os.path.join(self.tmpdir, 'qubes.xml'))
  1539. return backup_app
  1540. def _restore_vm_dirs(self, vms_dirs, vms_size, relocate):
  1541. # Currently each VM consists of at most 7 archives (count
  1542. # file_to_backup calls in backup_prepare()), but add some safety
  1543. # margin for further extensions. Each archive is divided into 100MB
  1544. # chunks. Additionally each file have own hmac file. So assume upper
  1545. # limit as 2*(10*COUNT_OF_VMS+TOTAL_SIZE/100MB)
  1546. limit_count = str(2 * (10 * len(vms_dirs) +
  1547. int(vms_size / (100 * 1024 * 1024))))
  1548. self.log.debug("Working in temporary dir:" + self.tmpdir)
  1549. self.log.info(
  1550. "Extracting data: " + size_to_human(vms_size) + " to restore")
  1551. # retrieve backup from the backup stream (either VM, or dom0 file)
  1552. (retrieve_proc, filelist_pipe, error_pipe) = \
  1553. self._start_retrieval_process(
  1554. vms_dirs, limit_count, vms_size)
  1555. to_extract = Queue()
  1556. # extract data retrieved by retrieve_proc
  1557. extract_proc = self._start_inner_extraction_worker(
  1558. to_extract, relocate)
  1559. try:
  1560. filename = None
  1561. nextfile = None
  1562. while True:
  1563. if self.canceled:
  1564. break
  1565. if not extract_proc.is_alive():
  1566. retrieve_proc.terminate()
  1567. retrieve_proc.wait()
  1568. if retrieve_proc in self.processes_to_kill_on_cancel:
  1569. self.processes_to_kill_on_cancel.remove(retrieve_proc)
  1570. # wait for other processes (if any)
  1571. for proc in self.processes_to_kill_on_cancel:
  1572. proc.wait()
  1573. break
  1574. if nextfile is not None:
  1575. filename = nextfile
  1576. else:
  1577. filename = filelist_pipe.readline().strip()
  1578. self.log.debug("Getting new file:" + filename)
  1579. if not filename or filename == "EOF":
  1580. break
  1581. hmacfile = filelist_pipe.readline().strip()
  1582. if self.canceled:
  1583. break
  1584. # if reading archive directly with tar, wait for next filename -
  1585. # tar prints filename before processing it, so wait for
  1586. # the next one to be sure that whole file was extracted
  1587. if not self.backup_vm:
  1588. nextfile = filelist_pipe.readline().strip()
  1589. self.log.debug("Getting hmac:" + hmacfile)
  1590. if not hmacfile or hmacfile == "EOF":
  1591. # Premature end of archive, either of tar1_command or
  1592. # vmproc exited with error
  1593. break
  1594. if not any(map(lambda x: filename.startswith(x), vms_dirs)):
  1595. self.log.debug("Ignoring VM not selected for restore")
  1596. os.unlink(os.path.join(self.tmpdir, filename))
  1597. os.unlink(os.path.join(self.tmpdir, hmacfile))
  1598. continue
  1599. if self._verify_hmac(filename, hmacfile):
  1600. to_extract.put(os.path.join(self.tmpdir, filename))
  1601. if self.canceled:
  1602. raise BackupCanceledError("Restore canceled",
  1603. tmpdir=self.tmpdir)
  1604. if retrieve_proc.wait() != 0:
  1605. raise qubes.exc.QubesException(
  1606. "unable to read the qubes backup file {0}: {1}"
  1607. .format(self.backup_location, error_pipe.read(
  1608. MAX_STDERR_BYTES)))
  1609. # wait for other processes (if any)
  1610. for proc in self.processes_to_kill_on_cancel:
  1611. proc.wait()
  1612. if proc.returncode != 0:
  1613. raise qubes.exc.QubesException(
  1614. "Backup completed, but VM receiving it reported an error "
  1615. "(exit code {})".format(proc.returncode))
  1616. if filename and filename != "EOF":
  1617. raise qubes.exc.QubesException(
  1618. "Premature end of archive, the last file was %s" % filename)
  1619. except:
  1620. to_extract.put(QUEUE_ERROR)
  1621. extract_proc.join()
  1622. raise
  1623. else:
  1624. to_extract.put(QUEUE_FINISHED)
  1625. self.log.debug("Waiting for the extraction process to finish...")
  1626. extract_proc.join()
  1627. self.log.debug("Extraction process finished with code: {}".format(
  1628. extract_proc.exitcode))
  1629. if extract_proc.exitcode != 0:
  1630. raise qubes.exc.QubesException(
  1631. "unable to extract the qubes backup. "
  1632. "Check extracting process errors.")
  1633. def generate_new_name_for_conflicting_vm(self, orig_name, restore_info):
  1634. number = 1
  1635. if len(orig_name) > 29:
  1636. orig_name = orig_name[0:29]
  1637. new_name = orig_name
  1638. while (new_name in restore_info.keys() or
  1639. new_name in map(lambda x: x.name,
  1640. restore_info.values()) or
  1641. new_name in self.app.domains):
  1642. new_name = str('{}{}'.format(orig_name, number))
  1643. number += 1
  1644. if number == 100:
  1645. # give up
  1646. return None
  1647. return new_name
  1648. def restore_info_verify(self, restore_info):
  1649. for vm in restore_info.keys():
  1650. if vm in ['dom0']:
  1651. continue
  1652. vm_info = restore_info[vm]
  1653. assert isinstance(vm_info, self.VMToRestore)
  1654. vm_info.problems.clear()
  1655. if vm in self.options.exclude:
  1656. vm_info.problems.add(self.VMToRestore.EXCLUDED)
  1657. if not self.options.verify_only and \
  1658. vm_info.name in self.app.domains:
  1659. if self.options.rename_conflicting:
  1660. new_name = self.generate_new_name_for_conflicting_vm(
  1661. vm, restore_info
  1662. )
  1663. if new_name is not None:
  1664. vm_info.name = new_name
  1665. else:
  1666. vm_info.problems.add(self.VMToRestore.ALREADY_EXISTS)
  1667. else:
  1668. vm_info.problems.add(self.VMToRestore.ALREADY_EXISTS)
  1669. # check template
  1670. if vm_info.template:
  1671. template_name = vm_info.template
  1672. try:
  1673. host_template = self.app.domains[template_name]
  1674. except KeyError:
  1675. host_template = None
  1676. if not host_template \
  1677. or not isinstance(host_template,
  1678. qubes.vm.templatevm.TemplateVM):
  1679. # Maybe the (custom) template is in the backup?
  1680. if not (template_name in restore_info.keys() and
  1681. restore_info[template_name].good_to_go and
  1682. isinstance(restore_info[template_name].vm,
  1683. qubes.vm.templatevm.TemplateVM)):
  1684. if self.options.use_default_template and \
  1685. self.app.default_template:
  1686. if vm_info.orig_template is None:
  1687. vm_info.orig_template = template_name
  1688. vm_info.template = self.app.default_template.name
  1689. else:
  1690. vm_info.problems.add(
  1691. self.VMToRestore.MISSING_TEMPLATE)
  1692. # check netvm
  1693. if not vm_info.vm.property_is_default('netvm') and vm_info.netvm:
  1694. netvm_name = vm_info.netvm
  1695. try:
  1696. netvm_on_host = self.app.domains[netvm_name]
  1697. except KeyError:
  1698. netvm_on_host = None
  1699. # No netvm on the host?
  1700. if not ((netvm_on_host is not None)
  1701. and netvm_on_host.provides_network):
  1702. # Maybe the (custom) netvm is in the backup?
  1703. if not (netvm_name in restore_info.keys() and
  1704. restore_info[netvm_name].good_to_go and
  1705. restore_info[netvm_name].vm.provides_network):
  1706. if self.options.use_default_netvm:
  1707. vm_info.vm.netvm = qubes.property.DEFAULT
  1708. elif self.options.use_none_netvm:
  1709. vm_info.netvm = None
  1710. else:
  1711. vm_info.problems.add(self.VMToRestore.MISSING_NETVM)
  1712. # check kernel
  1713. if hasattr(vm_info.vm, 'kernel'):
  1714. installed_kernels = os.listdir(os.path.join(
  1715. qubes.config.qubes_base_dir,
  1716. qubes.config.system_path['qubes_kernels_base_dir']))
  1717. # if uses default kernel - do not validate it
  1718. # allow kernel=None only for HVM,
  1719. # otherwise require valid kernel
  1720. if not (vm_info.vm.property_is_default('kernel')
  1721. or (not vm_info.vm.kernel and vm_info.vm.hvm)
  1722. or vm_info.vm.kernel in installed_kernels):
  1723. if self.options.use_default_kernel:
  1724. vm_info.vm.kernel = qubes.property.DEFAULT
  1725. else:
  1726. vm_info.problems.add(self.VMToRestore.MISSING_KERNEL)
  1727. return restore_info
  1728. def _is_vm_included_in_backup_v1(self, check_vm):
  1729. if check_vm.qid == 0:
  1730. return os.path.exists(
  1731. os.path.join(self.backup_location, 'dom0-home'))
  1732. # DisposableVM
  1733. if check_vm.dir_path is None:
  1734. return False
  1735. backup_vm_dir_path = check_vm.dir_path.replace(
  1736. qubes.config.system_path["qubes_base_dir"], self.backup_location)
  1737. if os.path.exists(backup_vm_dir_path):
  1738. return True
  1739. else:
  1740. return False
  1741. @staticmethod
  1742. def _is_vm_included_in_backup_v2(check_vm):
  1743. if 'backup-content' in check_vm.features:
  1744. return check_vm.features['backup-content']
  1745. else:
  1746. return False
  1747. def _find_template_name(self, template):
  1748. if template in self.options.replace_template:
  1749. return self.options.replace_template[template]
  1750. return template
  1751. def _is_vm_included_in_backup(self, vm):
  1752. if self.header_data.version == 1:
  1753. return self._is_vm_included_in_backup_v1(vm)
  1754. elif self.header_data.version in [2, 3, 4]:
  1755. return self._is_vm_included_in_backup_v2(vm)
  1756. else:
  1757. raise qubes.exc.QubesException(
  1758. "Unknown backup format version: {}".format(
  1759. self.header_data.version))
  1760. def get_restore_info(self):
  1761. # Format versions:
  1762. # 1 - Qubes R1, Qubes R2 beta1, beta2
  1763. # 2 - Qubes R2 beta3+
  1764. vms_to_restore = {}
  1765. for vm in self.backup_app.domains:
  1766. if vm.qid == 0:
  1767. # Handle dom0 as special case later
  1768. continue
  1769. if self._is_vm_included_in_backup(vm):
  1770. self.log.debug("{} is included in backup".format(vm.name))
  1771. vms_to_restore[vm.name] = self.VMToRestore(vm)
  1772. if hasattr(vm, 'template'):
  1773. templatevm_name = self._find_template_name(
  1774. vm.template.name)
  1775. vms_to_restore[vm.name].template = templatevm_name
  1776. # Set to None to not confuse QubesVm object from backup
  1777. # collection with host collection (further in clone_attrs).
  1778. vm.netvm = None
  1779. vms_to_restore = self.restore_info_verify(vms_to_restore)
  1780. # ...and dom0 home
  1781. if self.options.dom0_home and \
  1782. self._is_vm_included_in_backup(self.backup_app.domains[0]):
  1783. vm = self.backup_app.domains[0]
  1784. if self.header_data.version == 1:
  1785. subdir = os.listdir(os.path.join(self.backup_location,
  1786. 'dom0-home'))[0]
  1787. else:
  1788. subdir = None
  1789. vms_to_restore['dom0'] = self.Dom0ToRestore(vm, subdir)
  1790. local_user = grp.getgrnam('qubes').gr_mem[0]
  1791. if vms_to_restore['dom0'].username != local_user:
  1792. if not self.options.ignore_username_mismatch:
  1793. vms_to_restore['dom0'].problems.add(
  1794. self.Dom0ToRestore.USERNAME_MISMATCH)
  1795. return vms_to_restore
  1796. @staticmethod
  1797. def get_restore_summary(restore_info):
  1798. fields = {
  1799. "qid": {"func": "vm.qid"},
  1800. "name": {"func": "('[' if isinstance(vm, qubes.vm.templatevm.TemplateVM) else '')\
  1801. + ('{' if vm.provides_network else '')\
  1802. + vm.name \
  1803. + (']' if isinstance(vm, qubes.vm.templatevm.TemplateVM) else '')\
  1804. + ('}' if vm.provides_network else '')"},
  1805. "type": {"func": "'Tpl' if isinstance(vm, qubes.vm.templatevm.TemplateVM) else \
  1806. 'App' if isinstance(vm, qubes.vm.appvm.AppVM) else \
  1807. vm.__class__.__name__.replace('VM','')"},
  1808. "updbl": {"func": "'Yes' if vm.updateable else ''"},
  1809. "template": {"func": "'n/a' if not hasattr(vm, 'template') "
  1810. "else vm_info.template"},
  1811. "netvm": {"func": "('*' if vm.property_is_default('netvm') else '') +\
  1812. vm_info.netvm if vm_info.netvm is not None "
  1813. "else '-'"},
  1814. "label": {"func": "vm.label.name"},
  1815. }
  1816. fields_to_display = ["name", "type", "template", "updbl",
  1817. "netvm", "label"]
  1818. # First calculate the maximum width of each field we want to display
  1819. total_width = 0
  1820. for f in fields_to_display:
  1821. fields[f]["max_width"] = len(f)
  1822. for vm_info in restore_info.values():
  1823. if vm_info.vm:
  1824. # noinspection PyUnusedLocal
  1825. vm = vm_info.vm
  1826. l = len(unicode(eval(fields[f]["func"])))
  1827. if l > fields[f]["max_width"]:
  1828. fields[f]["max_width"] = l
  1829. total_width += fields[f]["max_width"]
  1830. summary = ""
  1831. summary += "The following VMs are included in the backup:\n"
  1832. summary += "\n"
  1833. # Display the header
  1834. for f in fields_to_display:
  1835. # noinspection PyTypeChecker
  1836. fmt = "{{0:-^{0}}}-+".format(fields[f]["max_width"] + 1)
  1837. summary += fmt.format('-')
  1838. summary += "\n"
  1839. for f in fields_to_display:
  1840. # noinspection PyTypeChecker
  1841. fmt = "{{0:>{0}}} |".format(fields[f]["max_width"] + 1)
  1842. summary += fmt.format(f)
  1843. summary += "\n"
  1844. for f in fields_to_display:
  1845. # noinspection PyTypeChecker
  1846. fmt = "{{0:-^{0}}}-+".format(fields[f]["max_width"] + 1)
  1847. summary += fmt.format('-')
  1848. summary += "\n"
  1849. for vm_info in restore_info.values():
  1850. assert isinstance(vm_info, BackupRestore.VMToRestore)
  1851. # Skip non-VM here
  1852. if not vm_info.vm:
  1853. continue
  1854. # noinspection PyUnusedLocal
  1855. vm = vm_info.vm
  1856. s = ""
  1857. for f in fields_to_display:
  1858. # noinspection PyTypeChecker
  1859. fmt = "{{0:>{0}}} |".format(fields[f]["max_width"] + 1)
  1860. s += fmt.format(eval(fields[f]["func"]))
  1861. if BackupRestore.VMToRestore.EXCLUDED in vm_info.problems:
  1862. s += " <-- Excluded from restore"
  1863. elif BackupRestore.VMToRestore.ALREADY_EXISTS in vm_info.problems:
  1864. s += " <-- A VM with the same name already exists on the host!"
  1865. elif BackupRestore.VMToRestore.MISSING_TEMPLATE in \
  1866. vm_info.problems:
  1867. s += " <-- No matching template on the host " \
  1868. "or in the backup found!"
  1869. elif BackupRestore.VMToRestore.MISSING_NETVM in \
  1870. vm_info.problems:
  1871. s += " <-- No matching netvm on the host " \
  1872. "or in the backup found!"
  1873. else:
  1874. if vm_info.orig_template:
  1875. s += " <-- Original template was '{}'".format(
  1876. vm_info.orig_template)
  1877. if vm_info.name != vm_info.vm.name:
  1878. s += " <-- Will be renamed to '{}'".format(
  1879. vm_info.name)
  1880. summary += s + "\n"
  1881. if 'dom0' in restore_info.keys():
  1882. s = ""
  1883. for f in fields_to_display:
  1884. # noinspection PyTypeChecker
  1885. fmt = "{{0:>{0}}} |".format(fields[f]["max_width"] + 1)
  1886. if f == "name":
  1887. s += fmt.format("Dom0")
  1888. elif f == "type":
  1889. s += fmt.format("Home")
  1890. else:
  1891. s += fmt.format("")
  1892. if BackupRestore.Dom0ToRestore.USERNAME_MISMATCH in \
  1893. restore_info['dom0'].problems:
  1894. s += " <-- username in backup and dom0 mismatch"
  1895. summary += s + "\n"
  1896. return summary
  1897. def _restore_vm_dir_v1(self, src_dir, dst_dir):
  1898. backup_src_dir = src_dir.replace(
  1899. qubes.config.system_path["qubes_base_dir"], self.backup_location)
  1900. # We prefer to use Linux's cp, because it nicely handles sparse files
  1901. cp_retcode = subprocess.call(
  1902. ["cp", "-rp", "--reflink=auto", backup_src_dir, dst_dir])
  1903. if cp_retcode != 0:
  1904. raise qubes.exc.QubesException(
  1905. "*** Error while copying file {0} to {1}".format(backup_src_dir,
  1906. dst_dir))
  1907. @staticmethod
  1908. def _templates_first(vms):
  1909. def key_function(instance):
  1910. if isinstance(instance, qubes.vm.BaseVM):
  1911. return isinstance(instance, qubes.vm.templatevm.TemplateVM)
  1912. elif hasattr(instance, 'vm'):
  1913. return key_function(instance.vm)
  1914. else:
  1915. return 0
  1916. return sorted(vms,
  1917. key=key_function,
  1918. reverse=True)
  1919. def restore_do(self, restore_info):
  1920. '''
  1921. High level workflow:
  1922. 1. Create VMs object in host collection (qubes.xml)
  1923. 2. Create them on disk (vm.create_on_disk)
  1924. 3. Restore VM data, overriding/converting VM files
  1925. 4. Apply possible fixups and save qubes.xml
  1926. :param restore_info:
  1927. :return:
  1928. '''
  1929. # FIXME handle locking
  1930. restore_info = self.restore_info_verify(restore_info)
  1931. self._restore_vms_metadata(restore_info)
  1932. # Perform VM restoration in backup order
  1933. vms_dirs = []
  1934. relocate = {}
  1935. vms_size = 0
  1936. for vm_info in self._templates_first(restore_info.values()):
  1937. vm = vm_info.restored_vm
  1938. if vm:
  1939. vms_size += int(vm_info.size)
  1940. vms_dirs.append(vm_info.subdir)
  1941. relocate[vm_info.subdir.rstrip('/')] = vm.dir_path
  1942. for name, volume in vm.volumes.items():
  1943. if not volume.save_on_stop:
  1944. continue
  1945. export_path = vm.storage.export(name)
  1946. backup_path = os.path.join(
  1947. vm_info.vm.dir_path, name + '.img')
  1948. if backup_path != export_path:
  1949. relocate[
  1950. os.path.join(vm_info.subdir, name + '.img')] = \
  1951. export_path
  1952. if self.header_data.version >= 2:
  1953. if 'dom0' in restore_info.keys() and \
  1954. restore_info['dom0'].good_to_go:
  1955. vms_dirs.append(os.path.dirname(restore_info['dom0'].subdir))
  1956. vms_size += restore_info['dom0'].size
  1957. try:
  1958. self._restore_vm_dirs(vms_dirs=vms_dirs, vms_size=vms_size,
  1959. relocate=relocate)
  1960. except qubes.exc.QubesException:
  1961. if self.options.verify_only:
  1962. raise
  1963. else:
  1964. self.log.warning(
  1965. "Some errors occurred during data extraction, "
  1966. "continuing anyway to restore at least some "
  1967. "VMs")
  1968. else:
  1969. for vm_info in self._templates_first(restore_info.values()):
  1970. vm = vm_info.restored_vm
  1971. if vm:
  1972. try:
  1973. self._restore_vm_dir_v1(vm_info.vm.dir_path,
  1974. os.path.dirname(vm.dir_path))
  1975. except qubes.exc.QubesException as e:
  1976. if self.options.verify_only:
  1977. raise
  1978. else:
  1979. self.log.error(
  1980. "Failed to restore VM '{}': {}".format(
  1981. vm.name, str(e)))
  1982. vm.remove_from_disk()
  1983. del self.app.domains[vm]
  1984. if self.options.verify_only:
  1985. self.log.warning(
  1986. "Backup verification not supported for this backup format.")
  1987. if self.options.verify_only:
  1988. shutil.rmtree(self.tmpdir)
  1989. return
  1990. for vm_info in self._templates_first(restore_info.values()):
  1991. if not vm_info.restored_vm:
  1992. continue
  1993. try:
  1994. vm_info.restored_vm.fire_event('domain-restore')
  1995. except Exception as err:
  1996. self.log.error("ERROR during appmenu restore: "
  1997. "{0}".format(err))
  1998. self.log.warning(
  1999. "*** VM '{0}' will not have appmenus".format(vm_info.name))
  2000. try:
  2001. vm_info.restored_vm.storage.verify()
  2002. except Exception as err:
  2003. self.log.error("ERROR: {0}".format(err))
  2004. if vm_info.restored_vm:
  2005. vm_info.restored_vm.remove_from_disk()
  2006. del self.app.domains[vm_info.restored_vm]
  2007. self.app.save()
  2008. if self.canceled:
  2009. if self.header_data.version >= 2:
  2010. raise BackupCanceledError("Restore canceled",
  2011. tmpdir=self.tmpdir)
  2012. else:
  2013. raise BackupCanceledError("Restore canceled")
  2014. # ... and dom0 home as last step
  2015. if 'dom0' in restore_info.keys() and restore_info['dom0'].good_to_go:
  2016. backup_path = restore_info['dom0'].subdir
  2017. local_user = grp.getgrnam('qubes').gr_mem[0]
  2018. home_dir = pwd.getpwnam(local_user).pw_dir
  2019. if self.header_data.version == 1:
  2020. backup_dom0_home_dir = os.path.join(self.backup_location,
  2021. backup_path)
  2022. else:
  2023. backup_dom0_home_dir = os.path.join(self.tmpdir, backup_path)
  2024. restore_home_backupdir = "home-pre-restore-{0}".format(
  2025. time.strftime("%Y-%m-%d-%H%M%S"))
  2026. self.log.info(
  2027. "Restoring home of user '{0}'...".format(local_user))
  2028. self.log.info(
  2029. "Existing files/dirs backed up in '{0}' dir".format(
  2030. restore_home_backupdir))
  2031. os.mkdir(home_dir + '/' + restore_home_backupdir)
  2032. for f in os.listdir(backup_dom0_home_dir):
  2033. home_file = home_dir + '/' + f
  2034. if os.path.exists(home_file):
  2035. os.rename(home_file,
  2036. home_dir + '/' + restore_home_backupdir + '/' + f)
  2037. if self.header_data.version == 1:
  2038. subprocess.call(
  2039. ["cp", "-nrp", "--reflink=auto",
  2040. backup_dom0_home_dir + '/' + f, home_file])
  2041. elif self.header_data.version >= 2:
  2042. shutil.move(backup_dom0_home_dir + '/' + f, home_file)
  2043. retcode = subprocess.call(['sudo', 'chown', '-R',
  2044. local_user, home_dir])
  2045. if retcode != 0:
  2046. self.log.error("*** Error while setting home directory owner")
  2047. shutil.rmtree(self.tmpdir)
  2048. self.log.info("-> Done. Please install updates for all the restored "
  2049. "templates.")
  2050. def _restore_vms_metadata(self, restore_info):
  2051. vms = {}
  2052. for vm_info in restore_info.values():
  2053. assert isinstance(vm_info, self.VMToRestore)
  2054. if not vm_info.vm:
  2055. continue
  2056. if not vm_info.good_to_go:
  2057. continue
  2058. vm = vm_info.vm
  2059. vms[vm.name] = vm
  2060. # First load templates, then other VMs
  2061. for vm in self._templates_first(vms.values()):
  2062. if self.canceled:
  2063. # only break the loop to save qubes.xml
  2064. # with already restored VMs
  2065. break
  2066. self.log.info("-> Restoring {0}...".format(vm.name))
  2067. kwargs = {}
  2068. if hasattr(vm, 'template'):
  2069. template = restore_info[vm.name].template
  2070. # handle potentially renamed template
  2071. if template in restore_info \
  2072. and restore_info[template].good_to_go:
  2073. template = restore_info[template].name
  2074. kwargs['template'] = template
  2075. new_vm = None
  2076. vm_name = restore_info[vm.name].name
  2077. try:
  2078. # first only minimal set, later clone_properties
  2079. # will be called
  2080. cls = self.app.get_vm_class(vm.__class__.__name__)
  2081. new_vm = self.app.add_new_vm(
  2082. cls,
  2083. name=vm_name,
  2084. label=vm.label,
  2085. installed_by_rpm=False,
  2086. **kwargs)
  2087. if os.path.exists(new_vm.dir_path):
  2088. move_to_path = tempfile.mkdtemp('', os.path.basename(
  2089. new_vm.dir_path), os.path.dirname(new_vm.dir_path))
  2090. try:
  2091. os.rename(new_vm.dir_path, move_to_path)
  2092. self.log.warning(
  2093. "*** Directory {} already exists! It has "
  2094. "been moved to {}".format(new_vm.dir_path,
  2095. move_to_path))
  2096. except OSError:
  2097. self.log.error(
  2098. "*** Directory {} already exists and "
  2099. "cannot be moved!".format(new_vm.dir_path))
  2100. self.log.warning("Skipping VM {}...".format(
  2101. vm.name))
  2102. continue
  2103. except Exception as err:
  2104. self.log.error("ERROR: {0}".format(err))
  2105. self.log.warning("*** Skipping VM: {0}".format(vm.name))
  2106. if new_vm:
  2107. del self.app.domains[new_vm.qid]
  2108. continue
  2109. # remove no longer needed backup metadata
  2110. if 'backup-content' in vm.features:
  2111. del vm.features['backup-content']
  2112. del vm.features['backup-size']
  2113. del vm.features['backup-path']
  2114. try:
  2115. # exclude VM references - handled manually according to
  2116. # restore options
  2117. proplist = [prop for prop in new_vm.property_list()
  2118. if prop.clone and prop.__name__ not in
  2119. ['template', 'netvm', 'dispvm_netvm']]
  2120. new_vm.clone_properties(vm, proplist=proplist)
  2121. except Exception as err:
  2122. self.log.error("ERROR: {0}".format(err))
  2123. self.log.warning("*** Some VM property will not be "
  2124. "restored")
  2125. if not self.options.verify_only:
  2126. try:
  2127. # have it here, to (maybe) patch storage config before
  2128. # creating child VMs (template first)
  2129. # TODO: adjust volumes config - especially size
  2130. new_vm.create_on_disk(pool=self.options.override_pool)
  2131. except qubes.exc.QubesException as e:
  2132. self.log.warning("Failed to create VM {}: {}".format(
  2133. vm.name, str(e)))
  2134. del self.app.domains[new_vm]
  2135. continue
  2136. restore_info[vm.name].restored_vm = new_vm
  2137. # Set network dependencies - only non-default netvm setting
  2138. for vm in vms.values():
  2139. vm_info = restore_info[vm.name]
  2140. vm_name = vm_info.name
  2141. try:
  2142. host_vm = self.app.domains[vm_name]
  2143. except KeyError:
  2144. # Failed/skipped VM
  2145. continue
  2146. if not vm.property_is_default('netvm'):
  2147. if vm_info.netvm in restore_info:
  2148. host_vm.netvm = restore_info[vm_info.netvm].name
  2149. else:
  2150. host_vm.netvm = vm_info.netvm
  2151. # vim:sw=4:et: