call copy_attachment() after configure() and move attachment files
[tools/mic.git] / plugins / imager / loop_plugin.py
old mode 100644 (file)
new mode 100755 (executable)
index 77e039c..8815fe4
 # Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 
 import os
+import subprocess
 import shutil
 import tempfile
 
 from mic import chroot, msger, rt_util
-from mic.utils import misc, fs_related, errors, cmdln
+from mic.utils import misc, fs_related, errors, runner
 from mic.conf import configmgr
 from mic.plugin import pluginmgr
 from mic.imager.loop import LoopImageCreator, load_mountpoints
@@ -30,13 +31,7 @@ class LoopPlugin(ImagerPlugin):
     name = 'loop'
 
     @classmethod
-    @cmdln.option("--taring-to", dest="compress_to", type='string',
-                  default=None, help="same with '--compress-to'")
-    @cmdln.option("--compress-to", dest="compress_to", type='string',
-                  default=None, help="Specify compress filename for all image "
-                  "output, compress type decided by file extension, '.zip' for "
-                  "zip format, '.tar' for tar format, default is tar format")
-    def do_create(self, subcmd, opts, *args):
+    def do_create(self, args):
         """${cmd_name}: create loop image
 
         Usage:
@@ -45,17 +40,15 @@ class LoopPlugin(ImagerPlugin):
         ${cmd_option_list}
         """
 
-        if not args:
-            raise errors.Usage("need one argument as the path of ks file")
-
-        if len(args) != 1:
-            raise errors.Usage("Extra arguments given")
+        if args is None:
+            raise errors.Usage("Invalid arguments")
 
         creatoropts = configmgr.create
-        ksconf = args[0]
+        ksconf = args.ksfile
 
-        if not os.path.exists(ksconf):
-            raise errors.CreatorError("Can't find the file: %s" % ksconf)
+        if creatoropts['runtime'] == "bootstrap":
+            configmgr._ksconf = ksconf
+            rt_util.bootstrap_mic()
 
         recording_pkgs = []
         if len(creatoropts['record_pkgs']) > 0:
@@ -64,64 +57,62 @@ class LoopPlugin(ImagerPlugin):
         if creatoropts['release'] is not None:
             if 'name' not in recording_pkgs:
                 recording_pkgs.append('name')
-            ksconf = misc.save_ksconf_file(ksconf, creatoropts['release'])
+            if 'vcs' not in recording_pkgs:
+                recording_pkgs.append('vcs')
 
         configmgr._ksconf = ksconf
 
-        # Called After setting the configmgr._ksconf
-        # as the creatoropts['name'] is reset there.
-        if creatoropts['release'] is not None:
-            creatoropts['outdir'] = "%s/%s/images/%s/" % (creatoropts['outdir'],
-                                                          creatoropts['release'],
-                                                          creatoropts['name'])
-
         # try to find the pkgmgr
         pkgmgr = None
-        for (key, pcls) in pluginmgr.get_plugins('backend').iteritems():
-            if key == creatoropts['pkgmgr']:
-                pkgmgr = pcls
-                break
+        backends = pluginmgr.get_plugins('backend')
+        if 'auto' == creatoropts['pkgmgr']:
+            for key in configmgr.prefer_backends:
+                if key in backends:
+                    pkgmgr = backends[key]
+                    break
+        else:
+            for key in backends.keys():
+                if key == creatoropts['pkgmgr']:
+                    pkgmgr = backends[key]
+                    break
 
         if not pkgmgr:
-            pkgmgrs = pluginmgr.get_plugins('backend').keys()
-            raise errors.CreatorError("Can't find package manager: %s "
-                                      "(availables: %s)" \
-                                      % (creatoropts['pkgmgr'],
-                                         ', '.join(pkgmgrs)))
-
-        if creatoropts['runtime']:
-            rt_util.runmic_in_runtime(creatoropts['runtime'], creatoropts, ksconf, None)
+            raise errors.CreatorError("Can't find backend: %s, "
+                                      "available choices: %s" %
+                                      (creatoropts['pkgmgr'],
+                                       ','.join(backends.keys())))
 
-        creator = LoopImageCreator(creatoropts, pkgmgr, opts.compress_to)
+        creator = LoopImageCreator(creatoropts,
+                                   pkgmgr,
+                                   args.compress_image,
+                                   args.shrink)
 
         if len(recording_pkgs) > 0:
             creator._recording_pkgs = recording_pkgs
 
-        if creatoropts['release'] is None:
-            if opts.compress_to:
-                imagefile = "%s" % os.path.join(creator.destdir, creator.compress_to)
-            else:
-                imagefile = "%s.img" % os.path.join(creator.destdir, creator.name)
-
-            if os.path.exists(imagefile):
-                if msger.ask('The target image: %s already exists, cleanup '
-                             'and continue?' % imagefile):
-                    os.unlink(imagefile)
-                else:
-                    raise errors.Abort('Canceled')
+        image_names = [creator.name + ".img"]
+        image_names.extend(creator.get_image_names())
+        self.check_image_exists(creator.destdir,
+                                creator.pack_to,
+                                image_names,
+                                creatoropts['release'])
 
         try:
             creator.check_depend_tools()
             creator.mount(None, creatoropts["cachedir"])
             creator.install()
             creator.configure(creatoropts["repomd"])
-            creator.copy_kernel()            
+            creator.copy_kernel()
+            creator.copy_attachment()
+            creator.create_cpio_image()
             creator.unmount()
-            creator.package(creatoropts["outdir"])
+            creator.copy_cpio_image()
+            creator.package(creatoropts["destdir"])
+            creator.create_manifest()
 
             if creatoropts['release'] is not None:
-                creator.release_output(ksconf, 
-                                       creatoropts['outdir'],
+                creator.release_output(ksconf,
+                                       creatoropts['destdir'],
                                        creatoropts['release'])
             creator.print_outimage_info()
 
@@ -130,11 +121,19 @@ class LoopPlugin(ImagerPlugin):
         finally:
             creator.cleanup()
 
+        #Run script of --run_script after image created
+        if creatoropts['run_script']:
+            cmd = creatoropts['run_script']
+            try:
+                runner.show(cmd)
+            except OSError,err:
+                msger.warning(str(err))
+
         msger.info("Finished.")
         return 0
 
     @classmethod
-    def _do_chroot_tar(cls, target):
+    def _do_chroot_tar(cls, target, cmd=[]):
         mountfp_xml = os.path.splitext(target)[0] + '.xml'
         if not os.path.exists(mountfp_xml):
             raise errors.CreatorError("No mount point file found for this tar "
@@ -157,7 +156,7 @@ class LoopPlugin(ImagerPlugin):
             elif fstype in ("vfat", "msdos"):
                 myDiskMount = fs_related.VfatDiskMount
             else:
-                msger.error("Cannot support fstype: %s" % fstype)
+                raise errors.CreatorError("Cannot support fstype: %s" % fstype)
 
             name = os.path.join(tmpdir, name)
             size = size * 1024L * 1024L
@@ -181,7 +180,11 @@ class LoopPlugin(ImagerPlugin):
             loops.append(loop)
 
         try:
-            chroot.chroot(mntdir, None, "/bin/env HOME=/root /bin/bash")
+            if len(cmd) != 0:
+                cmdline = "/usr/bin/env HOME=/root " + ' '.join(cmd)
+            else:
+                cmdline = "/usr/bin/env HOME=/root /bin/bash"
+            chroot.chroot(mntdir, None, cmdline)
         except:
             raise errors.CreatorError("Failed to chroot to %s." % target)
         finally:
@@ -191,11 +194,11 @@ class LoopPlugin(ImagerPlugin):
             shutil.rmtree(tmpdir, ignore_errors=True)
 
     @classmethod
-    def do_chroot(cls, target):
+    def do_chroot(cls, target, cmd=[]):
         if target.endswith('.tar'):
             import tarfile
             if tarfile.is_tarfile(target):
-                LoopPlugin._do_chroot_tar(target)
+                LoopPlugin._do_chroot_tar(target, cmd)
                 return
             else:
                 raise errors.CreatorError("damaged tarball for loop images")
@@ -228,7 +231,14 @@ class LoopPlugin(ImagerPlugin):
             raise
 
         try:
-            chroot.chroot(extmnt, None,  "/bin/env HOME=/root /bin/bash")
+            if cmd is not None:
+                cmdline = cmd
+            else:
+                cmdline = "/bin/bash"
+            envcmd = fs_related.find_binary_inchroot("env", extmnt)
+            if envcmd:
+                cmdline = "%s HOME=/root %s" % (envcmd, cmdline)
+            chroot.chroot(extmnt, None, cmdline)
         except:
             raise errors.CreatorError("Failed to chroot to %s." % img)
         finally: