Statistics
| Branch: | Tag: | Revision:

root / image_creator / bundle_volume.py @ 61d14323

History | View | Annotate | Download (17.1 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 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
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
            # 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)
229

    
230
            image_disk.setPartitionGeometry(
231
                image_disk.getPartitionBySector(last.start), constraint,
232
                start=last.start, end=part_end)
233
            image_disk.commitToDevice()
234

    
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
239

    
240
            new_end = part_end
241

    
242
            if last.type == parted.PARTITION_LOGICAL:
243
                # Fix the extended partition
244
                image_disk.minimizeExtendedPartition()
245

    
246
        return (new_end, self._get_partitions(image_disk))
247

    
248
    def _map_partition(self, dev, num, start, end):
249
        name = os.path.basename(dev) + "_" + uuid.uuid4().hex
250
        tablefd, table = tempfile.mkstemp()
251
        try:
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)
255
        finally:
256
            os.unlink(table)
257

    
258
        return "/dev/mapper/%sp%d" % (name, num)
259

    
260
    def _unmap_partition(self, dev):
261
        if not os.path.exists(dev):
262
            return
263

    
264
        try_fail_repeat(dmsetup, 'remove', dev.split('/dev/mapper/')[1])
265

    
266
    def _mount(self, target, devs):
267

    
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)
274

    
275
    def _umount_all(self, target):
276
        mpoints = []
277
        for entry in self._read_fstable('/proc/mounts'):
278
            if entry.mpoint.startswith(os.path.abspath(target)):
279
                    mpoints.append(entry.mpoint)
280

    
281
        mpoints.sort()
282
        for mpoint in reversed(mpoints):
283
            try_fail_repeat(umount, mpoint)
284

    
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:
292
                continue
293

    
294
            mpoint = entry.mpoint
295
            if mpoint in excluded:
296
                continue
297

    
298
            descendants = filter(
299
                lambda p: p.startswith(mpoint + '/'), excluded)
300
            if len(descendants):
301
                for d in descendants:
302
                    excluded.remove(d)
303
                excluded.append(mpoint)
304
                continue
305

    
306
            dirname = mpoint
307
            basename = ''
308
            found_ancestor = False
309
            while dirname != '/':
310
                (dirname, basename) = os.path.split(dirname)
311
                if dirname in excluded:
312
                    found_ancestor = True
313
                    break
314

    
315
            if not found_ancestor:
316
                excluded.append(mpoint)
317

    
318
        return excluded
319

    
320
    def _replace_uuids(self, target, new_uuid):
321

    
322
        files = ['/etc/fstab',
323
                 '/boot/grub/grub.cfg',
324
                 '/boot/grub/menu.lst',
325
                 '/boot/grub/grub.conf']
326

    
327
        orig = {}
328
        for p in self.disk.partitions:
329
            if p.number in new_uuid.keys():
330
                orig[p.number] = \
331
                    blkid('-s', 'UUID', '-o', 'value', p.path).stdout.strip()
332

    
333
        for f in map(lambda f: target + f, files):
334
            if not os.path.exists(f):
335
                continue
336

    
337
            with open(f, 'r') as src:
338
                lines = src.readlines()
339
            with open(f, 'w') as dest:
340
                for line in lines:
341
                    for i, uuid in new_uuid.items():
342
                        line = re.sub(orig[i], uuid, line)
343
                    dest.write(line)
344

    
345
    def _create_filesystems(self, image, partitions):
346

    
347
        filesystem = {}
348
        for p in self.disk.partitions:
349
            filesystem[p.number] = self._get_mount_options(p.path)
350

    
351
        unmounted = filter(lambda p: filesystem[p.num] is None, partitions)
352
        mounted = filter(lambda p: filesystem[p.num] is not None, partitions)
353

    
354
        # For partitions that are not mounted right now, we can simply dd them
355
        # into the image.
356
        for p in unmounted:
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")
362

    
363
        loop = str(losetup('-f', '--show', image)).strip()
364
        mapped = {}
365
        try:
366
            for p in mounted:
367
                i = p.num
368
                mapped[i] = self._map_partition(loop, i, p.start, p.end)
369

    
370
            new_uuid = {}
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 ... ' %
375
                                (fs, i), False)
376
                get_command('mkfs.%s' % fs)(*(MKFS_OPTS[fs] + [dev]))
377
                self.out.success('done')
378
                new_uuid[i] = blkid(
379
                    '-s', 'UUID', '-o', 'value', dev).stdout.strip()
380

    
381
            target = tempfile.mkdtemp()
382
            try:
383
                self._mount(
384
                    target,
385
                    [(mapped[i], filesystem[i].mpoint) for i in mapped.keys()])
386

    
387
                excluded = self._to_exclude()
388

    
389
                rsync = Rsync(self.out)
390

    
391
                for excl in excluded + [image]:
392
                    rsync.exclude(excl)
393

    
394
                rsync.archive().hard_links().xattrs().sparse().acls()
395
                rsync.run('/', target, 'host', 'temporary image')
396

    
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
400
                # parent dir
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)
407

    
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)
414
                    else:
415
                        stat = os.stat(excl)
416
                        os.chmod(target + excl, stat.st_mode)
417
                        os.chown(target + excl, stat.st_uid, stat.st_gid)
418

    
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)
423

    
424
            finally:
425
                self._umount_all(target)
426
                os.rmdir(target)
427
        finally:
428
            for dev in mapped.values():
429
                self._unmap_partition(dev)
430
            losetup('-d', loop)
431

    
432
    def create_image(self, image):
433
        """Given an image filename, this method will create an image out of the
434
        running system.
435
        """
436

    
437
        size = self.disk.device.length * self.disk.device.sectorSize
438

    
439
        # Create sparse file to host the image
440
        fd = os.open(image, os.O_WRONLY | os.O_CREAT)
441
        try:
442
            os.ftruncate(fd, size)
443
        finally:
444
            os.close(fd)
445

    
446
        self._create_partition_table(image)
447
        end_sector, partitions = self._shrink_partitions(image)
448

    
449
        if self.disk.type == 'gpt':
450
            old_size = size
451
            size = (end_sector + 1) * self.disk.device.sectorSize
452
            ptable = GPTPartitionTable(image)
453
            size = ptable.shrink(size, old_size)
454
        else:
455
            # Alighn to 2048
456
            end_sector = ((end_sector + 2047) // 2048) * 2048
457
            size = (end_sector + 1) * self.disk.device.sectorSize
458

    
459
        # Truncate image to the new size.
460
        fd = os.open(image, os.O_RDWR)
461
        try:
462
            os.ftruncate(fd, size)
463
        finally:
464
            os.close(fd)
465

    
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 "
471
                             "image" % dirname)
472
        self.out.success("sufficient")
473

    
474
        self._create_filesystems(image, partitions)
475

    
476
        return image
477

    
478
# vim: set sta sts=4 shiftwidth=4 sw=4 et ai :