Statistics
| Branch: | Tag: | Revision:

root / image_creator / bundle_volume.py @ b0376b3f

History | View | Annotate | Download (16.3 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 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
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
            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()
230

    
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
235

    
236
            new_end = part_end
237

    
238
            if last.type == parted.PARTITION_LOGICAL:
239
                # Fix the extended partition
240
                image_disk.minimizeExtendedPartition()
241

    
242
        return (new_end, self._get_partitions(image_disk))
243

    
244
    def _map_partition(self, dev, num, start, end):
245
        name = os.path.basename(dev) + "_" + uuid.uuid4().hex
246
        tablefd, table = tempfile.mkstemp()
247
        try:
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)
251
        finally:
252
            os.unlink(table)
253

    
254
        return "/dev/mapper/%sp%d" % (name, num)
255

    
256
    def _unmap_partition(self, dev):
257
        if not os.path.exists(dev):
258
            return
259

    
260
        try_fail_repeat(dmsetup, 'remove', dev.split('/dev/mapper/')[1])
261

    
262
    def _mount(self, target, devs):
263

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

    
271
    def _umount_all(self, target):
272
        mpoints = []
273
        for entry in self._read_fstable('/proc/mounts'):
274
            if entry.mpoint.startswith(os.path.abspath(target)):
275
                    mpoints.append(entry.mpoint)
276

    
277
        mpoints.sort()
278
        for mpoint in reversed(mpoints):
279
            try_fail_repeat(umount, mpoint)
280

    
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:
288
                continue
289

    
290
            mpoint = entry.mpoint
291
            if mpoint in excluded:
292
                continue
293

    
294
            descendants = filter(
295
                lambda p: p.startswith(mpoint + '/'), excluded)
296
            if len(descendants):
297
                for d in descendants:
298
                    excluded.remove(d)
299
                excluded.append(mpoint)
300
                continue
301

    
302
            dirname = mpoint
303
            basename = ''
304
            found_ancestor = False
305
            while dirname != '/':
306
                (dirname, basename) = os.path.split(dirname)
307
                if dirname in excluded:
308
                    found_ancestor = True
309
                    break
310

    
311
            if not found_ancestor:
312
                excluded.append(mpoint)
313

    
314
        return excluded
315

    
316
    def _replace_uuids(self, target, new_uuid):
317

    
318
        files = ['/etc/fstab',
319
                 '/boot/grub/grub.cfg',
320
                 '/boot/grub/menu.lst',
321
                 '/boot/grub/grub.conf']
322

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

    
329
        for f in map(lambda f: target + f, files):
330
            if not os.path.exists(f):
331
                continue
332

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

    
341
    def _create_filesystems(self, image, partitions):
342

    
343
        filesystem = {}
344
        for p in self.disk.partitions:
345
            filesystem[p.number] = self._get_mount_options(p.path)
346

    
347
        unmounted = filter(lambda p: filesystem[p.num] is None, partitions)
348
        mounted = filter(lambda p: filesystem[p.num] is not None, partitions)
349

    
350
        # For partitions that are not mounted right now, we can simply dd them
351
        # into the image.
352
        for p in unmounted:
353
            dd('if=%s' % self.disk.device.path, 'of=%s' % image,
354
               'count=%d' % (p.end - p.start + 1), 'conv=notrunc',
355
               'seek=%d' % p.start, 'skip=%d' % p.start)
356

    
357
        loop = str(losetup('-f', '--show', image)).strip()
358
        mapped = {}
359
        try:
360
            for p in mounted:
361
                i = p.num
362
                mapped[i] = self._map_partition(loop, i, p.start, p.end)
363

    
364
            new_uuid = {}
365
            # Create the file systems
366
            for i, dev in mapped.iteritems():
367
                fs = filesystem[i].fs
368
                self.out.output('Creating %s filesystem on partition %d ... ' %
369
                                (fs, i), False)
370
                get_command('mkfs.%s' % fs)(*(MKFS_OPTS[fs] + [dev]))
371
                self.out.success('done')
372
                new_uuid[i] = blkid(
373
                    '-s', 'UUID', '-o', 'value', dev).stdout.strip()
374

    
375
            target = tempfile.mkdtemp()
376
            try:
377
                absmpoints = self._mount(target,
378
                                         [(mapped[i], filesystem[i].mpoint)
379
                                         for i in mapped.keys()])
380
                excluded = self._to_exclude()
381

    
382
                rsync = Rsync(self.out)
383

    
384
                # Excluded paths need to be relative to the source
385
                for excl in map(lambda p: p[1:], excluded + [image]):
386
                    rsync.exclude(excl)
387

    
388
                rsync.archive().hard_links().xattrs().sparse().acls()
389
                rsync.run('/', target, 'host', 'temporary image')
390

    
391
                # Create missing mountpoints. Since they are mountpoints, we
392
                # cannot determine the ownership and the mode of the real
393
                # directory. Make them inherit those properties from their
394
                # parent dir
395
                for excl in excluded:
396
                   dirname = os.path.dirname(excl)
397
                   stat = os.stat(dirname)
398
                   os.mkdir(target + excl, stat.st_mode)
399
                   os.chown(target + excl, stat.st_uid, stat.st_gid)
400

    
401
                # We need to replace the old UUID referencies with the new
402
                # ones in grub configuration files and /etc/fstab for file
403
                # systems that have been recreated.
404
                self._replace_uuids(target, new_uuid)
405

    
406
            finally:
407
                self._umount_all(target)
408
                os.rmdir(target)
409
        finally:
410
            for dev in mapped.values():
411
                self._unmap_partition(dev)
412
            losetup('-d', loop)
413

    
414
    def create_image(self, image):
415
        """Given an image filename, this method will create an image out of the
416
        running system.
417
        """
418

    
419
        size = self.disk.device.length * self.disk.device.sectorSize
420

    
421
        # Create sparse file to host the image
422
        fd = os.open(image, os.O_WRONLY | os.O_CREAT)
423
        try:
424
            os.ftruncate(fd, size)
425
        finally:
426
            os.close(fd)
427

    
428
        self._create_partition_table(image)
429
        end_sector, partitions = self._shrink_partitions(image)
430

    
431
        if self.disk.type == 'gpt':
432
            old_size = size
433
            size = (end_sector + 1) * self.disk.device.sectorSize
434
            ptable = GPTPartitionTable(image)
435
            size = ptable.shrink(size, old_size)
436
        else:
437
            # Alighn to 2048
438
            end_sector = ((end_sector + 2047) // 2048) * 2048
439
            size = (end_sector + 1) * self.disk.device.sectorSize
440

    
441
        # Truncate image to the new size.
442
        fd = os.open(image, os.O_RDWR)
443
        try:
444
            os.ftruncate(fd, size)
445
        finally:
446
            os.close(fd)
447

    
448
        # Check if the available space is enough to host the image
449
        dirname = os.path.dirname(image)
450
        self.out.output("Examining available space ...", False)
451
        if free_space(dirname) <= size:
452
            raise FatalError('Not enough space under %s to host the image' %
453
                             dirname)
454
        self.out.success("sufficient")
455

    
456
        self._create_filesystems(image, partitions)
457

    
458
        return image
459

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