root / image_creator / bundle_volume.py @ 10a5c2bf
History | View | Annotate | Download (16.4 kB)
1 |
# Copyright 2012 GRNET S.A. All rights reserved.
|
---|---|
2 |
#
|
3 |
# Redistribution and use in source and binary forms, with or
|
4 |
# without modification, are permitted provided that the following
|
5 |
# conditions are met:
|
6 |
#
|
7 |
# 1. Redistributions of source code must retain the above
|
8 |
# copyright notice, this list of conditions and the following
|
9 |
# disclaimer.
|
10 |
#
|
11 |
# 2. Redistributions in binary form must reproduce the above
|
12 |
# copyright notice, this list of conditions and the following
|
13 |
# disclaimer in the documentation and/or other materials
|
14 |
# provided with the distribution.
|
15 |
#
|
16 |
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
|
17 |
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
18 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
19 |
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
|
20 |
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
|
23 |
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
24 |
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
25 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
26 |
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
27 |
# POSSIBILITY OF SUCH DAMAGE.
|
28 |
#
|
29 |
# The views and conclusions contained in the software and
|
30 |
# documentation are those of the authors and should not be
|
31 |
# interpreted as representing official policies, either expressed
|
32 |
# or implied, of GRNET S.A.
|
33 |
|
34 |
import os |
35 |
import re |
36 |
import tempfile |
37 |
import uuid |
38 |
from collections import namedtuple |
39 |
|
40 |
import parted |
41 |
|
42 |
from image_creator.rsync import Rsync |
43 |
from image_creator.util import get_command |
44 |
from image_creator.util import FatalError |
45 |
from image_creator.util import try_fail_repeat |
46 |
from image_creator.util import free_space |
47 |
from image_creator.gpt import GPTPartitionTable |
48 |
|
49 |
findfs = get_command('findfs')
|
50 |
dd = get_command('dd')
|
51 |
dmsetup = get_command('dmsetup')
|
52 |
losetup = get_command('losetup')
|
53 |
mount = get_command('mount')
|
54 |
umount = get_command('umount')
|
55 |
blkid = get_command('blkid')
|
56 |
|
57 |
MKFS_OPTS = {'ext2': ['-F'], |
58 |
'ext3': ['-F'], |
59 |
'ext4': ['-F'], |
60 |
'reiserfs': ['-ff'], |
61 |
'btrfs': [],
|
62 |
'minix': [],
|
63 |
'xfs': ['-f'], |
64 |
'jfs': ['-f'], |
65 |
'ntfs': ['-F'], |
66 |
'msdos': [],
|
67 |
'vfat': []}
|
68 |
|
69 |
|
70 |
class BundleVolume(object): |
71 |
"""This class can be used to create an image out of the running system"""
|
72 |
|
73 |
def __init__(self, out, meta, tmp=None): |
74 |
"""Create an instance of the BundleVolume class."""
|
75 |
self.out = out
|
76 |
self.meta = meta
|
77 |
self.tmp = tmp
|
78 |
|
79 |
self.out.output('Searching for root device ...', False) |
80 |
root = self._get_root_partition()
|
81 |
|
82 |
if root.startswith("UUID=") or root.startswith("LABEL="): |
83 |
root = findfs(root).stdout.strip() |
84 |
|
85 |
if not re.match('/dev/[hsv]d[a-z][1-9]*$', root): |
86 |
raise FatalError("Don't know how to handle root device: %s" % root) |
87 |
|
88 |
out.success(root) |
89 |
|
90 |
disk_file = re.split('[0-9]', root)[0] |
91 |
device = parted.Device(disk_file) |
92 |
self.disk = parted.Disk(device)
|
93 |
|
94 |
def _read_fstable(self, f): |
95 |
|
96 |
if not os.path.isfile(f): |
97 |
raise FatalError("Unable to open: `%s'. File is missing." % f) |
98 |
|
99 |
FileSystemTableEntry = namedtuple('FileSystemTableEntry',
|
100 |
'dev mpoint fs opts freq passno')
|
101 |
with open(f) as table: |
102 |
for line in iter(table): |
103 |
entry = line.split('#')[0].strip().split() |
104 |
if len(entry) != 6: |
105 |
continue
|
106 |
yield FileSystemTableEntry(*entry)
|
107 |
|
108 |
def _get_root_partition(self): |
109 |
for entry in self._read_fstable('/etc/fstab'): |
110 |
if entry.mpoint == '/': |
111 |
return entry.dev
|
112 |
|
113 |
raise FatalError("Unable to find root device in /etc/fstab") |
114 |
|
115 |
def _is_mpoint(self, path): |
116 |
for entry in self._read_fstable('/proc/mounts'): |
117 |
if entry.mpoint == path:
|
118 |
return True |
119 |
return False |
120 |
|
121 |
def _get_mount_options(self, device): |
122 |
for entry in self._read_fstable('/proc/mounts'): |
123 |
if not entry.dev.startswith('/'): |
124 |
continue
|
125 |
|
126 |
if os.path.realpath(entry.dev) == os.path.realpath(device):
|
127 |
return entry
|
128 |
|
129 |
return None |
130 |
|
131 |
def _create_partition_table(self, image): |
132 |
|
133 |
# Copy the MBR and the space between the MBR and the first partition.
|
134 |
# In msdos partitons tables Grub Stage 1.5 is located there.
|
135 |
# In gpt partition tables the Primary GPT Header is there.
|
136 |
first_sector = self.disk.getPrimaryPartitions()[0].geometry.start |
137 |
|
138 |
dd('if=%s' % self.disk.device.path, 'of=%s' % image, |
139 |
'bs=%d' % self.disk.device.sectorSize, |
140 |
'count=%d' % first_sector, 'conv=notrunc') |
141 |
|
142 |
if self.disk.type == 'gpt': |
143 |
# Copy the Secondary GPT Header
|
144 |
table = GPTPartitionTable(self.disk.device.path)
|
145 |
dd('if=%s' % self.disk.device.path, 'of=%s' % image, |
146 |
'bs=%d' % self.disk.device.sectorSize, 'conv=notrunc', |
147 |
'seek=%d' % table.primary.last_usable_lba,
|
148 |
'skip=%d' % table.primary.last_usable_lba)
|
149 |
|
150 |
# Create the Extended boot records (EBRs) in the image
|
151 |
extended = self.disk.getExtendedPartition()
|
152 |
if not extended: |
153 |
return
|
154 |
|
155 |
# Extended boot records precede the logical partitions they describe
|
156 |
logical = self.disk.getLogicalPartitions()
|
157 |
start = extended.geometry.start |
158 |
for i in range(len(logical)): |
159 |
end = logical[i].geometry.start - 1
|
160 |
dd('if=%s' % self.disk.device.path, 'of=%s' % image, |
161 |
'count=%d' % (end - start + 1), 'conv=notrunc', |
162 |
'seek=%d' % start, 'skip=%d' % start) |
163 |
start = logical[i].geometry.end + 1
|
164 |
|
165 |
def _get_partitions(self, disk): |
166 |
Partition = namedtuple('Partition', 'num start end type fs') |
167 |
|
168 |
partitions = [] |
169 |
for p in disk.partitions: |
170 |
num = p.number |
171 |
start = p.geometry.start |
172 |
end = p.geometry.end |
173 |
ptype = p.type |
174 |
fs = p.fileSystem.type if p.fileSystem is not None else '' |
175 |
partitions.append(Partition(num, start, end, ptype, fs)) |
176 |
|
177 |
return partitions
|
178 |
|
179 |
def _shrink_partitions(self, image): |
180 |
|
181 |
new_end = self.disk.device.length
|
182 |
|
183 |
image_disk = parted.Disk(parted.Device(image)) |
184 |
|
185 |
is_extended = lambda p: p.type == parted.PARTITION_EXTENDED
|
186 |
is_logical = lambda p: p.type == parted.PARTITION_LOGICAL
|
187 |
|
188 |
partitions = self._get_partitions(self.disk) |
189 |
|
190 |
last = partitions[-1]
|
191 |
if last.fs == 'linux-swap(v1)': |
192 |
MB = 2 ** 20 |
193 |
size = (last.end - last.start + 1) * self.disk.device.sectorSize |
194 |
self.meta['SWAP'] = "%d:%s" % (last.num, (size + MB - 1) // MB) |
195 |
|
196 |
image_disk.deletePartition( |
197 |
image_disk.getPartitionBySector(last.start)) |
198 |
image_disk.commitToDevice() |
199 |
|
200 |
if is_logical(last) and last.num == 5: |
201 |
extended = image_disk.getExtendedPartition() |
202 |
image_disk.deletePartition(extended) |
203 |
image_disk.commitToDevice() |
204 |
partitions.remove(filter(is_extended, partitions)[0]) |
205 |
|
206 |
partitions.remove(last) |
207 |
last = partitions[-1]
|
208 |
|
209 |
new_end = last.end |
210 |
|
211 |
mount_options = self._get_mount_options(
|
212 |
self.disk.getPartitionBySector(last.start).path)
|
213 |
if mount_options is not None: |
214 |
stat = os.statvfs(mount_options.mpoint) |
215 |
# Shrink the last partition. The new size should be the size of the
|
216 |
# occupied blocks
|
217 |
blcks = stat.f_blocks - stat.f_bavail |
218 |
new_size = (blcks * stat.f_frsize) // self.disk.device.sectorSize
|
219 |
|
220 |
# Add 10% just to be on the safe side
|
221 |
part_end = last.start + (new_size * 11) // 10 |
222 |
# Align to 2048
|
223 |
part_end = ((part_end + 2047) // 2048) * 2048 |
224 |
|
225 |
image_disk.setPartitionGeometry( |
226 |
image_disk.getPartitionBySector(last.start), |
227 |
parted.Constraint(device=image_disk.device), |
228 |
start=last.start, end=part_end) |
229 |
image_disk.commitToDevice() |
230 |
|
231 |
# Parted may have changed this for better alignment
|
232 |
part_end = image_disk.getPartitionBySector(last.start).geometry.end |
233 |
last = last._replace(end=part_end) |
234 |
partitions[-1] = last
|
235 |
|
236 |
new_end = part_end |
237 |
|
238 |
if last.type == parted.PARTITION_LOGICAL:
|
239 |
# Fix the extended partition
|
240 |
image_disk.minimizeExtendedPartition() |
241 |
|
242 |
return (new_end, self._get_partitions(image_disk)) |
243 |
|
244 |
def _map_partition(self, dev, num, start, end): |
245 |
name = os.path.basename(dev) + "_" + uuid.uuid4().hex
|
246 |
tablefd, table = tempfile.mkstemp() |
247 |
try:
|
248 |
size = end - start + 1
|
249 |
os.write(tablefd, "0 %d linear %s %d" % (size, dev, start))
|
250 |
dmsetup('create', "%sp%d" % (name, num), table) |
251 |
finally:
|
252 |
os.unlink(table) |
253 |
|
254 |
return "/dev/mapper/%sp%d" % (name, num) |
255 |
|
256 |
def _unmap_partition(self, dev): |
257 |
if not os.path.exists(dev): |
258 |
return
|
259 |
|
260 |
try_fail_repeat(dmsetup, 'remove', dev.split('/dev/mapper/')[1]) |
261 |
|
262 |
def _mount(self, target, devs): |
263 |
|
264 |
devs.sort(key=lambda d: d[1]) |
265 |
for dev, mpoint in devs: |
266 |
absmpoint = os.path.abspath(target + mpoint) |
267 |
if not os.path.exists(absmpoint): |
268 |
os.makedirs(absmpoint) |
269 |
mount(dev, absmpoint) |
270 |
|
271 |
def _umount_all(self, target): |
272 |
mpoints = [] |
273 |
for entry in self._read_fstable('/proc/mounts'): |
274 |
if entry.mpoint.startswith(os.path.abspath(target)):
|
275 |
mpoints.append(entry.mpoint) |
276 |
|
277 |
mpoints.sort() |
278 |
for mpoint in reversed(mpoints): |
279 |
try_fail_repeat(umount, mpoint) |
280 |
|
281 |
def _to_exclude(self): |
282 |
excluded = ['/tmp', '/var/tmp'] |
283 |
if self.tmp is not None: |
284 |
excluded.append(self.tmp)
|
285 |
local_filesystems = MKFS_OPTS.keys() + ['rootfs']
|
286 |
for entry in self._read_fstable('/proc/mounts'): |
287 |
if entry.fs in local_filesystems: |
288 |
continue
|
289 |
|
290 |
mpoint = entry.mpoint |
291 |
if mpoint in excluded: |
292 |
continue
|
293 |
|
294 |
descendants = filter(
|
295 |
lambda p: p.startswith(mpoint + '/'), excluded) |
296 |
if len(descendants): |
297 |
for d in descendants: |
298 |
excluded.remove(d) |
299 |
excluded.append(mpoint) |
300 |
continue
|
301 |
|
302 |
dirname = mpoint |
303 |
basename = ''
|
304 |
found_ancestor = False
|
305 |
while dirname != '/': |
306 |
(dirname, basename) = os.path.split(dirname) |
307 |
if dirname in excluded: |
308 |
found_ancestor = True
|
309 |
break
|
310 |
|
311 |
if not found_ancestor: |
312 |
excluded.append(mpoint) |
313 |
|
314 |
return excluded
|
315 |
|
316 |
def _replace_uuids(self, target, new_uuid): |
317 |
|
318 |
files = ['/etc/fstab',
|
319 |
'/boot/grub/grub.cfg',
|
320 |
'/boot/grub/menu.lst',
|
321 |
'/boot/grub/grub.conf']
|
322 |
|
323 |
orig = {} |
324 |
for p in self.disk.partitions: |
325 |
if p.number in new_uuid.keys(): |
326 |
orig[p.number] = \ |
327 |
blkid('-s', 'UUID', '-o', 'value', p.path).stdout.strip() |
328 |
|
329 |
for f in map(lambda f: target + f, files): |
330 |
if not os.path.exists(f): |
331 |
continue
|
332 |
|
333 |
with open(f, 'r') as src: |
334 |
lines = src.readlines() |
335 |
with open(f, 'w') as dest: |
336 |
for line in lines: |
337 |
for i, uuid in new_uuid.items(): |
338 |
line = re.sub(orig[i], uuid, line) |
339 |
dest.write(line) |
340 |
|
341 |
def _create_filesystems(self, image, partitions): |
342 |
|
343 |
filesystem = {} |
344 |
for p in self.disk.partitions: |
345 |
filesystem[p.number] = self._get_mount_options(p.path)
|
346 |
|
347 |
unmounted = filter(lambda p: filesystem[p.num] is None, partitions) |
348 |
mounted = filter(lambda p: filesystem[p.num] is not None, partitions) |
349 |
|
350 |
# For partitions that are not mounted right now, we can simply dd them
|
351 |
# into the image.
|
352 |
for p in unmounted: |
353 |
self.out.output('Cloning partition %d ... ' % p.num, False) |
354 |
dd('if=%s' % self.disk.device.path, 'of=%s' % image, |
355 |
'count=%d' % (p.end - p.start + 1), 'conv=notrunc', |
356 |
'seek=%d' % p.start, 'skip=%d' % p.start) |
357 |
self.out.success("done") |
358 |
|
359 |
loop = str(losetup('-f', '--show', image)).strip() |
360 |
mapped = {} |
361 |
try:
|
362 |
for p in mounted: |
363 |
i = p.num |
364 |
mapped[i] = self._map_partition(loop, i, p.start, p.end)
|
365 |
|
366 |
new_uuid = {} |
367 |
# Create the file systems
|
368 |
for i, dev in mapped.iteritems(): |
369 |
fs = filesystem[i].fs |
370 |
self.out.output('Creating %s filesystem on partition %d ... ' % |
371 |
(fs, i), False)
|
372 |
get_command('mkfs.%s' % fs)(*(MKFS_OPTS[fs] + [dev]))
|
373 |
self.out.success('done') |
374 |
new_uuid[i] = blkid( |
375 |
'-s', 'UUID', '-o', 'value', dev).stdout.strip() |
376 |
|
377 |
target = tempfile.mkdtemp() |
378 |
try:
|
379 |
absmpoints = self._mount(target,
|
380 |
[(mapped[i], filesystem[i].mpoint) |
381 |
for i in mapped.keys()]) |
382 |
excluded = self._to_exclude()
|
383 |
|
384 |
rsync = Rsync(self.out)
|
385 |
|
386 |
# Excluded paths need to be relative to the source
|
387 |
for excl in map(lambda p: p[1:], excluded + [image]): |
388 |
rsync.exclude(excl) |
389 |
|
390 |
rsync.archive().hard_links().xattrs().sparse().acls() |
391 |
rsync.run('/', target, 'host', 'temporary image') |
392 |
|
393 |
# Create missing mountpoints. Since they are mountpoints, we
|
394 |
# cannot determine the ownership and the mode of the real
|
395 |
# directory. Make them inherit those properties from their
|
396 |
# parent dir
|
397 |
for excl in excluded: |
398 |
dirname = os.path.dirname(excl) |
399 |
stat = os.stat(dirname) |
400 |
os.mkdir(target + excl, stat.st_mode) |
401 |
os.chown(target + excl, stat.st_uid, stat.st_gid) |
402 |
|
403 |
# We need to replace the old UUID referencies with the new
|
404 |
# ones in grub configuration files and /etc/fstab for file
|
405 |
# systems that have been recreated.
|
406 |
self._replace_uuids(target, new_uuid)
|
407 |
|
408 |
finally:
|
409 |
self._umount_all(target)
|
410 |
os.rmdir(target) |
411 |
finally:
|
412 |
for dev in mapped.values(): |
413 |
self._unmap_partition(dev)
|
414 |
losetup('-d', loop)
|
415 |
|
416 |
def create_image(self, image): |
417 |
"""Given an image filename, this method will create an image out of the
|
418 |
running system.
|
419 |
"""
|
420 |
|
421 |
size = self.disk.device.length * self.disk.device.sectorSize |
422 |
|
423 |
# Create sparse file to host the image
|
424 |
fd = os.open(image, os.O_WRONLY | os.O_CREAT) |
425 |
try:
|
426 |
os.ftruncate(fd, size) |
427 |
finally:
|
428 |
os.close(fd) |
429 |
|
430 |
self._create_partition_table(image)
|
431 |
end_sector, partitions = self._shrink_partitions(image)
|
432 |
|
433 |
if self.disk.type == 'gpt': |
434 |
old_size = size |
435 |
size = (end_sector + 1) * self.disk.device.sectorSize |
436 |
ptable = GPTPartitionTable(image) |
437 |
size = ptable.shrink(size, old_size) |
438 |
else:
|
439 |
# Alighn to 2048
|
440 |
end_sector = ((end_sector + 2047) // 2048) * 2048 |
441 |
size = (end_sector + 1) * self.disk.device.sectorSize |
442 |
|
443 |
# Truncate image to the new size.
|
444 |
fd = os.open(image, os.O_RDWR) |
445 |
try:
|
446 |
os.ftruncate(fd, size) |
447 |
finally:
|
448 |
os.close(fd) |
449 |
|
450 |
# Check if the available space is enough to host the image
|
451 |
dirname = os.path.dirname(image) |
452 |
self.out.output("Examining available space ...", False) |
453 |
if free_space(dirname) <= size:
|
454 |
raise FatalError('Not enough space under %s to host the image' % |
455 |
dirname) |
456 |
self.out.success("sufficient") |
457 |
|
458 |
self._create_filesystems(image, partitions)
|
459 |
|
460 |
return image
|
461 |
|
462 |
# vim: set sta sts=4 shiftwidth=4 sw=4 et ai :
|