Fix errors introduced in 9517bf29dadbb4f1257f240bc
[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 from collections import namedtuple
39
40 from image_creator.util import get_command
41 from image_creator.util import FatalError
42
43 findfs = get_command('findfs')
44 truncate = get_command('truncate')
45 dd = get_command('dd')
46
47 MB = 2 ** 20
48
49 def fstable(f):
50     if not os.path.isfile(f):
51         raise FatalError("Unable to open: `%s'. File is missing." % f)
52
53     Entry = namedtuple('Entry', 'dev mpoint fs opts freq passno')
54
55     with open(f) as table:
56         for line in iter(table):
57             entry = line.split('#')[0].strip().split()
58             if len(entry) != 6:
59                 continue
60             yield Entry(*entry)
61
62
63 def get_root_partition():
64     for entry in fstable('/etc/fstab'):
65         if entry.mpoint == '/':
66             return entry.dev
67
68     raise FatalError("Unable to find root device in /etc/fstab")
69
70
71 def is_mpoint(path):
72     for entry in fstable('/proc/mounts'):
73         if entry.mpoint == path:
74             return True
75     return False
76
77
78 def mpoint(device):
79     for entry in fstable('/proc/mounts'):
80         if not entry.dev.startswith('/'):
81             continue
82
83         if os.path.realpath(entry.dev) == os.path.realpath(device):
84             return entry.mpoint
85
86     return ""
87
88
89 def create_EBRs(src, dest):
90
91     # The Extended boot records precede the logical partitions they describe
92     extended = src.getExtendedPartition()
93     if not extended:
94         return
95
96     logical = src.getLogicalPartitions()
97     start = extended.geometry.start
98     for i in range(len(logical)):
99         end = logical[i].geometry.start - 1
100         dd('if=%s' % src.device.path, 'of=%s' % dest,
101             'count=%d' % (end - start + 1), 'conv=notrunc', 'seek=%d' % start,
102             'skip=%d' % start)
103         start = logical[i].geometry.end + 1
104
105
106 def bundle_volume(out, meta):
107
108     if is_mpoint('/mnt'):
109         raise FatalError('The directory /mnt where the image will be hosted'
110             'is mounted. Please unmount it and start over again.')
111
112     out.output('Searching for root device...', False)
113     root_part = get_root_partition()
114
115     if root_part.startswith("UUID=") or root_part.startswith("LABEL="):
116         root_part = findfs(root_part).stdout.strip()
117     elif not root_part.startswith("/"):
118         raise FatalError("Unable to find a block device for: %s" % root_dev)
119
120     if not re.match('/dev/[hsv]d[a-z][1-9]*$', root_part):
121         raise FatalError("Don't know how to handle root device: %s" % root_dev)
122
123     part_to_dev = lambda p: re.split('[0-9]', p)[0]
124
125     root_dev = part_to_dev(root_part)
126
127     out.success('%s' % root_dev)
128
129     src_dev = parted.Device(root_dev)
130
131     img = '/mnt/%s.diskdump' % uuid.uuid4().hex
132     disk_size = src_dev.getLength() * src_dev.sectorSize
133
134     # Create sparse file to host the image
135     truncate("-s", "%d" % disk_size, img)
136
137     src_disk = parted.Disk(src_dev)
138     if src_disk.type != 'msdos':
139         raise FatalError('For now we can only handle msdos partition tables')
140
141     # Copy the MBR and the space between the MBR and the first partition.
142     # In Grub version 1 Stage 1.5 is located there.
143     first_sector = src_disk.getPrimaryPartitions()[0].geometry.start
144
145     dd('if=%s' % src_dev.path, 'of=%s' % img, 'bs=%d' % src_dev.sectorSize,
146         'count=%d' % first_sector, 'conv=notrunc')
147
148     # Create the Extended boot records (EBRs) in the image
149     create_EBRs(src_disk, img)
150
151     img_dev = parted.Device(img)
152     img_disk = parted.Disk(img_dev)
153
154     is_extended = lambda p: p.type == parted.PARTITION_EXTENDED
155     is_logical = lambda p: p.type == parted.PARTITION_LOGICAL
156
157     Partition = namedtuple('Partition', 'num start end type fs mpoint')
158
159     partitions = []
160     for p in src_disk.partitions:
161         g = p.geometry
162         f = p.fileSystem
163         partitions.append(Partition(p.number, g.start, g.end, p.type,
164             f.type if f is not None else '', mpoint(p.path)))
165
166     last = partitions[-1]
167     new_end = src_dev.getLength()
168     if last.fs == 'linux-swap(v1)':
169         size = (last.end - last.start + 1) * src_dev.sectorSize
170         meta['SWAP'] = "%d:%s" % (last.num, ((size + MB - 1) // MB))
171         
172         img_disk.deletePartition(img_disk.getPartitionBySector(last.start))
173         img_disk.commit()
174
175         if is_logical(last) and last.num == 5:
176             img_disk.deletePartition(img_disk.getExtendedPartition())
177             img_disk.commit()
178             partitions.remove(filter(is_extended, partitions)[0])
179
180         partitions.remove(last)
181         last = partitions[-1]
182
183         # Leave 2048 blocks at the end
184         new_end = last.end + 2048
185
186     if last.mpoint:
187         stat = os.statvfs(last.mpoint)
188         occupied_blocks = stat.f_blocks - stat.f_bavail
189         new_size = (occupied_blocks * stat.f_frsize) // src_dev.sectorSize
190
191         # Add 10% just to be on the safe side
192         part_end = last.start + (new_size * 11) // 10
193         # Alighn to 2048
194         part_end = ((part_end + 2047) // 2048) * 2048
195         last = last._replace(end=part_end)
196         partitions[-1] = last
197         
198         # Leave 2048 blocks at the end.
199         new_end = new_size + 2048
200
201         img_disk.setPartitionGeometry(
202             img_disk.getPartitionBySector(last.start),
203             parted.Constraint(device=img_dev), start=last.start, end=last.end)
204         img_disk.commit()
205
206         if last.type == parted.PARTITION_LOGICAL:
207             # Fix the extended partition
208             ext = disk.getExtendedPartition()
209
210             img_disk.setPartitionGeometry(ext,
211                 parted.Constraint(device=img_dev), ext.geometry.start,
212                 end=last.end)
213             img_disk.commit()
214
215     # Check if we have the available space on the filesystem hosting /mnt
216     # for the image.
217     out.output("Examining available space in /mnt ... ", False)
218     stat = os.statvfs('/mnt')
219     image_size = (new_end + 1) * src_dev.sectorSize
220     available = stat.f_bavail * stat.f_frsize
221
222     if available <= image_size:
223         raise FatalError('Not enough space in /mnt to host the image')
224
225     out.success("sufficient")
226
227     return img
228
229 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :