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
42 from image_creator.util import get_command
43 from image_creator.util import FatalError
45 findfs = get_command('findfs')
46 truncate = get_command('truncate')
47 dd = get_command('dd')
48 dmsetup = get_command('dmsetup')
52 _FileSystemEntry = namedtuple('FileSystemEntry',
53 'dev mpoint fs opts freq passno')
55 _Partition = namedtuple('Partition', 'num start end type fs mopts')
57 def __init__(self, out, meta):
61 self.out.output('Searching for root device...', False)
62 root = self._get_root_partition()
64 if root.startswith("UUID=") or root.startswith("LABEL="):
65 self.root = findfs(root).stdout.strip()
69 if not re.match('/dev/[hsv]d[a-z][1-9]*$', self.root):
70 raise FatalError("Don't know how to handle root device: %s" % \
73 self.disk = re.split('[0-9]', self.root)[0]
75 out.success('%s' % root_dev)
78 if not os.path.isfile(f):
79 raise FatalError("Unable to open: `%s'. File is missing." % f)
81 with open(f) as table:
82 for line in iter(table):
83 entry = line.split('#')[0].strip().split()
86 yield FileSystemEntry(*entry)
88 def _get_root_partition():
89 for entry in self._read_fstable('/etc/fstab'):
90 if entry.mpoint == '/':
93 raise FatalError("Unable to find root device in /etc/fstab")
96 for entry in fstable('/proc/mounts'):
97 if entry.mpoint == path:
101 def _mount_options(device):
102 for entry in fstable('/proc/mounts'):
103 if not entry.dev.startswith('/'):
106 if os.path.realpath(entry.dev) == os.path.realpath(device):
111 def _create_partition_table(src_disk, dest_file):
113 if src_disk.type != 'msdos':
114 raise FatalError('Only msdos partition tables are supported')
116 first_sector = src_disk.getPrimaryPartitions()[0].geometry.start
118 # Copy the MBR and the space between the MBR and the first partition.
119 # In Grub version 1 Stage 1.5 is located there.
120 first_sector = src_disk.getPrimaryPartitions()[0].geometry.start
122 dd('if=%s' % src_disk.device.path, 'of=%s' % dest_file,
123 'bs=%d' % src_disk.device.sectorSize,
124 'count=%d' % first_sector, 'conv=notrunc')
126 # Create the Extended boot records (EBRs) in the image
127 extended = src_disk.getExtendedPartition()
131 # Extended boot records precede the logical partitions they describe
132 logical = src_disk.getLogicalPartitions()
133 start = extended.geometry.start
134 for i in range(len(logical)):
135 end = logical[i].geometry.start - 1
136 dd('if=%s' % src.device.path, 'of=%s' % dest,
137 'count=%d' % (end - start + 1), 'conv=notrunc',
138 'seek=%d' % start, 'skip=%d' % start)
139 start = logical[i].geometry.end + 1
141 def _shrink_partitions(src_disk, image_file):
146 image_dev = parted.Device(image_file)
148 image_disk = parted.Disk(image_dev)
150 is_extended = lambda p: p.type == parted.PARTITION_EXTENDED
151 is_logical = lambda p: p.type == parted.PARTITION_LOGICAL
154 for p in src_disk.partitions:
157 partitions.append(self._Partition(p.number, g.start, g.end,
158 p.type, f.type if f is not None else '',
159 mount_options(p.path)))
161 last = partitions[-1]
162 new_end = src_disk.device.getLength()
163 if last.fs == 'linux-swap(v1)':
165 size = (last.end - last.start + 1) * \
166 src_disk.device.sectorSize
167 meta['SWAP'] = "%d:%s" % (last.num, (size + MB - 1) // MB)
169 img_disk.deletePartition(
170 image_disk.getPartitionBySector(last.start))
173 if is_logical(last) and last.num == 5:
174 extended = image_disk.getExtendedPartition()
175 image_disk.deletePartition(extended)
177 partitions.remove(filter(is_extended, partitions)[0])
179 partitions.remove(last)
180 last = partitions[-1]
182 # Leave 2048 blocks at the end
183 new_end = last.end + 2048
186 stat = os.statvfs(last.mpoint)
187 # Shrink the last partition. The new size should be the
188 # size of the occupied blocks
189 blcks = stat.f_blocks - stat.f_bavail
190 new_size = (blcks * stat.f_frsize) // src_dev.sectorSize
192 # Add 10% just to be on the safe side
193 part_end = last.start + (new_size * 11) // 10
195 part_end = ((part_end + 2047) // 2048) * 2048
196 last = last._replace(end=part_end)
197 partitions[-1] = last
199 # Leave 2048 blocks at the end.
200 new_end = new_size + 2048
202 image_disk.setPartitionGeometry(
203 image_disk.getPartitionBySector(last.start),
204 parted.Constraint(device=image_disk.device),
205 start=last.start, end=last.end)
208 if last.type == parted.PARTITION_LOGICAL:
209 # Fix the extended partition
210 extended = disk.getExtendedPartition()
212 image_disk.setPartitionGeometry(extended,
213 parted.Constraint(device=img_dev),
214 ext.geometry.start, end=last.end)
221 # Check if the available space is enough to host the image
222 location = os.path.dirname(image_file)
223 size = (new_end + 1) * src_disk.device.sectorSize
224 self.out.output("Examining available space in %s" % location, False)
225 stat = os.statvfs(location)
226 available = stat.f_bavail * stat.f_frsize
227 if available <= size:
228 raise FatalError('Not enough space in %s to host the image' % \
230 out.success("sufficient")
234 def _fill_partitions(src_disk, image, partitions):
239 image_file = '/mnt/%s.diskdump' % uuid.uuid4().hex
241 src_dev = parted.Device(self.disk)
243 size = src_dev.getLength() * src_dev.sectorSize
245 # Create sparse file to host the image
246 truncate("-s", "%d" % disk_size, image_file)
248 src_disk = parted.Disk(src_dev)
250 self._create_partition_table(src_disk, image_file)
251 partitions = self._shrink_partitions(src_disk, image_file)
252 self.fill_partitions(src_disk, image_file, partitions)
261 # unmounted = filter(lambda p: not p.mopts.mpoint, partitions)
262 # mounted = filter(lambda p: p.mopts.mpoint, partitions)
264 # for p in unmounted:
265 # dd('if=%s' % src_dev.path, 'of=%s' % img_dev.path,
266 # 'count=%d' % (p.end - p.start + 1), 'conv=notrunc',
267 # 'seek=%d' % p.start, 'skip=%d' % p.start)
269 # partition_devices = create_devices(dest, partitions)
271 # mounted.sort(key=lambda p: p.mopts.mpoint)
275 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :