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')
49 if not os.path.isfile(f):
50 raise FatalError("Unable to open: `%s'. File is missing." % f)
52 Entry = namedtuple('Entry', 'dev mpoint fs opts freq passno')
54 with open(f) as table:
55 for line in iter(table):
56 entry = line.split('#')[0].strip().split()
62 def get_root_partition():
63 for entry in fstable('/etc/fstab'):
64 if entry.mpoint == '/':
67 raise FatalError("Unable to find root device in /etc/fstab")
71 for entry in fstable('/proc/mounts'):
72 if entry.mpoint == path:
78 for entry in fstable('/proc/mounts'):
79 if not entry.dev.startswith('/'):
82 if os.path.realpath(entry.dev) == os.path.realpath(device):
88 def create_EBRs(src, dest):
90 # The Extended boot records precede the logical partitions they describe
91 extended = src.getExtendedPartition()
95 logical = src.getLogicalPartitions()
96 start = extended.geometry.start
97 for l in range(len(logical)):
98 end = l.geometry.start - 1
99 dd('if=%s' % src.path, 'of=%s' % dest, 'count=%d' % (end - start + 1),
100 'conv=notrunc', 'seek=%d' % start, 'skip=%d' % start)
101 start = l.geometry.end + 1
104 def bundle_volume(out, meta):
106 if is_mpoint('/mnt'):
107 raise FatalError('The directory /mnt where the image will be hosted'
108 'is mounted. Please unmount it and start over again.')
110 out.output('Searching for root device...', False)
111 root_part = get_root_partition()
113 if root_part.startswith("UUID=") or root_part.startswith("LABEL="):
114 root_part = findfs(root_part)
115 elif not root_part.startswith("/"):
116 raise FatalError("Unable to find a block device for: %s" % root_dev)
118 if not re.match('/dev/[hsv]d[a-z][1-9]*$', root_part):
119 raise FatalError("Don't know how to handle root device: %s" % root_dev)
121 part_to_dev = lambda p: re.split('[0-9]', p)[0]
123 root_dev = part_to_dev(root_part)
125 out.success('%s' % root_dev)
127 src_dev = parted.Device(root_dev)
129 img = '/mnt/%s.diskdump' % uuid.uuid4().hex
130 disk_size = src_dev.getLength() * src_dev.sectorSize
132 # Create sparse file to host the image
133 truncate("-s", "%d" % disk_size, img)
135 src_disk = parted.Disk(src_dev)
136 if src_disk.type != 'msdos':
137 raise FatalError('For now we can only handle msdos partition tables')
139 # Copy the MBR and the space between the MBR and the first partition.
140 # In Grub version 1 Stage 1.5 is located there.
141 first_sector = src_disk.getPrimaryPartitions()[0].geometry.start
143 dd('if=%s' % src_dev.path, 'of=%s' % img, 'bs=%d' % src_dev.sectorSize,
144 'count=%d' % first_sector, 'conv=notrunc')
146 # Create the Extended boot records (EBRs) in the image
147 create_EBRs(src_disk, img)
149 img_dev = parted.Device(img)
150 img_disk = parted.Disk(img_dev)
152 Partition = namedtuple('Partition', 'num start end type fs mpoint')
155 for p in src_disk.partitions:
158 partitions.append(Partition(p.number, g.start, g.end, p.type,
159 f.type if f is not None else '', mpoint(p.path)))
161 last = partitions[-1]
162 new_end = src_dev.getLength()
163 if last.fs == 'linux-swap(v1)':
164 size = (last.end - last.start + 1) * src_dev.sectorSize
166 meta['SWAP'] = "%d:%s" % (last.num, ((size + MB - 1) // MB))
167 img_disk.deletePartition(img_disk.getPartitionBySector(last.start))
168 if last.type == parted.PARTITION_LOGICAL and last.num == 5:
169 img_disk.deletePartition(img_disk.getExtendedPartition())
170 partitions.remove(last)
171 last = partitions[-1]
173 # Leave 2048 blocks at the end
174 new_end = last.end + 2048
177 stat = statvfs(last.mpoint)
178 occupied_blocks = stat.f_blocks - stat.f_bavail
179 new_size = (occupied * stat.f_frsize) // src_dev.sectorSize
180 # Add 10% just to be on the safe side
181 last.end = last.start + (new_size * 11) // 10
184 last.end = ((last.end + 2047) // 2048) * 2048
186 # Leave 2048 blocks at the end.
187 new_end = new_size + 2048
189 img_disk.setPartitionGeometry(
190 img_disk.getPartitionBySector(last.start),
191 parted.Constraint(device=img_dev), start=last.star, end=last.end)
193 if last.type == parted.PARTITION_LOGICAL:
194 # Fix the extended partition
195 ext = disk.getExtendedPartition()
197 img_disk.setPartitionGeometry(ext,
198 parted.Constraint(device=img_dev), ext.geometry.start,
201 # Check if we have the available space on the filesystem hosting /mnt
203 out.output("Examining available space in /mnt ... ", False)
204 stat = os.statvfs('/mnt')
205 image_size = (new_end + 1) * src_dev.sectorSize
206 available = stat.f_bavail * stat.f_frsize
208 if available <= image_size:
209 raise FatalError('Not enough space in /mnt to host the image')
211 out.success("sufficient")
215 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :