better exception handlings
authorJF Ding <Jian-feng.Ding@intel.com>
Fri, 2 Sep 2011 01:50:01 +0000 (10:50 +0900)
committerJF Ding <Jian-feng.Ding@intel.com>
Fri, 2 Sep 2011 01:50:01 +0000 (10:50 +0900)
mic/creator.py
mic/msger.py
mic/utils/errors.py
plugins/backend/zypppkgmgr.py
plugins/imager/fs_plugin.py
plugins/imager/livecd_plugin.py
plugins/imager/liveusb_plugin.py
plugins/imager/loop_plugin.py
plugins/imager/raw_plugin.py
tools/mic

index ac55a4d..acf5e6b 100644 (file)
@@ -19,9 +19,7 @@
 
 import os, sys
 
-from mic import configmgr
-from mic import pluginmgr
-from mic import msger
+from mic import configmgr, pluginmgr, msger
 from mic.utils import cmdln
 
 class Creator(cmdln.Cmdln):
@@ -99,7 +97,7 @@ class Creator(cmdln.Cmdln):
             return self.emptyline()
             
         if os.geteuid() != 0:
-            msger.error('Need root permission to run this command')
+            msger.error('Root permission is required to continue, abort')
 
         return self.cmd(args)
 
index accf3d1..b24c38d 100644 (file)
@@ -21,7 +21,7 @@
 import os,sys
 import re
 
-__ALL__ = ['set_mode', 'set_loglevel', 'raw' 'debug', 'verbose', 'info', 'warning', 'error', 'ask', 'pause']
+__ALL__ = ['set_mode', 'get_loglevel', 'set_loglevel', 'raw' 'debug', 'verbose', 'info', 'warning', 'error', 'ask', 'pause']
 
 # COLORs in ANSI
 INFO_COLOR = 32 # green
@@ -103,6 +103,9 @@ def _split_msg(head, msg):
 
     return head, msg
 
+def get_loglevel():
+    return (k for k,v in LOG_LEVELS.items() if v==LOG_LEVEL).next()
+
 def set_loglevel(level):
     global LOG_LEVEL
     if level not in LOG_LEVELS:
index 51e550d..5dd7793 100644 (file)
 # along with this program; if not, write to the Free Software
 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 
-class Usage(Exception):
-    def __init__(self, msg=None):
-        Exception.__init__(self, msg)
-
-class ConfigError(Exception):
-    def __init__(self, msg=None):
-        Exception.__init__(self, msg)
-
 class CreatorError(Exception):
     """An exception base class for all imgcreate errors."""
+    keyword = '<creator>'
+
     def __init__(self, msg):
-        Exception.__init__(self, msg)
+        self.msg = msg
+
+    def __str__(self):
+        return self.keyword + repr(self.msg)
+
+class ConfigError(CreatorError):
+    keyword = '<config>'
+
+class Usage(CreatorError):
+    keyword = '<usage>'
 
 class KsError(CreatorError):
-    pass
+    keyword = '<kickstart>'
 
 class MountError(CreatorError):
-    pass
+    keyword = '<mount>'
 
 class SnapshotError(CreatorError):
-    pass
+    keyword = '<snapshot>'
 
 class SquashfsError(CreatorError):
-    pass
+    keyword = '<squashfs>'
index 8ee125c..72e9f18 100644 (file)
@@ -327,7 +327,7 @@ class Zypp(BackendPlugin):
             self.repo_manager.addRepository(repo_info)
             self.__build_repo_cache(name)
         except RuntimeError, e:
-            raise CreatorError("%s" % (e,))
+            raise CreatorError(str(e))
 
         msger.verbose('repo: %s was added' % name)
         return repo
index 70d9679..70c9a98 100644 (file)
@@ -76,7 +76,7 @@ class FsPlugin(ImagerPlugin):
             outimage = creator.outimage
             creator.print_outimage_info()
         except errors.CreatorError, e:
-            raise errors.CreatorError("failed to create image : %s" % e)
+            raise
         finally:
             creator.cleanup()
 
index 554da78..e9f192d 100644 (file)
@@ -78,8 +78,7 @@ class LiveCDPlugin(ImagerPlugin):
             outimage = creator.outimage
 
         except errors.CreatorError, e:
-            raise errors.CreatorError("failed to create image : %s" % e)
-
+            raise
         finally:
             creator.cleanup()
 
index d7a166f..2641218 100644 (file)
@@ -78,7 +78,7 @@ class LiveUSBPlugin(ImagerPlugin):
             outimage = creator.outimage
 
         except errors.CreatorError, e:
-            raise errors.CreatorError("failed to create image : %s" % e)
+            raise
         finally:
             creator.cleanup()
 
index e8e69a2..2281ad0 100644 (file)
@@ -69,7 +69,7 @@ class LoopPlugin(ImagerPlugin):
             creator.unmount()
             creator.package(creatoropts["outdir"])
         except errors.CreatorError, e:
-            raise errors.CreatorError("failed to create image : %s" % e)
+            raise
         finally:
             creator.cleanup()
 
index 02b027a..b380fde 100644 (file)
@@ -77,8 +77,7 @@ class RawPlugin(ImagerPlugin):
             outimage = creator.outimage
 
         except errors.CreatorError, e:
-            raise errors.CreatorError("failed to create image : %s" % e)
-
+            raise
         finally:
             creator.cleanup()
 
index d0137c0..e63ab28 100755 (executable)
--- a/tools/mic
+++ b/tools/mic
@@ -1,6 +1,6 @@
 #!/usr/bin/python -tt
 #
-# Copyright 2008, 2009, 2010 Intel, Inc.
+# Copyright 2008, 2009, 2010, 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
 #
 
 import os, sys
-
-import mic.utils.misc as misc
-import mic.utils.errors as errors
-import mic.configmgr as configmgr
-import mic.pluginmgr as pluginmgr
-import mic.creator as creator
-from mic import msger
-from mic.utils import cmdln
-try:
-    from mic.__version__ import VERSION
-except:
-    VERSION = 'Unknown'
+from mic import msger, creator, configmgr, pluginmgr
+from mic.utils import cmdln, misc, errors
+from mic.__version__ import VERSION
 
 class Mic(cmdln.Cmdln):
     """
@@ -54,9 +45,9 @@ class Mic(cmdln.Cmdln):
 
     def postoptparse(self):
         if self.options.verbose:
-           msger.set_loglevel('verbose')
+            msger.set_loglevel('verbose')
         if self.options.debug:
-           msger.set_loglevel('debug')
+            msger.set_loglevel('debug')
 
     @cmdln.alias("cr")
     def do_create(self, argv):
@@ -76,6 +67,10 @@ class Mic(cmdln.Cmdln):
         doc = doc.rstrip() + '\n'
         return doc
 
+    def _root_confirm(self):
+        if os.geteuid() != 0:
+            msger.error('Root permission is required to continue, abort')
+
     @cmdln.alias("cv")
     def do_convert(self, subcmd, opts, *args):
         """${cmd_name}: convert image format
@@ -85,22 +80,22 @@ class Mic(cmdln.Cmdln):
 
         ${cmd_option_list}
         """
-        if len(args) == 0:
+
+        if not args:
             # print help
             handler = self._get_cmd_handler('convert')
             if hasattr(handler, "optparser"):
                 handler.optparser.print_help()
             return
+
         if len(args) == 1:
-            raise errors.Usage("It takes 2 arguments (1 given)")
+            raise errors.Usage("It need 2 arguments (1 given)")
         elif len(args) == 2:
-            srcimg = args[0]
-            destformat = args[1]
+            (srcimg, destformat) = args
         else:
             raise errors.Usage("Extra argument given")
 
-        if os.geteuid() != 0:
-            raise errors.Usage("You must run as root")
+        self._root_confirm()
 
         srcformat = misc.get_image_type(srcimg)
         if srcformat == "ext3fsimg":
@@ -133,19 +128,20 @@ class Mic(cmdln.Cmdln):
 
         ${cmd_option_list}
         """
-        if len(args) == 0:
+
+        if not args:
             # print help
             handler = self._get_cmd_handler('chroot')
             if hasattr(handler, "optparser"):
                 handler.optparser.print_help()
             return
+
         if len(args) == 1:
             targetimage = args[0]
         else:
             raise errors.Usage("Extra argument given")
 
-        if os.geteuid() != 0:
-            raise errors.Usage("You must run as root")
+        self._root_confirm()
 
         imagetype = misc.get_image_type(targetimage)
         if not imagetype:
@@ -163,7 +159,7 @@ class Mic(cmdln.Cmdln):
                 break
 
         if not chrootclass:
-            raise errors.CreatorError("Don't support image type: %s" % imagetype)
+            raise errors.CreatorError("Cannot support image type: %s" % imagetype)
 
         chrootclass.do_chroot(targetimage)
 
@@ -172,11 +168,9 @@ if __name__ == "__main__":
         mic = Mic()
         sys.exit(mic.main())
 
-    except errors.Usage, msg:
-        msger.error("<usage> %s\n" % msg)
-
-    except errors.ConfigError, msg:
-        msger.error("<config> %s\n" % msg)
-
-    except errors.CreatorError, msg:
-        msger.error("<creator> %s\n" % msg)
+    except (errors.Usage, errors.ConfigError, errors.CreatorError) as err:
+        if msger.get_loglevel() == 'debug':
+            import traceback
+            msger.error(traceback.format_exc())
+        else:
+            msger.error(str(err))