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.
34 from image_creator.util import get_command
35 from image_creator.util import warn, progress, success, output, FatalError
45 from sendfile import sendfile
48 class DiskError(Exception):
51 dd = get_command('dd')
52 dmsetup = get_command('dmsetup')
53 losetup = get_command('losetup')
54 blockdev = get_command('blockdev')
58 """This class represents a hard disk hosting an Operating System
60 A Disk instance never alters the source media it is created from.
61 Any change is done on a snapshot created by the device-mapper of
65 def __init__(self, source):
66 """Create a new Disk instance out of a source media. The source
67 media can be an image file, a block device or a directory."""
68 self._cleanup_jobs = []
72 def _add_cleanup(self, job, *args):
73 self._cleanup_jobs.append((job, args))
75 def _losetup(self, fname):
76 loop = losetup('-f', '--show', fname)
77 loop = loop.strip() # remove the new-line char
78 self._add_cleanup(losetup, '-d', loop)
81 def _dir_to_disk(self):
82 raise NotImplementedError
85 """Cleanup internal data. This needs to be called before the
88 while len(self._devices):
89 device = self._devices.pop()
92 while len(self._cleanup_jobs):
93 job, args = self._cleanup_jobs.pop()
97 """Creates a snapshot of the original source media of the Disk
101 output("Examining source media `%s'..." % self.source, False)
102 sourcedev = self.source
103 mode = os.stat(self.source).st_mode
104 if stat.S_ISDIR(mode):
105 success('looks like a directory')
106 return self._losetup(self._dir_to_disk())
107 elif stat.S_ISREG(mode):
108 success('looks like an image file')
109 sourcedev = self._losetup(self.source)
110 elif not stat.S_ISBLK(mode):
111 raise ValueError("Invalid media source. Only block devices, "
112 "regular files and directories are supported.")
114 success('looks like a block device')
116 # Take a snapshot and return it to the user
117 output("Snapshotting media source...", False)
118 size = blockdev('--getsize', sourcedev)
119 cowfd, cow = tempfile.mkstemp()
121 self._add_cleanup(os.unlink, cow)
122 # Create 1G cow sparse file
123 dd('if=/dev/null', 'of=%s' % cow, 'bs=1k', \
124 'seek=%d' % (1024 * 1024))
125 cowdev = self._losetup(cow)
127 snapshot = uuid.uuid4().hex
128 tablefd, table = tempfile.mkstemp()
130 os.write(tablefd, "0 %d snapshot %s %s n 8" % \
131 (int(size), sourcedev, cowdev))
132 dmsetup('create', snapshot, table)
133 self._add_cleanup(dmsetup, 'remove', snapshot)
134 # Sometimes dmsetup remove fails with Device or resource busy,
135 # although everything is cleaned up and the snapshot is not
136 # used by anyone. Add a 2 seconds delay to be on the safe side.
137 self._add_cleanup(time.sleep, 2)
142 return "/dev/mapper/%s" % snapshot
144 def get_device(self, media):
145 """Returns a newly created DiskDevice instance."""
147 new_device = DiskDevice(media)
148 self._devices.append(new_device)
152 def destroy_device(self, device):
153 """Destroys a DiskDevice instance previously created by
156 self._devices.remove(device)
160 class DiskDevice(object):
161 """This class represents a block device hosting an Operating System
162 as created by the device-mapper.
165 def __init__(self, device, bootable=True):
166 """Create a new DiskDevice."""
169 self.bootable = bootable
170 self.progress_bar = None
172 self.g = guestfs.GuestFS()
173 self.g.add_drive_opts(self.device, readonly=0)
176 #self.g.set_verbose(1)
178 self.guestfs_enabled = False
181 """Enable a newly created DiskDevice"""
182 new_progress = progress("Launching helper VM: ")
183 self.progressbar = new_progress()
184 self.progressbar.next()
185 eh = self.g.set_event_callback(self.progress_callback,
186 guestfs.EVENT_PROGRESS)
188 self.guestfs_enabled = True
189 self.g.delete_event_callback(eh)
190 if self.progressbar is not None:
191 self.progressbar.send(100)
192 self.progressbar = None
194 output('Inspecting Operating System...', False)
195 roots = self.g.inspect_os()
197 raise FatalError("No operating system found")
199 raise FatalError("Multiple operating systems found."
200 "We only support images with one filesystem.")
202 self.ostype = self.g.inspect_get_type(self.root)
203 self.distro = self.g.inspect_get_distro(self.root)
204 success('found a %s system' % self.distro)
207 """Destroy this DiskDevice instance."""
209 if self.guestfs_enabled:
213 # Close the guestfs handler if open
216 def progress_callback(self, ev, eh, buf, array):
220 self.progressbar.send((position * 100) // total)
222 if position == total:
223 self.progressbar = None
226 """Mount all disk partitions in a correct order."""
228 output("Mounting image...", False)
229 mps = self.g.inspect_get_mountpoints(self.root)
231 # Sort the keys to mount the fs in a correct order.
232 # / should be mounted befor /boot, etc
234 if len(a[0]) > len(b[0]):
236 elif len(a[0]) == len(b[0]):
243 self.g.mount(dev, mp)
244 except RuntimeError as msg:
245 warn("%s (ignored)" % msg)
249 """Umount all mounted filesystems."""
255 This is accomplished by shrinking the last filesystem in the
256 disk and then updating the partition table. The new disk size
257 (in bytes) is returned.
259 output("Shrinking image (this may take a while)...", False)
261 dev = self.g.part_to_dev(self.root)
262 parttype = self.g.part_get_parttype(dev)
263 if parttype != 'msdos':
264 raise FatalError("You have a %s partition table. "
265 "Only msdos partitions are supported" % parttype)
267 last_partition = self.g.part_list(dev)[-1]
269 if last_partition['part_num'] > 4:
270 raise FatalError("This disk contains logical partitions. "
271 "Only primary partitions are supported.")
273 part_dev = "%s%d" % (dev, last_partition['part_num'])
274 fs_type = self.g.vfs_type(part_dev)
275 if not re.match("ext[234]", fs_type):
276 warn("Don't know how to resize %s partitions." % vfs_type)
279 self.g.e2fsck_f(part_dev)
280 self.g.resize2fs_M(part_dev)
282 out = self.g.tune2fs_l(part_dev)
284 filter(lambda x: x[0] == 'Block size', out)[0][1])
286 filter(lambda x: x[0] == 'Block count', out)[0][1])
288 sector_size = self.g.blockdev_getss(dev)
290 start = last_partition['part_start'] / sector_size
291 end = start + (block_size * block_cnt) / sector_size - 1
293 self.g.part_del(dev, last_partition['part_num'])
294 self.g.part_add(dev, 'p', start, end)
296 new_size = (end + 1) * sector_size
297 success("new image size is %dMB" %
298 ((new_size + 2 ** 20 - 1) // 2 ** 20))
302 """Returns the "payload" size of the device.
304 The size returned by this method is the size of the space occupied by
305 the partitions (including the space before the first partition).
307 dev = self.g.part_to_dev(self.root)
308 last = self.g.part_list(dev)[-1]
310 return last['part_end'] + 1
312 def dump(self, outfile):
313 """Dumps the content of device into a file.
315 This method will only dump the actual payload, found by reading the
316 partition table. Empty space in the end of the device will be ignored.
318 blocksize = 2 ** 22 # 4MB
320 progress_size = (size + 2 ** 20 - 1) // 2 ** 20 # in MB
321 new_progress = progress("Dumping image file: ")
322 progressbar = new_progress(progress_size)
323 source = open(self.device, "r")
325 dest = open(outfile, "w")
331 length = min(left, blocksize)
332 sent = sendfile(dest.fileno(), source.fileno(), offset,
336 for i in range((length + 2 ** 20 - 1) // 2 ** 20):
343 success('Image file %s was successfully created' % outfile)
345 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :