replace most of subprocess calls by new runner apis
[tools/mic.git] / plugins / imager / fs_plugin.py
index e40e1fd..f6c7d3f 100644 (file)
@@ -1,18 +1,32 @@
-#!/usr/bin/python
-import sys
-import subprocess
-import logging
+#!/usr/bin/python -tt
+#
+# Copyright 2011 Intel, Inc.
+#
+# This copyrighted material is made available to anyone wishing to use, modify,
+# copy, or redistribute it subject to the terms and conditions of the GNU
+# General Public License v.2.  This program is distributed in the hope that it
+# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
+# implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+# See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program; if not, write to the Free Software Foundation, Inc., 51
+# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  Any Red Hat
+# trademarks that are incorporated in the source code or documentation are not
+# subject to the GNU General Public License and may only be used or replicated
+# with the express permission of Red Hat, Inc.
+#
 
-from micng.pluginbase.imager_plugin import ImagerPlugin
-import micng.utils.cmdln as cmdln
-import micng.utils.errors as errors
-import micng.configmgr as configmgr
-import micng.pluginmgr as pluginmgr
-import micng.imager.fs as fs
-import micng.chroot as chroot
+import os
 
+from mic import configmgr, pluginmgr, chroot, msger
+from mic.utils import cmdln, errors
+from mic.imager import fs
 
+from mic.pluginbase import ImagerPlugin
 class FsPlugin(ImagerPlugin):
+    name = 'fs'
+
     @classmethod
     @cmdln.option("--include-src", dest="include_src", help="include source pakcage")
     def do_create(self, subcmd, opts, *args):
@@ -21,8 +35,10 @@ class FsPlugin(ImagerPlugin):
         ${cmd_usage}
         ${cmd_option_list}
         """
-        if len(args) == 0:
-            return
+
+        if not args:
+            raise errors.Usage("More arguments needed")
+
         if len(args) == 1:
             ksconf = args[0]
         else:
@@ -32,52 +48,58 @@ class FsPlugin(ImagerPlugin):
         createopts = cfgmgr.create
         cfgmgr.setProperty("ksconf", ksconf)
 
-        plgmgr = pluginmgr.PluginMgr()
-        plgmgr.loadPlugins()
-        for (key, pcls) in plgmgr.getBackendPlugins():
+        # try to find the pkgmgr
+        pkgmgr = None
+        for (key, pcls) in pluginmgr.PluginMgr().get_plugins('backend').iteritems():
             if key == createopts['pkgmgr']:
                 pkgmgr = pcls
+                break
+
         if not pkgmgr:
-            #logging.warn("Can't find backend plugin: %s" % createopts['pkgmgr'])
             raise CreatorError("Can't find backend plugin: %s" % createopts['pkgmgr'])
-            # try other backend plugin
-            #try:
-            #except:    
-            #    raise CreatorError("None backend found, please check it")
 
         creator = fs.FsImageCreator(createopts, pkgmgr)
+
+        destdir = os.path.abspath(os.path.expanduser(createopts["outdir"]))
+        fsdir = os.path.join(destdir, creator.name)
+
+        if not os.path.exists(destdir):
+            os.makedirs(destdir)
+        elif os.path.exists(fsdir):
+            if msger.ask('The target dir: %s already exists, need to delete it?' % fsdir):
+                import shutil
+                shutil.rmtree(fsdir)
+
         try:
             creator.check_depend_tools()
-            creator.mount(None, createopts["cachedir"])  
+            creator.mount(None, createopts["cachedir"])
             creator.install()
             #Download the source packages ###private options
             if opts.include_src:
                 installed_pkgs =  creator.get_installed_packages()
-                print '--------------------------------------------------'
-                print 'Generating the image with source rpms included, The number of source packages is %d.' %(len(installed_pkgs))
+                msger.info('--------------------------------------------------')
+                msger.info('Generating the image with source rpms included, The number of source packages is %d.' %(len(installed_pkgs)))
                 if not misc.SrcpkgsDownload(installed_pkgs, createopts["repomd"], creator._instroot, createopts["cachedir"]):
-                    print "Source packages can't be downloaded"
-    
+                    msger.warning("Source packages can't be downloaded")
+
             creator.configure(createopts["repomd"])
             creator.unmount()
-            creator.package(createopts["outdir"])
+            creator.package(destdir)
             outimage = creator.outimage
             creator.print_outimage_info()
-        except errors.CreatorError, e:
-            raise errors.CreatorError("failed to create image : %s" % e)
+        except errors.CreatorError:
+            raise
         finally:
             creator.cleanup()
-            print "Finished."
-        return 0    
-           
+
+        msger.info("Finished.")
+        return 0
+
     @classmethod
     def do_chroot(self, target):#chroot.py parse opts&args
             try:
                 chroot.chroot(target, None, "/bin/env HOME=/root /bin/bash")
-            except:
-                print >> sys.stderr, "Failed to chroot to %s." % target
             finally:
                 chroot.cleanup_after_chroot("dir", None, None, None)
                 return 1
-            
-mic_plugin = ["fs", FsPlugin]
+