Fix wrong variable name in progress_callback
[snf-image-creator] / image_creator / disk.py
index 6d0ad1f..f117e80 100644 (file)
@@ -1,6 +1,9 @@
 #!/usr/bin/env python
 
-import losetup
+from image_creator.util import get_command
+from image_creator import FatalError
+from clint.textui import progress
+
 import stat
 import os
 import tempfile
@@ -8,34 +11,16 @@ import uuid
 import re
 import sys
 import guestfs
-
-import pbs
-from pbs import dd
-from clint.textui import progress
+import time
 
 
 class DiskError(Exception):
     pass
 
-
-def find_sbin_command(command, exception):
-    search_paths = ['/usr/local/sbin', '/usr/sbin', '/sbin']
-    for fullpath in map(lambda x: "%s/%s" % (x, command), search_paths):
-        if os.path.exists(fullpath) and os.access(fullpath, os.X_OK):
-            return pbs.Command(fullpath)
-        continue
-    raise exception
-
-
-try:
-    from pbs import dmsetup
-except pbs.CommandNotFound as e:
-    dmsetup = find_sbin_command('dmsetup', e)
-
-try:
-    from pbs import blockdev
-except pbs.CommandNotFound as e:
-    blockdev = find_sbin_command('blockdev', e)
+dd = get_command('dd')
+dmsetup = get_command('dmsetup')
+losetup = get_command('losetup')
+blockdev = get_command('blockdev')
 
 
 class Disk(object):
@@ -57,10 +42,10 @@ class Disk(object):
         self._cleanup_jobs.append((job, args))
 
     def _losetup(self, fname):
-        loop = losetup.find_unused_loop_device()
-        loop.mount(fname)
-        self._add_cleanup(loop.unmount)
-        return loop.device
+        loop = losetup('-f', '--show', fname)
+        loop = loop.strip() # remove the new-line char
+        self._add_cleanup(losetup, '-d', loop)
+        return loop
 
     def _dir_to_disk(self):
         raise NotImplementedError
@@ -95,6 +80,7 @@ class Disk(object):
         # Take a snapshot and return it to the user
         size = blockdev('--getsize', sourcedev)
         cowfd, cow = tempfile.mkstemp()
+        os.close(cowfd)
         self._add_cleanup(os.unlink, cow)
         # Create 1G cow sparse file
         dd('if=/dev/null', 'of=%s' % cow, 'bs=1k', 'seek=%d' % (1024 * 1024))
@@ -109,9 +95,9 @@ class Disk(object):
             self._add_cleanup(dmsetup, 'remove', snapshot)
         finally:
             os.unlink(table)
-
         new_device = DiskDevice("/dev/mapper/%s" % snapshot)
         self._devices.append(new_device)
+        new_device.enable()
         return new_device
 
     def destroy_device(self, device):
@@ -122,9 +108,9 @@ class Disk(object):
         device.destroy()
 
 
-def progress_generator(total):
+def progress_generator(label=''):
     position = 0;
-    for i in progress.bar(range(total)):
+    for i in progress.bar(range(100),label):
         if i < position:
             continue
         position = yield
@@ -138,25 +124,37 @@ class DiskDevice(object):
 
     def __init__(self, device, bootable=True):
         """Create a new DiskDevice."""
+
         self.device = device
         self.bootable = bootable
         self.progress_bar = None
 
         self.g = guestfs.GuestFS()
-        self.g.add_drive_opts(device, readonly=0)
+        self.g.add_drive_opts(self.device, readonly=0)
 
         #self.g.set_trace(1)
         #self.g.set_verbose(1)
 
+        self.guestfs_enabled = False
+    
+    def enable(self):
+        """Enable a newly created DiskDevice"""
+
+        self.progressbar = progress_generator("VM lauch: ")
+        self.progressbar.next()
         eh = self.g.set_event_callback(self.progress_callback, guestfs.EVENT_PROGRESS)
         self.g.launch()
+        self.guestfs_enabled = True
         self.g.delete_event_callback(eh)
+        if self.progressbar is not None:
+            self.progressbar.send(100)
+            self.progressbar = None
         
         roots = self.g.inspect_os()
         if len(roots) == 0:
-            raise DiskError("No operating system found")
+            raise FatalError("No operating system found")
         if len(roots) > 1:
-            raise DiskError("Multiple operating systems found")
+            raise FatalError("Multiple operating systems found")
 
         self.root = roots[0]
         self.ostype = self.g.inspect_get_type(self.root)
@@ -164,23 +162,22 @@ class DiskDevice(object):
 
     def destroy(self):
         """Destroy this DiskDevice instance."""
-        self.g.umount_all()
-        self.g.sync()
-        # Close the guestfs handler
+
+        if self.guestfs_enabled:
+            self.g.umount_all()
+            self.g.sync()
+
+        # Close the guestfs handler if open
         self.g.close()
 
     def progress_callback(self, ev, eh, buf, array):
         position = array[2]
         total = array[3]
-        
-        if self.progress_bar is None:
-            self.progress_bar = progress_generator(total)
-            self.progress_bar.next()
 
-        self.progress_bar.send(position)
+        self.progressbar.send((position * 100)//total)
 
         if position == total:
-            self.progress_bar = None
+            self.progressbar = None
 
     def mount(self):
         """Mount all disk partitions in a correct order."""
@@ -216,13 +213,13 @@ class DiskDevice(object):
         dev = self.g.part_to_dev(self.root)
         parttype = self.g.part_get_parttype(dev)
         if parttype != 'msdos':
-            raise DiskError("You have a %s partition table. "
+            raise FatalError("You have a %s partition table. "
                 "Only msdos partitions are supported" % parttype)
 
         last_partition = self.g.part_list(dev)[-1]
 
         if last_partition['part_num'] > 4:
-            raise DiskError("This disk contains logical partitions. "
+            raise FatalError("This disk contains logical partitions. "
                 "Only primary partitions are supported.")
 
         part_dev = "%s%d" % (dev, last_partition['part_num'])