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 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
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 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()
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
238 if last.type == parted.PARTITION_LOGICAL:
239 # Fix the extended partition
240 image_disk.minimizeExtendedPartition()
242 return (new_end, self._get_partitions(image_disk))
244 def _map_partition(self, dev, num, start, end):
245 name = os.path.basename(dev) + "_" + uuid.uuid4().hex
246 tablefd, table = tempfile.mkstemp()
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)
254 return "/dev/mapper/%sp%d" % (name, num)
256 def _unmap_partition(self, dev):
257 if not os.path.exists(dev):
260 try_fail_repeat(dmsetup, 'remove', dev.split('/dev/mapper/')[1])
262 def _mount(self, target, devs):
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)
271 def _umount_all(self, target):
273 for entry in self._read_fstable('/proc/mounts'):
274 if entry.mpoint.startswith(os.path.abspath(target)):
275 mpoints.append(entry.mpoint)
278 for mpoint in reversed(mpoints):
279 try_fail_repeat(umount, mpoint)
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:
290 mpoint = entry.mpoint
291 if mpoint in excluded:
294 descendants = filter(
295 lambda p: p.startswith(mpoint + '/'), excluded)
297 for d in descendants:
299 excluded.append(mpoint)
304 found_ancestor = False
305 while dirname != '/':
306 (dirname, basename) = os.path.split(dirname)
307 if dirname in excluded:
308 found_ancestor = True
311 if not found_ancestor:
312 excluded.append(mpoint)
316 def _replace_uuids(self, target, new_uuid):
318 files = ['/etc/fstab',
319 '/boot/grub/grub.cfg',
320 '/boot/grub/menu.lst',
321 '/boot/grub/grub.conf']
324 for p in self.disk.partitions:
325 if p.number in new_uuid.keys():
327 blkid('-s', 'UUID', '-o', 'value', p.path).stdout.strip()
329 for f in map(lambda f: target + f, files):
330 if not os.path.exists(f):
333 with open(f, 'r') as src:
334 lines = src.readlines()
335 with open(f, 'w') as dest:
337 for i, uuid in new_uuid.items():
338 line = re.sub(orig[i], uuid, line)
341 def _create_filesystems(self, image, partitions):
344 for p in self.disk.partitions:
345 filesystem[p.number] = self._get_mount_options(p.path)
347 unmounted = filter(lambda p: filesystem[p.num] is None, partitions)
348 mounted = filter(lambda p: filesystem[p.num] is not None, partitions)
350 # For partitions that are not mounted right now, we can simply dd them
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")
359 loop = str(losetup('-f', '--show', image)).strip()
364 mapped[i] = self._map_partition(loop, i, p.start, p.end)
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 ... ' %
372 get_command('mkfs.%s' % fs)(*(MKFS_OPTS[fs] + [dev]))
373 self.out.success('done')
375 '-s', 'UUID', '-o', 'value', dev).stdout.strip()
377 target = tempfile.mkdtemp()
379 absmpoints = self._mount(target,
380 [(mapped[i], filesystem[i].mpoint)
381 for i in mapped.keys()])
382 excluded = self._to_exclude()
384 rsync = Rsync(self.out)
386 # Excluded paths need to be relative to the source
387 for excl in map(lambda p: p[1:], excluded + [image]):
390 rsync.archive().hard_links().xattrs().sparse().acls()
391 rsync.run('/', target, 'host', 'temporary image')
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
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)
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)
409 self._umount_all(target)
412 for dev in mapped.values():
413 self._unmap_partition(dev)
416 def create_image(self, image):
417 """Given an image filename, this method will create an image out of the
421 size = self.disk.device.length * self.disk.device.sectorSize
423 # Create sparse file to host the image
424 fd = os.open(image, os.O_WRONLY | os.O_CREAT)
426 os.ftruncate(fd, size)
430 self._create_partition_table(image)
431 end_sector, partitions = self._shrink_partitions(image)
433 if self.disk.type == 'gpt':
435 size = (end_sector + 1) * self.disk.device.sectorSize
436 ptable = GPTPartitionTable(image)
437 size = ptable.shrink(size, old_size)
440 end_sector = ((end_sector + 2047) // 2048) * 2048
441 size = (end_sector + 1) * self.disk.device.sectorSize
443 # Truncate image to the new size.
444 fd = os.open(image, os.O_RDWR)
446 os.ftruncate(fd, size)
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' %
456 self.out.success("sufficient")
458 self._create_filesystems(image, partitions)
462 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :