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.
37 from collections import namedtuple
41 from image_creator.rsync import Rsync
42 from image_creator.util import get_command
43 from image_creator.util import FatalError
44 from image_creator.util import try_fail_repeat
45 from image_creator.util import free_space
47 findfs = get_command('findfs')
48 dd = get_command('dd')
49 dmsetup = get_command('dmsetup')
50 losetup = get_command('losetup')
51 mount = get_command('mount')
52 umount = get_command('umount')
53 blkid = get_command('blkid')
55 MKFS_OPTS = {'ext2': ['-F'],
68 class BundleVolume(object):
69 """This class can be used to create an image out of the running system"""
71 def __init__(self, out, meta, tmp=None):
72 """Create an instance of the BundleVolume class."""
77 self.out.output('Searching for root device ...', False)
78 root = self._get_root_partition()
80 if root.startswith("UUID=") or root.startswith("LABEL="):
81 root = findfs(root).stdout.strip()
83 if not re.match('/dev/[hsv]d[a-z][1-9]*$', root):
84 raise FatalError("Don't know how to handle root device: %s" % root)
88 disk_file = re.split('[0-9]', root)[0]
89 device = parted.Device(disk_file)
90 self.disk = parted.Disk(device)
92 def _read_fstable(self, f):
94 if not os.path.isfile(f):
95 raise FatalError("Unable to open: `%s'. File is missing." % f)
97 FileSystemTableEntry = namedtuple('FileSystemTableEntry',
98 'dev mpoint fs opts freq passno')
99 with open(f) as table:
100 for line in iter(table):
101 entry = line.split('#')[0].strip().split()
104 yield FileSystemTableEntry(*entry)
106 def _get_root_partition(self):
107 for entry in self._read_fstable('/etc/fstab'):
108 if entry.mpoint == '/':
111 raise FatalError("Unable to find root device in /etc/fstab")
113 def _is_mpoint(self, path):
114 for entry in self._read_fstable('/proc/mounts'):
115 if entry.mpoint == path:
119 def _get_mount_options(self, device):
120 for entry in self._read_fstable('/proc/mounts'):
121 if not entry.dev.startswith('/'):
124 if os.path.realpath(entry.dev) == os.path.realpath(device):
129 def _create_partition_table(self, image):
131 if self.disk.type != 'msdos':
132 raise FatalError('Only msdos partition tables are supported')
134 # Copy the MBR and the space between the MBR and the first partition.
135 # In Grub version 1 Stage 1.5 is located 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 # Create the Extended boot records (EBRs) in the image
143 extended = self.disk.getExtendedPartition()
147 # Extended boot records precede the logical partitions they describe
148 logical = self.disk.getLogicalPartitions()
149 start = extended.geometry.start
150 for i in range(len(logical)):
151 end = logical[i].geometry.start - 1
152 dd('if=%s' % self.disk.device.path, 'of=%s' % image,
153 'count=%d' % (end - start + 1), 'conv=notrunc',
154 'seek=%d' % start, 'skip=%d' % start)
155 start = logical[i].geometry.end + 1
157 def _get_partitions(self, disk):
158 Partition = namedtuple('Partition', 'num start end type fs')
161 for p in disk.partitions:
163 start = p.geometry.start
166 fs = p.fileSystem.type if p.fileSystem is not None else ''
167 partitions.append(Partition(num, start, end, ptype, fs))
171 def _shrink_partitions(self, image):
173 new_end = self.disk.device.length
175 image_dev = parted.Device(image)
176 image_disk = parted.Disk(image_dev)
178 is_extended = lambda p: p.type == parted.PARTITION_EXTENDED
179 is_logical = lambda p: p.type == parted.PARTITION_LOGICAL
181 partitions = self._get_partitions(self.disk)
183 last = partitions[-1]
184 if last.fs == 'linux-swap(v1)':
186 size = (last.end - last.start + 1) * self.disk.device.sectorSize
187 self.meta['SWAP'] = "%d:%s" % (last.num, (size + MB - 1) // MB)
189 image_disk.deletePartition(
190 image_disk.getPartitionBySector(last.start))
193 if is_logical(last) and last.num == 5:
194 extended = image_disk.getExtendedPartition()
195 image_disk.deletePartition(extended)
197 partitions.remove(filter(is_extended, partitions)[0])
199 partitions.remove(last)
200 last = partitions[-1]
202 # Leave 2048 blocks at the end
203 new_end = last.end + 2048
205 mount_options = self._get_mount_options(
206 self.disk.getPartitionBySector(last.start).path)
207 if mount_options is not None:
208 stat = os.statvfs(mount_options.mpoint)
209 # Shrink the last partition. The new size should be the size of the
211 blcks = stat.f_blocks - stat.f_bavail
212 new_size = (blcks * stat.f_frsize) // self.disk.device.sectorSize
214 # Add 10% just to be on the safe side
215 part_end = last.start + (new_size * 11) // 10
217 part_end = ((part_end + 2047) // 2048) * 2048
219 image_disk.setPartitionGeometry(
220 image_disk.getPartitionBySector(last.start),
221 parted.Constraint(device=image_disk.device),
222 start=last.start, end=part_end)
225 # Parted may have changed this for better alignment
226 part_end = image_disk.getPartitionBySector(last.start).geometry.end
227 last = last._replace(end=part_end)
228 partitions[-1] = last
230 # Leave 2048 blocks at the end.
231 new_end = part_end + 2048
233 if last.type == parted.PARTITION_LOGICAL:
234 # Fix the extended partition
235 extended = disk.getExtendedPartition()
237 image_disk.setPartitionGeometry(
238 extended, parted.Constraint(device=img_dev),
239 ext.geometry.start, end=last.end)
242 # image_dev.destroy()
245 def _map_partition(self, dev, num, start, end):
246 name = os.path.basename(dev)
247 tablefd, table = tempfile.mkstemp()
249 size = end - start + 1
250 os.write(tablefd, "0 %d linear %s %d" % (size, dev, start))
251 dmsetup('create', "%sp%d" % (name, num), table)
255 return "/dev/mapper/%sp%d" % (name, num)
257 def _unmap_partition(self, dev):
258 if not os.path.exists(dev):
261 try_fail_repeat(dmsetup, 'remove', dev.split('/dev/mapper/')[1])
263 def _mount(self, target, devs):
265 devs.sort(key=lambda d: d[1])
266 for dev, mpoint in devs:
267 absmpoint = os.path.abspath(target + mpoint)
268 if not os.path.exists(absmpoint):
269 os.makedirs(absmpoint)
270 mount(dev, absmpoint)
272 def _umount_all(self, target):
274 for entry in self._read_fstable('/proc/mounts'):
275 if entry.mpoint.startswith(os.path.abspath(target)):
276 mpoints.append(entry.mpoint)
279 for mpoint in reversed(mpoints):
280 try_fail_repeat(umount, mpoint)
282 def _to_exclude(self):
283 excluded = ['/tmp', '/var/tmp']
284 if self.tmp is not None:
285 excluded.append(self.tmp)
286 local_filesystems = MKFS_OPTS.keys() + ['rootfs']
287 for entry in self._read_fstable('/proc/mounts'):
288 if entry.fs in local_filesystems:
291 mpoint = entry.mpoint
292 if mpoint in excluded:
295 descendants = filter(
296 lambda p: p.startswith(mpoint + '/'), excluded)
298 for d in descendants:
300 excluded.append(mpoint)
305 found_ancestor = False
306 while dirname != '/':
307 (dirname, basename) = os.path.split(dirname)
308 if dirname in excluded:
309 found_ancestor = True
312 if not found_ancestor:
313 excluded.append(mpoint)
317 def _replace_uuids(self, target, new_uuid):
319 files = ['/etc/fstab',
320 '/boot/grub/grub.cfg',
321 '/boot/grub/menu.lst',
322 '/boot/grub/grub.conf']
327 blkid('-s', 'UUID', '-o', 'value', p.path).stdout.strip()),
328 self.disk.partitions))
330 for f in map(lambda f: target + f, files):
332 if not os.path.exists(f):
335 with open(f, 'r') as src:
336 lines = src.readlines()
337 with open(f, 'w') as dest:
339 for i, uuid in new_uuid.items():
340 line = re.sub(orig[i], uuid, line)
343 def _create_filesystems(self, image):
346 for p in self.disk.partitions:
347 filesystem[p.number] = self._get_mount_options(p.path)
349 partitions = self._get_partitions(parted.Disk(parted.Device(image)))
350 unmounted = filter(lambda p: filesystem[p.num] is None, partitions)
351 mounted = filter(lambda p: filesystem[p.num] is not None, partitions)
353 # For partitions that are not mounted right now, we can simply dd them
356 dd('if=%s' % self.disk.device.path, 'of=%s' % image,
357 'count=%d' % (p.end - p.start + 1), 'conv=notrunc',
358 'seek=%d' % p.start, 'skip=%d' % p.start)
360 loop = str(losetup('-f', '--show', image)).strip()
365 mapped[i] = self._map_partition(loop, i, p.start, p.end)
368 # Create the file systems
369 for i, dev in mapped.iteritems():
370 fs = filesystem[i].fs
371 self.out.output('Creating %s filesystem on partition %d ... ' %
373 get_command('mkfs.%s' % fs)(*(MKFS_OPTS[fs] + [dev]))
374 self.out.success('done')
376 '-s', 'UUID', '-o', 'value', dev).stdout.strip()
378 target = tempfile.mkdtemp()
380 absmpoints = self._mount(target,
381 [(mapped[i], filesystem[i].mpoint)
382 for i in mapped.keys()])
383 excluded = self._to_exclude()
385 rsync = Rsync(self.out)
387 # Excluded paths need to be relative to the source
388 for excl in map(lambda p: p[1:], excluded + [image]):
391 rsync.archive().hard_links().xattrs().sparse().acls()
392 rsync.run('/', target, 'host', 'temporary image')
394 # Create missing mountpoints. Since they are mountpoints, we
395 # cannot determine the ownership and the mode of the real
396 # directory. Make them inherit those properties from their
398 for excl in excluded:
399 dirname = os.path.dirname(excl)
400 stat = os.stat(dirname)
401 os.mkdir(target + excl, stat.st_mode)
402 os.chown(target + excl, stat.st_uid, stat.st_gid)
404 # We need to replace the old UUID referencies with the new
405 # ones in grub configuration files and /etc/fstab for file
406 # systems that have been recreated.
407 self._replace_uuids(target, new_uuid)
410 self._umount_all(target)
413 for dev in mapped.values():
414 self._unmap_partition(dev)
417 def create_image(self, image):
418 """Given an image filename, this method will create an image out of the
422 size = self.disk.device.length * self.disk.device.sectorSize
424 # Create sparse file to host the image
425 fd = os.open(image, os.O_WRONLY | os.O_CREAT)
427 os.ftruncate(fd, size)
431 self._create_partition_table(image)
433 end_sector = self._shrink_partitions(image)
435 size = (end_sector + 1) * self.disk.device.sectorSize
437 # Truncate image to the new size.
438 fd = os.open(image, os.O_RDWR)
440 os.ftruncate(fd, size)
444 # Check if the available space is enough to host the image
445 dirname = os.path.dirname(image)
446 self.out.output("Examining available space ...", False)
447 if free_space(dirname) <= size:
448 raise FatalError('Not enough space under %s to host the image' %
450 self.out.success("sufficient")
452 self._create_filesystems(image)
456 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :