1 # -*- coding: utf-8 -*-
3 # Copyright 2012 GRNET S.A. All rights reserved.
5 # Redistribution and use in source and binary forms, with or
6 # without modification, are permitted provided that the following
9 # 1. Redistributions of source code must retain the above
10 # copyright notice, this list of conditions and the following
13 # 2. Redistributions in binary form must reproduce the above
14 # copyright notice, this list of conditions and the following
15 # disclaimer in the documentation and/or other materials
16 # provided with the distribution.
18 # THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
19 # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21 # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
22 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
25 # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26 # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 # POSSIBILITY OF SUCH DAMAGE.
31 # The views and conclusions contained in the software and
32 # documentation are those of the authors and should not be
33 # interpreted as representing official policies, either expressed
34 # or implied, of GRNET S.A.
36 """This module hosts the code that performes the host bundling operation. By
37 using the create_image method of the BundleVolume class the user can create an
38 image out of the running system.
45 from collections import namedtuple
49 from image_creator.rsync import Rsync
50 from image_creator.util import get_command
51 from image_creator.util import FatalError
52 from image_creator.util import try_fail_repeat
53 from image_creator.util import free_space
54 from image_creator.gpt import GPTPartitionTable
56 findfs = get_command('findfs')
57 dd = get_command('dd')
58 dmsetup = get_command('dmsetup')
59 losetup = get_command('losetup')
60 mount = get_command('mount')
61 umount = get_command('umount')
62 blkid = get_command('blkid')
63 tune2fs = get_command('tune2fs')
65 MKFS_OPTS = {'ext2': ['-F'],
78 class BundleVolume(object):
79 """This class can be used to create an image out of the running system"""
81 def __init__(self, out, meta, tmp=None):
82 """Create an instance of the BundleVolume class."""
87 self.out.output('Searching for root device ...', False)
88 root = self._get_root_partition()
90 if root.startswith("UUID=") or root.startswith("LABEL="):
91 root = findfs(root).stdout.strip()
93 if not re.match('/dev/[hsv]d[a-z][1-9]*$', root):
94 raise FatalError("Don't know how to handle root device: %s" % root)
98 disk_file = re.split('[0-9]', root)[0]
99 device = parted.Device(disk_file)
100 self.disk = parted.Disk(device)
102 def _read_fstable(self, f):
103 """Use this generator to iterate over the lines of and fstab file"""
105 if not os.path.isfile(f):
106 raise FatalError("Unable to open: `%s'. File is missing." % f)
108 FileSystemTableEntry = namedtuple('FileSystemTableEntry',
109 'dev mpoint fs opts freq passno')
110 with open(f) as table:
111 for line in iter(table):
112 entry = line.split('#')[0].strip().split()
115 yield FileSystemTableEntry(*entry)
117 def _get_root_partition(self):
118 """Return the fstab entry accosiated with the root filesystem"""
119 for entry in self._read_fstable('/etc/fstab'):
120 if entry.mpoint == '/':
123 raise FatalError("Unable to find root device in /etc/fstab")
125 def _is_mpoint(self, path):
126 """Check if a directory is currently a mount point"""
127 for entry in self._read_fstable('/proc/mounts'):
128 if entry.mpoint == path:
132 def _get_mount_options(self, device):
133 """Return the mount entry associated with a mounted device"""
134 for entry in self._read_fstable('/proc/mounts'):
135 if not entry.dev.startswith('/'):
138 if os.path.realpath(entry.dev) == os.path.realpath(device):
143 def _create_partition_table(self, image):
144 """Copy the partition table of the host system into the image"""
146 # Copy the MBR and the space between the MBR and the first partition.
147 # In msdos partition tables Grub Stage 1.5 is located there.
148 # In gpt partition tables the Primary GPT Header is there.
149 first_sector = self.disk.getPrimaryPartitions()[0].geometry.start
151 dd('if=%s' % self.disk.device.path, 'of=%s' % image,
152 'bs=%d' % self.disk.device.sectorSize,
153 'count=%d' % first_sector, 'conv=notrunc')
155 if self.disk.type == 'gpt':
156 # Copy the Secondary GPT Header
157 table = GPTPartitionTable(self.disk.device.path)
158 dd('if=%s' % self.disk.device.path, 'of=%s' % image,
159 'bs=%d' % self.disk.device.sectorSize, 'conv=notrunc',
160 'seek=%d' % table.primary.last_usable_lba,
161 'skip=%d' % table.primary.last_usable_lba)
163 # Create the Extended boot records (EBRs) in the image
164 extended = self.disk.getExtendedPartition()
168 # Extended boot records precede the logical partitions they describe
169 logical = self.disk.getLogicalPartitions()
170 start = extended.geometry.start
171 for i in range(len(logical)):
172 end = logical[i].geometry.start - 1
173 dd('if=%s' % self.disk.device.path, 'of=%s' % image,
174 'count=%d' % (end - start + 1), 'conv=notrunc',
175 'seek=%d' % start, 'skip=%d' % start)
176 start = logical[i].geometry.end + 1
178 def _get_partitions(self, disk):
179 """Returns a list with the partitions of the provided disk"""
180 Partition = namedtuple('Partition', 'num start end type fs')
183 for p in disk.partitions:
185 start = p.geometry.start
188 fs = p.fileSystem.type if p.fileSystem is not None else ''
189 partitions.append(Partition(num, start, end, ptype, fs))
193 def _shrink_partitions(self, image):
194 """Remove the last partition of the image if it is a swap partition and
195 shrink the partition before that. Make sure it can still host all the
196 files the corresponding host file system hosts
198 new_end = self.disk.device.length
200 image_disk = parted.Disk(parted.Device(image))
202 is_extended = lambda p: p.type == parted.PARTITION_EXTENDED
203 is_logical = lambda p: p.type == parted.PARTITION_LOGICAL
205 partitions = self._get_partitions(self.disk)
207 last = partitions[-1]
208 if last.fs == 'linux-swap(v1)':
210 size = (last.end - last.start + 1) * self.disk.device.sectorSize
211 self.meta['SWAP'] = "%d:%s" % (last.num, (size + MB - 1) // MB)
213 image_disk.deletePartition(
214 image_disk.getPartitionBySector(last.start))
215 image_disk.commitToDevice()
217 if is_logical(last) and last.num == 5:
218 extended = image_disk.getExtendedPartition()
219 image_disk.deletePartition(extended)
220 image_disk.commitToDevice()
221 partitions.remove(filter(is_extended, partitions)[0])
223 partitions.remove(last)
224 last = partitions[-1]
228 mount_options = self._get_mount_options(
229 self.disk.getPartitionBySector(last.start).path)
230 if mount_options is not None:
231 stat = os.statvfs(mount_options.mpoint)
232 # Shrink the last partition. The new size should be the size of the
234 blcks = stat.f_blocks - stat.f_bavail
235 new_size = (blcks * stat.f_frsize) // self.disk.device.sectorSize
237 # Add 10% just to be on the safe side
238 part_end = last.start + (new_size * 11) // 10
240 part_end = ((part_end + 2047) // 2048) * 2048
242 # Make sure the partition starts where the old partition started.
243 constraint = parted.Constraint(device=image_disk.device)
244 constraint.startRange = parted.Geometry(device=image_disk.device,
245 start=last.start, length=1)
247 image_disk.setPartitionGeometry(
248 image_disk.getPartitionBySector(last.start), constraint,
249 start=last.start, end=part_end)
250 image_disk.commitToDevice()
252 # Parted may have changed this for better alignment
253 part_end = image_disk.getPartitionBySector(last.start).geometry.end
254 last = last._replace(end=part_end)
255 partitions[-1] = last
259 if last.type == parted.PARTITION_LOGICAL:
260 # Fix the extended partition
261 image_disk.minimizeExtendedPartition()
263 return (new_end, self._get_partitions(image_disk))
265 def _map_partition(self, dev, num, start, end):
266 """Map a partition into a block device using the device mapper"""
267 name = os.path.basename(dev) + "_" + uuid.uuid4().hex
268 tablefd, table = tempfile.mkstemp()
270 size = end - start + 1
271 os.write(tablefd, "0 %d linear %s %d" % (size, dev, start))
272 dmsetup('create', "%sp%d" % (name, num), table)
276 return "/dev/mapper/%sp%d" % (name, num)
278 def _unmap_partition(self, dev):
279 """Unmap a previously mapped partition"""
280 if not os.path.exists(dev):
283 try_fail_repeat(dmsetup, 'remove', dev.split('/dev/mapper/')[1])
285 def _mount(self, target, devs):
286 """Mount a list of filesystems in mountpoints relative to target"""
287 devs.sort(key=lambda d: d[1])
288 for dev, mpoint, options in devs:
289 absmpoint = os.path.abspath(target + mpoint)
290 if not os.path.exists(absmpoint):
291 os.makedirs(absmpoint)
294 mount(dev, absmpoint, '-o', ",".join(options))
296 mount(dev, absmpoint)
298 def _umount_all(self, target):
299 """Unmount all filesystems that are mounted under the directory target
302 for entry in self._read_fstable('/proc/mounts'):
303 if entry.mpoint.startswith(os.path.abspath(target)):
304 mpoints.append(entry.mpoint)
307 for mpoint in reversed(mpoints):
308 try_fail_repeat(umount, mpoint)
310 def _to_exclude(self):
311 """Find which directories to exclude during the image copy. This is
312 accompliced by checking which directories serve as mount points for
315 excluded = ['/tmp', '/var/tmp']
316 if self.tmp is not None:
317 excluded.append(self.tmp)
318 local_filesystems = MKFS_OPTS.keys() + ['rootfs']
319 for entry in self._read_fstable('/proc/mounts'):
320 if entry.fs in local_filesystems:
323 mpoint = entry.mpoint
324 if mpoint in excluded:
327 descendants = filter(
328 lambda p: p.startswith(mpoint + '/'), excluded)
330 for d in descendants:
332 excluded.append(mpoint)
337 found_ancestor = False
338 while dirname != '/':
339 (dirname, basename) = os.path.split(dirname)
340 if dirname in excluded:
341 found_ancestor = True
344 if not found_ancestor:
345 excluded.append(mpoint)
349 def _replace_uuids(self, target, new_uuid):
350 """Replace UUID references in various files. This is needed after
351 copying system files of the host into a new filesystem
354 files = ['/etc/fstab',
355 '/boot/grub/grub.cfg',
356 '/boot/grub/menu.lst',
357 '/boot/grub/grub.conf']
360 for p in self.disk.partitions:
361 if p.number in new_uuid.keys():
363 blkid('-s', 'UUID', '-o', 'value', p.path).stdout.strip()
365 for f in map(lambda f: target + f, files):
366 if not os.path.exists(f):
369 with open(f, 'r') as src:
370 lines = src.readlines()
371 with open(f, 'w') as dest:
373 for i, uuid in new_uuid.items():
374 line = re.sub(orig[i], uuid, line)
377 def _create_filesystems(self, image, partitions):
378 """Fill the image with data. Host file systems that are not currently
379 mounted are binary copied into the image. For mounted file systems, a
380 file system level copy is performed.
385 for p in self.disk.partitions:
386 filesystem[p.number] = self._get_mount_options(p.path)
387 orig_dev[p.number] = p.path
389 unmounted = filter(lambda p: filesystem[p.num] is None, partitions)
390 mounted = filter(lambda p: filesystem[p.num] is not None, partitions)
392 # For partitions that are not mounted right now, we can simply dd them
395 self.out.output('Cloning partition %d ... ' % p.num, False)
396 dd('if=%s' % self.disk.device.path, 'of=%s' % image,
397 'count=%d' % (p.end - p.start + 1), 'conv=notrunc',
398 'seek=%d' % p.start, 'skip=%d' % p.start)
399 self.out.success("done")
401 loop = str(losetup('-f', '--show', image)).strip()
403 # Recreate mounted file systems
408 mapped[i] = self._map_partition(loop, i, p.start, p.end)
411 # Create the file systems
412 for i, dev in mapped.iteritems():
413 fs = filesystem[i].fs
414 self.out.output('Creating %s filesystem on partition %d ... ' %
416 get_command('mkfs.%s' % fs)(*(MKFS_OPTS[fs] + [dev]))
418 # For ext[234] enable the default mount options
419 if re.match('^ext[234]$', fs):
421 lambda p: p.startswith('Default mount options:'),
422 tune2fs('-l', orig_dev[i]).splitlines()
423 )[0].split(':')[1].strip().split()
425 if not (len(mopts) == 1 and mopts[0] == '(none)'):
427 tune2fs('-o', opt, dev)
429 self.out.success('done')
431 '-s', 'UUID', '-o', 'value', dev).stdout.strip()
433 target = tempfile.mkdtemp()
435 for i in mapped.keys():
436 fs = filesystem[i].fs
437 mpoint = filesystem[i].mpoint
439 for opt in filesystem[i].opts.split(','):
440 if opt in ('acl', 'user_xattr'):
442 devs.append((mapped[i], mpoint, opts))
444 self._mount(target, devs)
446 excluded = self._to_exclude()
448 rsync = Rsync(self.out)
450 for excl in excluded + [image]:
453 rsync.archive().hard_links().xattrs().sparse().acls()
454 rsync.run('/', target, 'host', 'temporary image')
456 # Create missing mountpoints. Since they are mountpoints, we
457 # cannot determine the ownership and the mode of the real
458 # directory. Make them inherit those properties from their
460 for excl in excluded:
461 dirname = os.path.dirname(excl)
462 stat = os.stat(dirname)
463 os.mkdir(target + excl)
464 os.chmod(target + excl, stat.st_mode)
465 os.chown(target + excl, stat.st_uid, stat.st_gid)
467 # /tmp and /var/tmp are special cases. We exclude then even if
468 # they aren't mountpoints. Restore their permissions.
469 for excl in ('/tmp', '/var/tmp'):
470 if self._is_mpoint(excl):
471 os.chmod(target + excl, 041777)
472 os.chown(target + excl, 0, 0)
475 os.chmod(target + excl, stat.st_mode)
476 os.chown(target + excl, stat.st_uid, stat.st_gid)
478 # We need to replace the old UUID referencies with the new
479 # ones in grub configuration files and /etc/fstab for file
480 # systems that have been recreated.
481 self._replace_uuids(target, new_uuid)
484 self._umount_all(target)
487 for dev in mapped.values():
488 self._unmap_partition(dev)
491 def create_image(self, image):
492 """Given an image filename, this method will create an image out of the
496 size = self.disk.device.length * self.disk.device.sectorSize
498 # Create sparse file to host the image
499 fd = os.open(image, os.O_WRONLY | os.O_CREAT)
501 os.ftruncate(fd, size)
505 self._create_partition_table(image)
506 end_sector, partitions = self._shrink_partitions(image)
508 if self.disk.type == 'gpt':
510 size = (end_sector + 1) * self.disk.device.sectorSize
511 ptable = GPTPartitionTable(image)
512 size = ptable.shrink(size, old_size)
515 end_sector = ((end_sector + 2047) // 2048) * 2048
516 size = (end_sector + 1) * self.disk.device.sectorSize
518 # Truncate image to the new size.
519 fd = os.open(image, os.O_RDWR)
521 os.ftruncate(fd, size)
525 # Check if the available space is enough to host the image
526 dirname = os.path.dirname(image)
527 self.out.output("Examining available space ...", False)
528 if free_space(dirname) <= size:
529 raise FatalError("Not enough space under %s to host the temporary "
531 self.out.success("sufficient")
533 self._create_filesystems(image, partitions)
537 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :