forked from xcp-ng/host-installer_old
-
Notifications
You must be signed in to change notification settings - Fork 0
/
restore.py
369 lines (313 loc) · 17 KB
/
restore.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# Copyright (c) 2005-2006 XenSource, Inc. All use and distribution of this
# copyrighted material is governed by and subject to terms and conditions
# as licensed by XenSource, Inc. All other rights reserved.
# Xen, XenSource and XenEnterprise are either registered trademarks or
# trademarks of XenSource Inc. in the United States and/or other countries.
###
# XEN CLEAN INSTALLER
# Functions to perform restore from backup partition, including UI.
#
# written by Andrew Peace
import backend
import product
from disktools import *
import xelogging
import diskutil
import util
import os
import os.path
import constants
import re
import tempfile
import shutil
import xcp.bootloader as bootloader
def restoreFromBackup(backup, progress = lambda x: ()):
""" Restore files from backup_partition to the root partition on disk.
Call progress with a value between 0 and 100. Re-install bootloader. Fails if
backup is not same version as the CD in use."""
disk = backup.root_disk
tool = PartitionTool(disk)
_, boot_partnum, primary_partnum, backup_partnum, logs_partnum, swap_partnum, _ = backend.inspectTargetDisk(disk, None, [], constants.PRESERVE_IF_UTILITY, True, True)
backup_version = backup.version
limit_version = product.THIS_PLATFORM_VERSION
logs_partition = tool.getPartition(logs_partnum)
boot_partition = tool.getPartition(boot_partnum)
root_partition = partitionDevice(disk, primary_partnum)
backup_fs = util.TempMount(backup.partition, 'backup-', options = ['ro'])
inventory = util.readKeyValueFile(os.path.join(backup_fs.mount_point, constants.INVENTORY_FILE), strip_quotes = True)
backup_partition_layout = []
if 'PARTITION_LAYOUT' in inventory: # Present from XS 7.0
backup_partition_layout = inventory['PARTITION_LAYOUT'].split(',')
backup_fs.unmount()
(boot, _, _, _, logs) = diskutil.probeDisk(disk)
xelogging.log("BACKUP DISK PARTITION LAYOUT: %s" % backup_partition_layout)
if not logs[0] and boot[0] and not backup_partition_layout: # From 7.x (no new layout - yes Boot partition) to 6.x
restoreWithoutRepartButUEFI(backup, progress)
else:
doRestore(backup, progress, backup_partition_layout, logs[0])
def doRestore(backup, progress, backup_partition_layout, has_logs_partition):
backup_partition = backup.partition
backup_version = backup.version
disk = backup.root_disk
tool = PartitionTool(disk)
_, boot_partnum, primary_partnum, backup_partnum, logs_partnum, swap_partnum, _ = backend.inspectTargetDisk(disk, None, [], constants.PRESERVE_IF_UTILITY, True, True)
limit_version = product.THIS_PLATFORM_VERSION
logs_partition = tool.getPartition(logs_partnum)
boot_partition = tool.getPartition(boot_partnum)
assert backup_partition.startswith('/dev/')
assert disk.startswith('/dev/')
label = None
bootlabel = None
if has_logs_partition and not backup_partition_layout: # From 7.x (new layout) to 6.x
restore_partition = partitionDevice(disk, logs_partnum)
else:
restore_partition = partitionDevice(disk, primary_partnum)
xelogging.log("Restoring to partition %s." % restore_partition)
tool = PartitionTool(disk)
boot_part = tool.getPartition(boot_partnum)
boot_device = partitionDevice(disk, boot_partnum) if boot_part else None
efi_boot = boot_part and boot_part['id'] == GPTPartitionTool.ID_EFI_BOOT
# determine current location of bootloader
current_location = 'unknown'
try:
root_fs = util.TempMount(restore_partition, 'root-', options = ['ro'], boot_device = boot_device)
try:
boot_config = bootloader.Bootloader.loadExisting(root_fs.mount_point)
current_location = boot_config.location
xelogging.log("Bootloader currently in %s" % current_location)
finally:
root_fs.unmount()
except:
pass
# mount the backup fs
backup_fs = util.TempMount(backup_partition, 'restore-backup-', options = ['ro'])
try:
# extract the bootloader config
boot_config = bootloader.Bootloader.loadExisting(backup_fs.mount_point)
if boot_config.src_fmt == 'grub':
raise RuntimeError, "Backup uses grub bootloader which is no longer supported - " + \
"to restore please use a version of the installer that matches the backup partition"
# format the restore partition(s):
if util.runCmd2(['mkfs.%s' % constants.rootfs_type, restore_partition]) != 0:
raise RuntimeError, "Failed to create root filesystem"
if efi_boot:
if util.runCmd2(['mkfs.vfat', boot_device]) != 0:
raise RuntimeError, "Failed to create boot filesystem"
# mount restore partition:
dest_fs = util.TempMount(restore_partition, 'restore-dest-')
try:
# copy files from the backup partition to the restore partition:
objs = filter(lambda x: x not in ['lost+found', '.xen-backup-partition', '.xen-gpt.bin'],
os.listdir(backup_fs.mount_point))
for i in range(len(objs)):
obj = objs[i]
xelogging.log("Restoring subtree %s..." % obj)
progress((i * 100) / len(objs))
# Use 'cp' here because Python's copying tools are useless and
# get stuck in an infinite loop when copying e.g. /dev/null.
if util.runCmd2(['cp', '-a', os.path.join(backup_fs.mount_point, obj),
dest_fs.mount_point]) != 0:
raise RuntimeError, "Failed to restore %s directory" % obj
xelogging.log("Data restoration complete. About to re-install bootloader.")
location = boot_config.location
m = re.search(r'root=LABEL=(\S+)', boot_config.menu[boot_config.default].kernel_args)
if m:
label = m.group(1)
if location == constants.BOOT_LOCATION_PARTITION and current_location == constants.BOOT_LOCATION_MBR:
# if bootloader in the MBR it's probably not safe to restore with it
# on the partition
xelogging.log("Bootloader is currently installed to MBR, restoring to MBR instead of partition")
location = constants.BOOT_LOCATION_MBR
with open(os.path.join(backup_fs.mount_point, 'etc', 'fstab'), 'r') as fstab:
for line in fstab:
m = re.match(r'LABEL=(\S+)\s+/boot/efi\s', line)
if m:
bootlabel = m.group(1)
mounts = {'root': dest_fs.mount_point, 'boot': os.path.join(dest_fs.mount_point, 'boot')}
# prepare extra mounts for installing bootloader:
util.bindMount("/dev", "%s/dev" % dest_fs.mount_point)
util.bindMount("/sys", "%s/sys" % dest_fs.mount_point)
util.bindMount("/proc", "%s/proc" % dest_fs.mount_point)
if boot_config.src_fmt == 'grub2':
if efi_boot:
branding = util.readKeyValueFile(os.path.join(backup_fs.mount_point, constants.INVENTORY_FILE))
branding['product-brand'] = branding['PRODUCT_BRAND']
backend.setEfiBootEntry(mounts, disk, boot_partnum, branding)
else:
if location == constants.BOOT_LOCATION_MBR:
backend.installGrub2(mounts, disk, False)
else:
backend.installGrub2(mounts, restore_partition, True)
else:
backend.installExtLinux(mounts, disk, probePartitioningScheme(disk), location)
# restore bootloader configuration
dst_file = boot_config.src_file.replace(backup_fs.mount_point, dest_fs.mount_point, 1)
util.assertDir(os.path.dirname(dst_file))
boot_config.commit(dst_file)
finally:
util.umount("%s/proc" % dest_fs.mount_point)
util.umount("%s/sys" % dest_fs.mount_point)
util.umount("%s/dev" % dest_fs.mount_point)
dest_fs.unmount()
finally:
backup_fs.unmount()
if not label:
raise RuntimeError, "Failed to find label required for root filesystem."
if efi_boot and not bootlabel:
raise RuntimeError("Failed to find label required for boot filesystem.")
if util.runCmd2(['e2label', restore_partition, label]) != 0:
raise RuntimeError, "Failed to label root partition"
if bootlabel:
if util.runCmd2(['fatlabel', boot_device, bootlabel]) != 0:
raise RuntimeError, "Failed to label boot partition"
if has_logs_partition:
if not backup_partition_layout: # From 7.x (new layout) to 6.x
# Delete backup, dom0, Boot and swap partitions
tool.deletePartition(backup_partnum)
tool.deletePartition(primary_partnum)
tool.deletePartition(boot_partnum)
tool.deletePartition(swap_partnum)
# Rename logs partition to be n.1
tool.renamePartition(srcNumber = logs_partnum, destNumber = primary_partnum, overwrite = False)
# Create 4GB backup partition
tool.createPartition(tool.ID_LINUX, sizeBytes = constants.backup_size_old * 2**20, startBytes = tool.partitionEnd(primary_partnum) + tool.sectorSize, number = backup_partnum)
# Commit partition table and mark dom0 disk as bootable
tool.commit(log = True)
tool.commitActivePartitiontoDisk(primary_partnum)
xelogging.log("Bootloader restoration complete.")
xelogging.log("Restore successful.")
backend.writeLog(disk, primary_partnum, logs_partnum)
elif 'LOG' in backup_partition_layout: # From 7.x (new layout) to 7.x (new layout)
tool.commitActivePartitiontoDisk(boot_partnum)
rdm_label = label.split("-")[1]
logs_part = partitionDevice(disk, logs_partnum)
swap_part = partitionDevice(disk, swap_partnum)
if util.runCmd2(['e2label', logs_part, constants.logsfs_label%rdm_label]) != 0:
raise RuntimeError, "Failed to label logs partition"
if util.runCmd2(['swaplabel', '-L', constants.swap_label%rdm_label, swap_part]) != 0:
raise RuntimeError, "Failed to label swap partition"
def restoreWithoutRepartButUEFI(backup, progress):
backup_partition = backup.partition
disk = backup.root_disk
assert backup_partition.startswith('/dev/')
assert disk.startswith('/dev/')
# Restore the partition layout
backup_fs = util.TempMount(backup_partition, 'restore-backup-', options = ['ro'])
gpt_bin = None
try:
src_bin = os.path.join(backup_fs.mount_point, '.xen-gpt.bin')
if os.path.exists(src_bin):
gpt_bin = tempfile.mktemp()
shutil.copyfile(src_bin, gpt_bin)
finally:
backup_fs.unmount()
if gpt_bin:
xelogging.log("Restoring partition layout")
rc, err = util.runCmd2(["sgdisk", "-l", gpt_bin, disk], with_stderr = True)
if rc != 0:
raise RuntimeError, "Failed to restore partition layout: %s" % err
label = None
bootlabel = None
_, boot_partnum, primary_partnum, backup_partnum, logs_partnum, swap_partnum, _ = backend.inspectTargetDisk(disk, None, [], constants.PRESERVE_IF_UTILITY, True, True)
restore_partition = partitionDevice(disk, primary_partnum)
xelogging.log("Restoring to partition %s." % restore_partition)
tool = PartitionTool(disk)
boot_part = tool.getPartition(boot_partnum)
boot_device = partitionDevice(disk, boot_partnum) if boot_part else None
efi_boot = boot_part and boot_part['id'] == GPTPartitionTool.ID_EFI_BOOT
# determine current location of bootloader
current_location = 'unknown'
try:
root_fs = util.TempMount(restore_partition, 'root-', options = ['ro'], boot_device = boot_device)
try:
boot_config = bootloader.Bootloader.loadExisting(root_fs.mount_point)
current_location = boot_config.location
xelogging.log("Bootloader currently in %s" % current_location)
finally:
root_fs.unmount()
except:
pass
# mount the backup fs
backup_fs = util.TempMount(backup_partition, 'restore-backup-', options = ['ro'])
try:
# extract the bootloader config
boot_config = bootloader.Bootloader.loadExisting(backup_fs.mount_point)
if boot_config.src_fmt == 'grub':
raise RuntimeError, "Backup uses grub bootloader which is no longer supported - " + \
"to restore please use a version of the installer that matches the backup partition"
# format the restore partition(s):
if util.runCmd2(['mkfs.%s' % constants.rootfs_type, restore_partition]) != 0:
raise RuntimeError, "Failed to create root filesystem"
if efi_boot:
if util.runCmd2(['mkfs.vfat', boot_device]) != 0:
raise RuntimeError, "Failed to create boot filesystem"
# mount restore partition:
dest_fs = util.TempMount(restore_partition, 'restore-dest-', boot_device = boot_device, boot_mount_point = '/boot/efi')
try:
# copy files from the backup partition to the restore partition:
objs = filter(lambda x: x not in ['lost+found', '.xen-backup-partition', '.xen-gpt.bin'],
os.listdir(backup_fs.mount_point))
for i in range(len(objs)):
obj = objs[i]
xelogging.log("Restoring subtree %s..." % obj)
progress((i * 100) / len(objs))
# Use 'cp' here because Python's copying tools are useless and
# get stuck in an infinite loop when copying e.g. /dev/null.
if util.runCmd2(['cp', '-a', os.path.join(backup_fs.mount_point, obj),
dest_fs.mount_point]) != 0:
raise RuntimeError, "Failed to restore %s directory" % obj
xelogging.log("Data restoration complete. About to re-install bootloader.")
location = boot_config.location
m = re.search(r'root=LABEL=(\S+)', boot_config.menu[boot_config.default].kernel_args)
if m:
label = m.group(1)
if location == constants.BOOT_LOCATION_PARTITION and current_location == constants.BOOT_LOCATION_MBR:
# if bootloader in the MBR it's probably not safe to restore with it
# on the partition
xelogging.log("Bootloader is currently installed to MBR, restoring to MBR instead of partition")
location = constants.BOOT_LOCATION_MBR
with open(os.path.join(backup_fs.mount_point, 'etc', 'fstab'), 'r') as fstab:
for line in fstab:
m = re.match(r'LABEL=(\S+)\s+/boot/efi\s', line)
if m:
bootlabel = m.group(1)
mounts = {'root': dest_fs.mount_point, 'boot': os.path.join(dest_fs.mount_point, 'boot')}
# prepare extra mounts for installing bootloader:
util.bindMount("/dev", "%s/dev" % dest_fs.mount_point)
util.bindMount("/sys", "%s/sys" % dest_fs.mount_point)
util.bindMount("/proc", "%s/proc" % dest_fs.mount_point)
if boot_config.src_fmt == 'grub2':
if efi_boot:
branding = util.readKeyValueFile(os.path.join(backup_fs.mount_point, constants.INVENTORY_FILE))
branding['product-brand'] = branding['PRODUCT_BRAND']
backend.setEfiBootEntry(mounts, disk, boot_partnum, branding)
else:
if location == constants.BOOT_LOCATION_MBR:
backend.installGrub2(mounts, disk, False)
else:
backend.installGrub2(mounts, restore_partition, True)
else:
backend.installExtLinux(mounts, disk, probePartitioningScheme(disk), location)
# restore bootloader configuration
dst_file = boot_config.src_file.replace(backup_fs.mount_point, dest_fs.mount_point, 1)
util.assertDir(os.path.dirname(dst_file))
boot_config.commit(dst_file)
finally:
util.umount("%s/proc" % dest_fs.mount_point)
util.umount("%s/sys" % dest_fs.mount_point)
util.umount("%s/dev" % dest_fs.mount_point)
dest_fs.unmount()
finally:
backup_fs.unmount()
if not label:
raise RuntimeError, "Failed to find label required for root filesystem."
if efi_boot and not bootlabel:
raise RuntimeError("Failed to find label required for boot filesystem.")
if util.runCmd2(['e2label', restore_partition, label]) != 0:
raise RuntimeError, "Failed to label root partition"
if bootlabel:
if util.runCmd2(['fatlabel', boot_device, bootlabel]) != 0:
raise RuntimeError, "Failed to label boot partition"
xelogging.log("Bootloader restoration complete.")
xelogging.log("Restore successful.")
backend.writeLog(disk, primary_partnum, logs_partnum)