1 # Copyright 2012 GRNET S.A. All rights reserved.
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
7 # 1. Redistributions of source code must retain the above
8 # copyright notice, this list of conditions and the following
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.
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.
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.
38 from collections import namedtuple
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
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')
57 MKFS_OPTS = {'ext2': ['-F'],
70 class BundleVolume(object):
71 """This class can be used to create an image out of the running system"""
73 def __init__(self, out, meta, tmp=None):
74 """Create an instance of the BundleVolume class."""
79 self.out.output('Searching for root device ...', False)
80 root = self._get_root_partition()
82 if root.startswith("UUID=") or root.startswith("LABEL="):
83 root = findfs(root).stdout.strip()
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)
90 disk_file = re.split('[0-9]', root)[0]
91 device = parted.Device(disk_file)
92 self.disk = parted.Disk(device)
94 def _read_fstable(self, f):
96 if not os.path.isfile(f):
97 raise FatalError("Unable to open: `%s'. File is missing." % f)
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()
106 yield FileSystemTableEntry(*entry)
108 def _get_root_partition(self):
109 for entry in self._read_fstable('/etc/fstab'):
110 if entry.mpoint == '/':
113 raise FatalError("Unable to find root device in /etc/fstab")
115 def _is_mpoint(self, path):
116 for entry in self._read_fstable('/proc/mounts'):
117 if entry.mpoint == path:
121 def _get_mount_options(self, device):
122 for entry in self._read_fstable('/proc/mounts'):
123 if not entry.dev.startswith('/'):
126 if os.path.realpath(entry.dev) == os.path.realpath(device):
131 def _create_partition_table(self, image):
133 # Copy the MBR and the space between the MBR and the first partition.
134 # In msdos partition 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
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')
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)
150 # Create the Extended boot records (EBRs) in the image
151 extended = self.disk.getExtendedPartition()
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
165 def _get_partitions(self, disk):
166 Partition = namedtuple('Partition', 'num start end type fs')
169 for p in disk.partitions:
171 start = p.geometry.start
174 fs = p.fileSystem.type if p.fileSystem is not None else ''
175 partitions.append(Partition(num, start, end, ptype, fs))
179 def _shrink_partitions(self, image):
181 new_end = self.disk.device.length
183 image_disk = parted.Disk(parted.Device(image))
185 is_extended = lambda p: p.type == parted.PARTITION_EXTENDED
186 is_logical = lambda p: p.type == parted.PARTITION_LOGICAL
188 partitions = self._get_partitions(self.disk)
190 last = partitions[-1]
191 if last.fs == 'linux-swap(v1)':
193 size = (last.end - last.start + 1) * self.disk.device.sectorSize
194 self.meta['SWAP'] = "%d:%s" % (last.num, (size + MB - 1) // MB)
196 image_disk.deletePartition(
197 image_disk.getPartitionBySector(last.start))
198 image_disk.commitToDevice()
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])
206 partitions.remove(last)
207 last = partitions[-1]
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
217 blcks = stat.f_blocks - stat.f_bavail
218 new_size = (blcks * stat.f_frsize) // self.disk.device.sectorSize
220 # Add 10% just to be on the safe side
221 part_end = last.start + (new_size * 11) // 10
223 part_end = ((part_end + 2047) // 2048) * 2048
225 # Make sure the partition starts where the old partition started.
226 constraint = parted.Constraint(device=image_disk.device)
227 constraint.startRange = parted.Geometry(device=image_disk.device,
228 start=last.start, length=1)
230 image_disk.setPartitionGeometry(
231 image_disk.getPartitionBySector(last.start), constraint,
232 start=last.start, end=part_end)
233 image_disk.commitToDevice()
235 # Parted may have changed this for better alignment
236 part_end = image_disk.getPartitionBySector(last.start).geometry.end
237 last = last._replace(end=part_end)
238 partitions[-1] = last
242 if last.type == parted.PARTITION_LOGICAL:
243 # Fix the extended partition
244 image_disk.minimizeExtendedPartition()
246 return (new_end, self._get_partitions(image_disk))
248 def _map_partition(self, dev, num, start, end):
249 name = os.path.basename(dev) + "_" + uuid.uuid4().hex
250 tablefd, table = tempfile.mkstemp()
252 size = end - start + 1
253 os.write(tablefd, "0 %d linear %s %d" % (size, dev, start))
254 dmsetup('create', "%sp%d" % (name, num), table)
258 return "/dev/mapper/%sp%d" % (name, num)
260 def _unmap_partition(self, dev):
261 if not os.path.exists(dev):
264 try_fail_repeat(dmsetup, 'remove', dev.split('/dev/mapper/')[1])
266 def _mount(self, target, devs):
268 devs.sort(key=lambda d: d[1])
269 for dev, mpoint in devs:
270 absmpoint = os.path.abspath(target + mpoint)
271 if not os.path.exists(absmpoint):
272 os.makedirs(absmpoint)
273 mount(dev, absmpoint)
275 def _umount_all(self, target):
277 for entry in self._read_fstable('/proc/mounts'):
278 if entry.mpoint.startswith(os.path.abspath(target)):
279 mpoints.append(entry.mpoint)
282 for mpoint in reversed(mpoints):
283 try_fail_repeat(umount, mpoint)
285 def _to_exclude(self):
286 excluded = ['/tmp', '/var/tmp']
287 if self.tmp is not None:
288 excluded.append(self.tmp)
289 local_filesystems = MKFS_OPTS.keys() + ['rootfs']
290 for entry in self._read_fstable('/proc/mounts'):
291 if entry.fs in local_filesystems:
294 mpoint = entry.mpoint
295 if mpoint in excluded:
298 descendants = filter(
299 lambda p: p.startswith(mpoint + '/'), excluded)
301 for d in descendants:
303 excluded.append(mpoint)
308 found_ancestor = False
309 while dirname != '/':
310 (dirname, basename) = os.path.split(dirname)
311 if dirname in excluded:
312 found_ancestor = True
315 if not found_ancestor:
316 excluded.append(mpoint)
320 def _replace_uuids(self, target, new_uuid):
322 files = ['/etc/fstab',
323 '/boot/grub/grub.cfg',
324 '/boot/grub/menu.lst',
325 '/boot/grub/grub.conf']
328 for p in self.disk.partitions:
329 if p.number in new_uuid.keys():
331 blkid('-s', 'UUID', '-o', 'value', p.path).stdout.strip()
333 for f in map(lambda f: target + f, files):
334 if not os.path.exists(f):
337 with open(f, 'r') as src:
338 lines = src.readlines()
339 with open(f, 'w') as dest:
341 for i, uuid in new_uuid.items():
342 line = re.sub(orig[i], uuid, line)
345 def _create_filesystems(self, image, partitions):
348 for p in self.disk.partitions:
349 filesystem[p.number] = self._get_mount_options(p.path)
351 unmounted = filter(lambda p: filesystem[p.num] is None, partitions)
352 mounted = filter(lambda p: filesystem[p.num] is not None, partitions)
354 # For partitions that are not mounted right now, we can simply dd them
357 self.out.output('Cloning partition %d ... ' % p.num, False)
358 dd('if=%s' % self.disk.device.path, 'of=%s' % image,
359 'count=%d' % (p.end - p.start + 1), 'conv=notrunc',
360 'seek=%d' % p.start, 'skip=%d' % p.start)
361 self.out.success("done")
363 loop = str(losetup('-f', '--show', image)).strip()
368 mapped[i] = self._map_partition(loop, i, p.start, p.end)
371 # Create the file systems
372 for i, dev in mapped.iteritems():
373 fs = filesystem[i].fs
374 self.out.output('Creating %s filesystem on partition %d ... ' %
376 get_command('mkfs.%s' % fs)(*(MKFS_OPTS[fs] + [dev]))
377 self.out.success('done')
379 '-s', 'UUID', '-o', 'value', dev).stdout.strip()
381 target = tempfile.mkdtemp()
385 [(mapped[i], filesystem[i].mpoint) for i in mapped.keys()])
387 excluded = self._to_exclude()
389 rsync = Rsync(self.out)
391 for excl in excluded + [image]:
394 rsync.archive().hard_links().xattrs().sparse().acls()
395 rsync.run('/', target, 'host', 'temporary image')
397 # Create missing mountpoints. Since they are mountpoints, we
398 # cannot determine the ownership and the mode of the real
399 # directory. Make them inherit those properties from their
401 for excl in excluded:
402 dirname = os.path.dirname(excl)
403 stat = os.stat(dirname)
404 os.mkdir(target + excl)
405 os.chmod(target + excl, stat.st_mode)
406 os.chown(target + excl, stat.st_uid, stat.st_gid)
408 # /tmp and /var/tmp are special cases. We exclude then even if
409 # they aren't mountpoints. Restore their permissions.
410 for excl in ('/tmp', '/var/tmp'):
411 if self._is_mpoint(excl):
412 os.chmod(target + excl, 041777)
413 os.chown(target + excl, 0, 0)
416 os.chmod(target + excl, stat.st_mode)
417 os.chown(target + excl, stat.st_uid, stat.st_gid)
419 # We need to replace the old UUID referencies with the new
420 # ones in grub configuration files and /etc/fstab for file
421 # systems that have been recreated.
422 self._replace_uuids(target, new_uuid)
425 self._umount_all(target)
428 for dev in mapped.values():
429 self._unmap_partition(dev)
432 def create_image(self, image):
433 """Given an image filename, this method will create an image out of the
437 size = self.disk.device.length * self.disk.device.sectorSize
439 # Create sparse file to host the image
440 fd = os.open(image, os.O_WRONLY | os.O_CREAT)
442 os.ftruncate(fd, size)
446 self._create_partition_table(image)
447 end_sector, partitions = self._shrink_partitions(image)
449 if self.disk.type == 'gpt':
451 size = (end_sector + 1) * self.disk.device.sectorSize
452 ptable = GPTPartitionTable(image)
453 size = ptable.shrink(size, old_size)
456 end_sector = ((end_sector + 2047) // 2048) * 2048
457 size = (end_sector + 1) * self.disk.device.sectorSize
459 # Truncate image to the new size.
460 fd = os.open(image, os.O_RDWR)
462 os.ftruncate(fd, size)
466 # Check if the available space is enough to host the image
467 dirname = os.path.dirname(image)
468 self.out.output("Examining available space ...", False)
469 if free_space(dirname) <= size:
470 raise FatalError("Not enough space under %s to host the temporary "
472 self.out.success("sufficient")
474 self._create_filesystems(image, partitions)
478 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :