35 |
35 |
import re
|
36 |
36 |
import uuid
|
37 |
37 |
import tempfile
|
|
38 |
import time
|
38 |
39 |
from collections import namedtuple
|
39 |
40 |
|
40 |
41 |
import parted
|
... | ... | |
46 |
47 |
truncate = get_command('truncate')
|
47 |
48 |
dd = get_command('dd')
|
48 |
49 |
dmsetup = get_command('dmsetup')
|
|
50 |
losetup = get_command('losetup')
|
|
51 |
mount = get_command('mount')
|
|
52 |
umount = get_command('umount')
|
|
53 |
|
|
54 |
MKFS_OPTS = {
|
|
55 |
'ext2': ['-F'],
|
|
56 |
'ext3': ['-F'],
|
|
57 |
'ext4': ['-F'],
|
|
58 |
'reiserfs': ['-ff'],
|
|
59 |
'btrfs': [],
|
|
60 |
'minix': [],
|
|
61 |
'xfs': ['-f'],
|
|
62 |
'jfs': ['-f'],
|
|
63 |
'ntfs': ['-F'],
|
|
64 |
'msdos': [],
|
|
65 |
'vfat': []
|
|
66 |
}
|
49 |
67 |
|
50 |
68 |
|
51 |
69 |
class BundleVolume():
|
52 |
|
_FileSystemEntry = namedtuple('FileSystemEntry',
|
53 |
|
'dev mpoint fs opts freq passno')
|
54 |
|
|
55 |
|
_Partition = namedtuple('Partition', 'num start end type fs mopts')
|
56 |
70 |
|
57 |
71 |
def __init__(self, out, meta):
|
58 |
72 |
self.out = out
|
... | ... | |
62 |
76 |
root = self._get_root_partition()
|
63 |
77 |
|
64 |
78 |
if root.startswith("UUID=") or root.startswith("LABEL="):
|
65 |
|
self.root = findfs(root).stdout.strip()
|
66 |
|
else:
|
67 |
|
self.root = root
|
|
79 |
root = findfs(root).stdout.strip()
|
68 |
80 |
|
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" % \
|
71 |
|
self.root)
|
|
81 |
if not re.match('/dev/[hsv]d[a-z][1-9]*$', root):
|
|
82 |
raise FatalError("Don't know how to handle root device: %s" % root)
|
72 |
83 |
|
73 |
|
self.disk = re.split('[0-9]', self.root)[0]
|
|
84 |
out.success(root)
|
74 |
85 |
|
75 |
|
out.success('%s' % self.root)
|
|
86 |
disk_file = re.split('[0-9]', root)[0]
|
|
87 |
device = parted.Device(disk_file)
|
|
88 |
self.disk = parted.Disk(device)
|
76 |
89 |
|
77 |
90 |
def _read_fstable(self, f):
|
|
91 |
|
78 |
92 |
if not os.path.isfile(f):
|
79 |
93 |
raise FatalError("Unable to open: `%s'. File is missing." % f)
|
80 |
94 |
|
|
95 |
FileSystemEntry = namedtuple('FileSystemEntry',
|
|
96 |
'dev mpoint fs opts freq passno')
|
81 |
97 |
with open(f) as table:
|
82 |
98 |
for line in iter(table):
|
83 |
99 |
entry = line.split('#')[0].strip().split()
|
84 |
100 |
if len(entry) != 6:
|
85 |
101 |
continue
|
86 |
|
yield self._FileSystemEntry(*entry)
|
|
102 |
yield FileSystemEntry(*entry)
|
87 |
103 |
|
88 |
104 |
def _get_root_partition(self):
|
89 |
105 |
for entry in self._read_fstable('/etc/fstab'):
|
... | ... | |
98 |
114 |
return True
|
99 |
115 |
return False
|
100 |
116 |
|
101 |
|
def _mount_options(self, device):
|
|
117 |
def _get_mount_options(self, device):
|
102 |
118 |
for entry in self._read_fstable('/proc/mounts'):
|
103 |
119 |
if not entry.dev.startswith('/'):
|
104 |
120 |
continue
|
... | ... | |
106 |
122 |
if os.path.realpath(entry.dev) == os.path.realpath(device):
|
107 |
123 |
return entry
|
108 |
124 |
|
109 |
|
return
|
|
125 |
return None
|
110 |
126 |
|
111 |
|
def _create_partition_table(self, src_disk, dest_file):
|
|
127 |
def _create_partition_table(self, image):
|
112 |
128 |
|
113 |
|
if src_disk.type != 'msdos':
|
|
129 |
if self.disk.type != 'msdos':
|
114 |
130 |
raise FatalError('Only msdos partition tables are supported')
|
115 |
131 |
|
116 |
|
first_sector = src_disk.getPrimaryPartitions()[0].geometry.start
|
117 |
|
|
118 |
132 |
# Copy the MBR and the space between the MBR and the first partition.
|
119 |
133 |
# In Grub version 1 Stage 1.5 is located there.
|
120 |
|
first_sector = src_disk.getPrimaryPartitions()[0].geometry.start
|
|
134 |
first_sector = self.disk.getPrimaryPartitions()[0].geometry.start
|
121 |
135 |
|
122 |
|
dd('if=%s' % src_disk.device.path, 'of=%s' % dest_file,
|
123 |
|
'bs=%d' % src_disk.device.sectorSize,
|
|
136 |
dd('if=%s' % self.disk.device.path, 'of=%s' % image,
|
|
137 |
'bs=%d' % self.disk.device.sectorSize,
|
124 |
138 |
'count=%d' % first_sector, 'conv=notrunc')
|
125 |
139 |
|
126 |
140 |
# Create the Extended boot records (EBRs) in the image
|
127 |
|
extended = src_disk.getExtendedPartition()
|
|
141 |
extended = self.disk.getExtendedPartition()
|
128 |
142 |
if not extended:
|
129 |
143 |
return
|
130 |
144 |
|
131 |
145 |
# Extended boot records precede the logical partitions they describe
|
132 |
|
logical = src_disk.getLogicalPartitions()
|
|
146 |
logical = self.disk.getLogicalPartitions()
|
133 |
147 |
start = extended.geometry.start
|
134 |
148 |
for i in range(len(logical)):
|
135 |
149 |
end = logical[i].geometry.start - 1
|
136 |
|
dd('if=%s' % src_disk.device.path, 'of=%s' % dest_file,
|
|
150 |
dd('if=%s' % self.disk.device.path, 'of=%s' % image,
|
137 |
151 |
'count=%d' % (end - start + 1), 'conv=notrunc',
|
138 |
152 |
'seek=%d' % start, 'skip=%d' % start)
|
139 |
153 |
start = logical[i].geometry.end + 1
|
140 |
154 |
|
141 |
|
def _shrink_partitions(self, src_disk, image_file):
|
|
155 |
def _get_partitions(self, disk):
|
|
156 |
Partition = namedtuple('Partition', 'num start end type fs')
|
142 |
157 |
|
143 |
158 |
partitions = []
|
144 |
|
new_end = 0
|
|
159 |
for p in disk.partitions:
|
|
160 |
num = p.number
|
|
161 |
start = p.geometry.start
|
|
162 |
end = p.geometry.end
|
|
163 |
ptype = p.type
|
|
164 |
fs = p.fileSystem.type if p.fileSystem is not None else ''
|
|
165 |
partitions.append(Partition(num, start, end, ptype, fs))
|
|
166 |
|
|
167 |
return partitions
|
|
168 |
|
|
169 |
def _shrink_partitions(self, image):
|
145 |
170 |
|
146 |
|
image_dev = parted.Device(image_file)
|
|
171 |
new_end = self.disk.device.getLength()
|
|
172 |
|
|
173 |
image_dev = parted.Device(image)
|
147 |
174 |
image_disk = parted.Disk(image_dev)
|
148 |
175 |
|
149 |
176 |
is_extended = lambda p: p.type == parted.PARTITION_EXTENDED
|
150 |
177 |
is_logical = lambda p: p.type == parted.PARTITION_LOGICAL
|
151 |
178 |
|
152 |
|
partitions = []
|
153 |
|
for p in src_disk.partitions:
|
154 |
|
g = p.geometry
|
155 |
|
f = p.fileSystem
|
156 |
|
partitions.append(self._Partition(p.number, g.start, g.end,
|
157 |
|
p.type, f.type if f is not None else '',
|
158 |
|
self._mount_options(p.path)))
|
|
179 |
partitions = self._get_partitions(self.disk)
|
159 |
180 |
|
160 |
181 |
last = partitions[-1]
|
161 |
|
new_end = src_disk.device.getLength()
|
162 |
182 |
if last.fs == 'linux-swap(v1)':
|
163 |
183 |
MB = 2 ** 20
|
164 |
|
size = (last.end - last.start + 1) * src_disk.device.sectorSize
|
|
184 |
size = (last.end - last.start + 1) * self.disk.device.sectorSize
|
165 |
185 |
self.meta['SWAP'] = "%d:%s" % (last.num, (size + MB - 1) // MB)
|
166 |
186 |
|
167 |
187 |
image_disk.deletePartition(
|
... | ... | |
180 |
200 |
# Leave 2048 blocks at the end
|
181 |
201 |
new_end = last.end + 2048
|
182 |
202 |
|
183 |
|
if last.mopts.mpoint:
|
184 |
|
stat = os.statvfs(last.mopts.mpoint)
|
185 |
|
# Shrink the last partition. The new size should be the
|
186 |
|
# size of the occupied blocks
|
|
203 |
mount_options = self._get_mount_options(
|
|
204 |
self.disk.getPartitionBySector(last.start).path)
|
|
205 |
if mount_options is not None:
|
|
206 |
stat = os.statvfs(mount_options.mpoint)
|
|
207 |
# Shrink the last partition. The new size should be the size of the
|
|
208 |
# occupied blocks
|
187 |
209 |
blcks = stat.f_blocks - stat.f_bavail
|
188 |
|
new_size = (blcks * stat.f_frsize) // src_disk.device.sectorSize
|
|
210 |
new_size = (blcks * stat.f_frsize) // self.disk.device.sectorSize
|
189 |
211 |
|
190 |
212 |
# Add 10% just to be on the safe side
|
191 |
213 |
part_end = last.start + (new_size * 11) // 10
|
192 |
214 |
# Alighn to 2048
|
193 |
215 |
part_end = ((part_end + 2047) // 2048) * 2048
|
194 |
|
last = last._replace(end=part_end)
|
195 |
|
partitions[-1] = last
|
196 |
|
|
197 |
|
# Leave 2048 blocks at the end.
|
198 |
|
new_end = new_size + 2048
|
199 |
216 |
|
200 |
217 |
image_disk.setPartitionGeometry(
|
201 |
218 |
image_disk.getPartitionBySector(last.start),
|
... | ... | |
203 |
220 |
start=last.start, end=last.end)
|
204 |
221 |
image_disk.commit()
|
205 |
222 |
|
|
223 |
# Parted may have changed this for better alignment
|
|
224 |
part_end = image_disk.getPartitionBySector(last.start).geometry.end
|
|
225 |
last = last._replace(end=part_end)
|
|
226 |
partitions[-1] = last
|
|
227 |
|
|
228 |
# Leave 2048 blocks at the end.
|
|
229 |
new_end = new_size + 2048
|
|
230 |
|
|
231 |
|
206 |
232 |
if last.type == parted.PARTITION_LOGICAL:
|
207 |
233 |
# Fix the extended partition
|
208 |
234 |
extended = disk.getExtendedPartition()
|
... | ... | |
212 |
238 |
ext.geometry.start, end=last.end)
|
213 |
239 |
image_disk.commit()
|
214 |
240 |
|
215 |
|
# Check if the available space is enough to host the image
|
216 |
|
location = os.path.dirname(image_file)
|
217 |
|
size = (new_end + 1) * src_disk.device.sectorSize
|
218 |
|
self.out.output("Examining available space in %s..." % location, False)
|
219 |
|
stat = os.statvfs(location)
|
220 |
|
available = stat.f_bavail * stat.f_frsize
|
221 |
|
if available <= size:
|
222 |
|
raise FatalError('Not enough space in %s to host the image' % \
|
223 |
|
location)
|
224 |
|
self.out.success("sufficient")
|
|
241 |
return new_end
|
225 |
242 |
|
226 |
|
return partitions
|
|
243 |
def _map_partition(self, dev, num, start, end):
|
|
244 |
name = os.path.basename(dev)
|
|
245 |
tablefd, table = tempfile.mkstemp()
|
|
246 |
try:
|
|
247 |
size = end - start + 1
|
|
248 |
os.write(tablefd, "0 %d linear %s %d" % (size, dev, start))
|
|
249 |
dmsetup('create', "%sp%d" % (name, num), table)
|
|
250 |
finally:
|
|
251 |
os.unlink(table)
|
227 |
252 |
|
228 |
|
def _fill_partitions(self, src_disk, image, partitions):
|
229 |
|
pass
|
|
253 |
return "/dev/mapper/%sp%d" % (name, num)
|
230 |
254 |
|
231 |
|
def create_image(self):
|
|
255 |
def _unmap_partition(self, dev):
|
|
256 |
if not os.path.exists(dev):
|
|
257 |
return
|
232 |
258 |
|
233 |
|
image_file = '/mnt/%s.diskdump' % uuid.uuid4().hex
|
|
259 |
dmsetup('remove', dev.split('/dev/mapper/')[1])
|
|
260 |
time.sleep(0.1)
|
234 |
261 |
|
235 |
|
src_dev = parted.Device(self.disk)
|
|
262 |
def _mount(self, target, devs):
|
|
263 |
|
|
264 |
devs.sort(key=lambda d: d[1])
|
|
265 |
for dev, mpoint in devs:
|
|
266 |
absmpoint = os.path.abspath(target + mpoint)
|
|
267 |
if not os.path.exists(absmpoint):
|
|
268 |
os.makedirs(absmpoint)
|
|
269 |
mount(dev, absmpoint)
|
|
270 |
|
|
271 |
def _umount_all(self, target):
|
|
272 |
mpoints = []
|
|
273 |
for entry in self._read_fstable('/proc/mounts'):
|
|
274 |
if entry.mpoint.startswith(os.path.abspath(target)):
|
|
275 |
mpoints.append(entry.mpoint)
|
|
276 |
|
|
277 |
mpoints.sort()
|
|
278 |
for mpoint in reversed(mpoints):
|
|
279 |
umount(mpoint)
|
|
280 |
|
|
281 |
def _create_filesystems(self, image):
|
|
282 |
|
|
283 |
partitions = self._get_partitions(parted.Disk(parted.Device(image)))
|
|
284 |
filesystems = {}
|
|
285 |
for p in self.disk.partitions:
|
|
286 |
filesystems[p.number] = self._get_mount_options(p.path)
|
|
287 |
|
|
288 |
unmounted = filter(lambda p: filesystems[p.num] is None, partitions)
|
|
289 |
mounted = filter(lambda p: filesystems[p.num] is not None, partitions)
|
|
290 |
|
|
291 |
# For partitions that are not mounted right now, we can simply dd them
|
|
292 |
# into the image.
|
|
293 |
for p in unmounted:
|
|
294 |
dd('if=%s' % self.disk.device.path, 'of=%s' % image,
|
|
295 |
'count=%d' % (p.end - p.start + 1), 'conv=notrunc',
|
|
296 |
'seek=%d' % p.start, 'skip=%d' % p.start)
|
|
297 |
|
|
298 |
loop = str(losetup('-f', '--show', image)).strip()
|
|
299 |
mapped = {}
|
|
300 |
try:
|
|
301 |
for p in mounted:
|
|
302 |
i = p.num
|
|
303 |
mapped[i] = self._map_partition(loop, i, p.start, p.end)
|
|
304 |
|
|
305 |
# Create the file systems
|
|
306 |
for i, dev in mapped.iteritems():
|
|
307 |
fs = filesystems[i].fs
|
|
308 |
self.out.output('Creating %s filesystem on partition %d ... ' %
|
|
309 |
(fs, i), False)
|
|
310 |
get_command('mkfs.%s' % fs)(*(MKFS_OPTS[fs] + [dev]))
|
|
311 |
self.out.success('done')
|
|
312 |
|
|
313 |
target = tempfile.mkdtemp()
|
|
314 |
try:
|
|
315 |
absmpoints = self._mount(target,
|
|
316 |
[(mapped[i], filesystems[i].mpoint) for i in mapped.keys()]
|
|
317 |
)
|
|
318 |
|
|
319 |
finally:
|
|
320 |
self._umount_all(target)
|
|
321 |
os.rmdir(target)
|
|
322 |
finally:
|
|
323 |
for dev in mapped.values():
|
|
324 |
self._unmap_partition(dev)
|
|
325 |
losetup('-d', loop)
|
|
326 |
|
|
327 |
def create_image(self):
|
236 |
328 |
|
237 |
|
size = src_dev.getLength() * src_dev.sectorSize
|
|
329 |
image = '/mnt/%s.diskdump' % uuid.uuid4().hex
|
|
330 |
|
|
331 |
disk_size = self.disk.device.getLength() * self.disk.device.sectorSize
|
238 |
332 |
|
239 |
333 |
# Create sparse file to host the image
|
240 |
|
truncate("-s", "%d" % size, image_file)
|
|
334 |
truncate("-s", "%d" % disk_size, image)
|
|
335 |
|
|
336 |
self._create_partition_table(image)
|
|
337 |
end_sector = self._shrink_partitions(image)
|
241 |
338 |
|
242 |
|
src_disk = parted.Disk(src_dev)
|
243 |
|
self._create_partition_table(src_disk, image_file)
|
244 |
|
partitions = self._shrink_partitions(src_disk, image_file)
|
245 |
|
self._fill_partitions(src_disk, image_file, partitions)
|
|
339 |
# Check if the available space is enough to host the image
|
|
340 |
dirname = os.path.dirname(image)
|
|
341 |
size = (end_sector + 1) * self.disk.device.sectorSize
|
|
342 |
self.out.output("Examining available space in %s ..." % dirname, False)
|
|
343 |
stat = os.statvfs(dirname)
|
|
344 |
available = stat.f_bavail * stat.f_frsize
|
|
345 |
if available <= size:
|
|
346 |
raise FatalError('Not enough space in %s to host the image' %
|
|
347 |
dirname)
|
|
348 |
self.out.success("sufficient")
|
246 |
349 |
|
247 |
|
return image_file
|
|
350 |
self._create_filesystems(image)
|
248 |
351 |
|
249 |
|
# unmounted = filter(lambda p: not p.mopts.mpoint, partitions)
|
250 |
|
# mounted = filter(lambda p: p.mopts.mpoint, partitions)
|
251 |
|
#
|
252 |
|
# for p in unmounted:
|
253 |
|
# dd('if=%s' % src_dev.path, 'of=%s' % img_dev.path,
|
254 |
|
# 'count=%d' % (p.end - p.start + 1), 'conv=notrunc',
|
255 |
|
# 'seek=%d' % p.start, 'skip=%d' % p.start)
|
256 |
|
#
|
257 |
|
# partition_devices = create_devices(dest, partitions)
|
258 |
|
#
|
259 |
|
# mounted.sort(key=lambda p: p.mopts.mpoint)
|
260 |
|
#
|
261 |
|
# return img
|
|
352 |
return image
|
262 |
353 |
|
263 |
354 |
# vim: set sta sts=4 shiftwidth=4 sw=4 et ai :
|