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.
38 from collections import namedtuple
40 from image_creator.util import get_command
41 from image_creator.util import FatalError
43 findfs = get_command('findfs')
44 truncate = get_command('truncate')
45 dd = get_command('dd')
50 if not os.path.isfile(f):
51 raise FatalError("Unable to open: `%s'. File is missing." % f)
53 Entry = namedtuple('Entry', 'dev mpoint fs opts freq passno')
55 with open(f) as table:
56 for line in iter(table):
57 entry = line.split('#')[0].strip().split()
63 def get_root_partition():
64 for entry in fstable('/etc/fstab'):
65 if entry.mpoint == '/':
68 raise FatalError("Unable to find root device in /etc/fstab")
72 for entry in fstable('/proc/mounts'):
73 if entry.mpoint == path:
79 for entry in fstable('/proc/mounts'):
80 if not entry.dev.startswith('/'):
83 if os.path.realpath(entry.dev) == os.path.realpath(device):
89 def create_EBRs(src, dest):
91 # The Extended boot records precede the logical partitions they describe
92 extended = src.getExtendedPartition()
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,
103 start = logical[i].geometry.end + 1
106 def bundle_volume(out, meta):
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.')
112 out.output('Searching for root device...', False)
113 root_part = get_root_partition()
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)
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)
123 part_to_dev = lambda p: re.split('[0-9]', p)[0]
125 root_dev = part_to_dev(root_part)
127 out.success('%s' % root_dev)
129 src_dev = parted.Device(root_dev)
131 img = '/mnt/%s.diskdump' % uuid.uuid4().hex
132 disk_size = src_dev.getLength() * src_dev.sectorSize
134 # Create sparse file to host the image
135 truncate("-s", "%d" % disk_size, img)
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')
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
145 dd('if=%s' % src_dev.path, 'of=%s' % img, 'bs=%d' % src_dev.sectorSize,
146 'count=%d' % first_sector, 'conv=notrunc')
148 # Create the Extended boot records (EBRs) in the image
149 create_EBRs(src_disk, img)
151 img_dev = parted.Device(img)
152 img_disk = parted.Disk(img_dev)
154 is_extended = lambda p: p.type == parted.PARTITION_EXTENDED
155 is_logical = lambda p: p.type == parted.PARTITION_LOGICAL
157 Partition = namedtuple('Partition', 'num start end type fs mpoint')
160 for p in src_disk.partitions:
163 partitions.append(Partition(p.number, g.start, g.end, p.type,
164 f.type if f is not None else '', mpoint(p.path)))
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))
172 img_disk.deletePartition(img_disk.getPartitionBySector(last.start))
175 if is_logical(last) and last.num == 5:
176 img_disk.deletePartition(img_disk.getExtendedPartition())
178 partitions.remove(filter(is_extended, partitions)[0])
180 partitions.remove(last)
181 last = partitions[-1]
183 # Leave 2048 blocks at the end
184 new_end = last.end + 2048
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
191 # Add 10% just to be on the safe side
192 part_end = last.start + (new_size * 11) // 10
194 part_end = ((part_end + 2047) // 2048) * 2048
195 last = last._replace(end=part_end)
196 partitions[-1] = last
198 # Leave 2048 blocks at the end.
199 new_end = new_size + 2048
201 img_disk.setPartitionGeometry(
202 img_disk.getPartitionBySector(last.start),
203 parted.Constraint(device=img_dev), start=last.start, end=last.end)
206 if last.type == parted.PARTITION_LOGICAL:
207 # Fix the extended partition
208 ext = disk.getExtendedPartition()
210 img_disk.setPartitionGeometry(ext,
211 parted.Constraint(device=img_dev), ext.geometry.start,
215 # Check if we have the available space on the filesystem hosting /mnt
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
222 if available <= image_size:
223 raise FatalError('Not enough space in /mnt to host the image')
225 out.success("sufficient")
229 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :