Futher development for bundle_volume
[snf-image-creator] / image_creator / bundle_volume.py
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 parted
37 import uuid
38
39 from image_creator.util import get_command
40 from image_creator.util import FatalError
41
42 findfs = get_command('findfs')
43 truncate = get_command('truncate')
44 dd = get_command('dd')
45
46 def get_root_partition():
47     if not os.path.isfile('/etc/fstab'):
48         raise FatalError("Unable to open `/etc/fstab'. File is missing.")
49
50     with open('/etc/fstab') as fstab:
51         for line in iter(fstab):
52             entry = line.split('#')[0].strip().split()
53             if len(entry) != 6:
54                 continue
55
56             if entry[1] == "/":
57                 return entry[0]
58
59         raise FatalError("Unable to find root device in /etc/fstab")
60
61 def mnt_mounted():
62     if not os.path.isfile('/etc/mtab'):
63         raise FatalError("Unable to open `/etc/fstab'. File is missing.")
64
65     with open('/etc/mtab') as mtab:
66         for line in iter(mtab):
67             entry = line.split('#')[0].strip().split()
68             if len(entry) != 6:
69                 continue
70
71             if entry[1] == '/mnt':
72                 return True
73
74     return False
75
76
77 def part_to_dev(part):
78     return re.split('[0-9]', part)[0]
79
80 def part_to_num(part):
81     return re.split('[^0-9]+', part)[-1]
82
83 def bundle_volume(out):
84
85     if mnt_mounted():
86         raise FatalError('The directory /mnt where the image will be hosted'
87             'is mounted. Please unmount it and start over again.')
88
89     out.output('Searching for root device...', False)
90     root_part = get_root_partition()
91
92     if root_part.startswith("UUID=") or root_part.startswith("LABEL="):
93         root_part = findfs(root_part)
94     elif not root_part.startswith("/"):
95         raise FatalError("Unable to find a block device for: %s" % root_dev)
96
97     if not re.match('/dev/[hsv]d[a-z][1-9]*$', root_part):
98         raise FatalError("Don't know how to handle root device: %s" % root_dev)
99
100     device = parted.Device(part_to_dev(root_part))
101
102     image = '/mnt/%s.diskdump' % uuid.uuid4().hex
103
104     # Create sparse file to host the image
105     truncate("-s", "%d" % (device.getLength() * device.sectorSize), image)
106
107     disk = parted.Disk(device)
108     if disk.type != 'msdos':
109         raise FatalError('For now we can only handle msdos partition tables')
110
111     # Copy the MBR and the space between the MBR and the first partition.
112     # In Grub version 1 Stage 1.5 is located there.
113     first_sector = disk.getPrimaryPartitions()[0].geometry.start
114
115     dd('if=%s' % device.path, 'of=%s' % image, 'bs=%d' % device.sectorSize,
116         'count=%d' % first_sector, 'conv=notrunc')
117
118     return image
119
120 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :