#
import os, sys
-import logging
import ConfigParser
import mic.utils as utils
import mic.utils.errors as errors
#
import os, sys
-import logging
from mic import configmgr
from mic import pluginmgr
import stat
import tempfile
import shutil
-import logging
import subprocess
import re
import tarfile
(pkg, e))
for pkg in skipped_pkgs:
- logging.warn("Skipping missing package '%s'" % (pkg,))
+ msger.warning("Skipping missing package '%s'" % (pkg,))
def __select_groups(self, pkg_manager):
skipped_groups = []
(group.name, e))
for group in skipped_groups:
- logging.warn("Skipping missing group '%s'" % (group.name,))
+ msger.warning("Skipping missing group '%s'" % (group.name,))
def __deselect_packages(self, pkg_manager):
for pkg in self._excluded_pkgs:
stdout=subprocess.PIPE)
(md5sum, errorstr) = p.communicate()
if p.returncode != 0:
- logging.warning("Can't generate md5sum for image %s" % image_name)
+ msger.warning("Can't generate md5sum for image %s" % image_name)
else:
pattern = re.compile("\*.*$")
md5sum = pattern.sub("*" + os.path.basename(image_name), md5sum)
""" For image formats with two or multiple image files, it will be better to put them under a directory """
if self.image_format in ("raw", "vmdk", "vdi", "nand", "mrstnand"):
destdir = os.path.join(destdir, "%s-%s" % (self.name, self.image_format))
- logging.debug("creating destination dir: %s" % destdir)
+ msger.debug("creating destination dir: %s" % destdir)
makedirs(destdir)
# Ensure all data is flushed to _outdir
import sys
import tempfile
import shutil
-import logging
import subprocess
import re
import tarfile
if self._recording_pkgs:
self._save_recording_pkgs(destdir)
- logging.info("Copying %s to %s, please be patient to wait" % (self._instroot, destdir + "/" + self.name))
+ msger.info("Copying %s to %s, please be patient to wait" % (self._instroot, destdir + "/" + self.name))
copycmd = find_binary_path("cp")
args = [ copycmd, "-af", self._instroot, destdir + "/" + self.name ]
import glob
import shutil
import subprocess
-import logging
import re
import time
import mic.utils.misc as misc
from mic.utils.errors import *
from loop import LoopImageCreator
+from mic import msger
class LiveImageCreatorBase(LoopImageCreator):
"""A base class for LiveCD image creators.
elif os.path.exists("/usr/lib/anaconda-runtime/implantisomd5"):
implantisomd5 = "/usr/lib/anaconda-runtime/implantisomd5"
else:
- logging.warn("isomd5sum not installed; not setting up mediacheck")
+ msger.warn("isomd5sum not installed; not setting up mediacheck")
implantisomd5 = ""
return
import glob
import shutil
import subprocess
-import logging
import re
import time
import zipfile
import tarfile
import subprocess
-import logging
import mic.kickstart as kickstart
import mic.utils.fs_related as fs_related
from baseimager import BaseImageCreator
from mic.utils.partitionedfs import PartitionedMount
from mic.utils.errors import *
+from mic import msger
class RawImageCreator(BaseImageCreator):
mkinitrd += "rootfs=\"ext3\"\n"
mkinitrd += "rootopts=\"defaults\"\n"
- logging.debug("Writing mkinitrd config %s/etc/sysconfig/mkinitrd" % self._instroot)
+ msger.debug("Writing mkinitrd config %s/etc/sysconfig/mkinitrd" % self._instroot)
os.makedirs(self._instroot + "/etc/sysconfig/",mode=644)
cfg = open(self._instroot + "/etc/sysconfig/mkinitrd", "w")
cfg.write(mkinitrd)
#create disk
for item in disks:
- logging.debug("Adding disk %s as %s/%s-%s.raw" % (item['name'], self.__imgdir,self.name, item['name']))
+ msger.debug("Adding disk %s as %s/%s-%s.raw" % (item['name'], self.__imgdir,self.name, item['name']))
disk = fs_related.SparseLoopbackDisk("%s/%s-%s.raw" % (self.__imgdir,self.name, item['name']),item['size'])
self.__disks[item['name']] = disk
syslinux_conf += "\tmenu default\n"
footlabel += 1;
- logging.debug("Writing syslinux config %s/boot/extlinux/extlinux.conf" % self._instroot)
+ msger.debug("Writing syslinux config %s/boot/extlinux/extlinux.conf" % self._instroot)
cfg = open(self._instroot + "/boot/extlinux/extlinux.conf", "w")
cfg.write(syslinux_conf)
cfg.close()
loopdev = self.__disks[name].device
i =i+1
- logging.debug("Installing syslinux bootloader to %s" % loopdev)
+ msger.debug("Installing syslinux bootloader to %s" % loopdev)
(bootdevnum, rootdevnum, rootdev, prefix) = self._get_syslinux_boot_config()
"""
self._resparse()
- logging.debug("moving disks to stage location")
+ msger.debug("moving disks to stage location")
for name in self.__disks.keys():
src = "%s/%s-%s.raw" % (self.__imgdir, self.name,name)
self._img_name = "%s-%s.%s" % (self.name, name, self.__disk_format)
dst = "%s/%s" % (self._outdir, self._img_name)
- logging.debug("moving %s to %s" % (src,dst))
+ msger.debug("moving %s to %s" % (src,dst))
shutil.move(src,dst)
self._write_image_xml()
xml += " </storage>\n"
xml += "</image>\n"
- logging.debug("writing image XML to %s/%s.xml" % (self._outdir, self.name))
+ msger.debug("writing image XML to %s/%s.xml" % (self._outdir, self.name))
cfg = open("%s/%s.xml" % (self._outdir, self.name), "w")
cfg.write(xml)
cfg.close()
import os,sys
import re
-__ALL__ = ['set_mode', 'info', 'warning', 'error', 'ask']
+__ALL__ = ['set_mode', 'set_loglevel', 'raw' 'debug', 'verbose', 'info', 'warning', 'error', 'ask']
# COLORs in ANSI
INFO_COLOR = 32 # green
INTERACTIVE = True
-def _color_print(head, color, msg = None, stream = sys.stdout):
+LOG_LEVELS = {
+ 'quiet': 0,
+ 'normal': 1,
+ 'verbose': 2,
+ 'debug': 3,
+ }
+LOG_LEVEL = 1
+
+def _color_print(head, color, msg = None, stream = sys.stdout, level = 'normal'):
+
+ if LOG_LEVELS[level] > LOG_LEVEL:
+ # skip
+ return
colored = True
if color == NO_COLOR or \
stream.flush()
-def _color_perror(head, color, msg):
- _color_print(head, color, msg, sys.stderr)
+def _color_perror(head, color, msg, level = 'normal'):
+ _color_print(head, color, msg, sys.stderr, level)
def _split_msg(head, msg):
if msg.startswith('\n'):
return head, msg
+def set_loglevel(level):
+ global LOG_LEVEL
+ if level not in LOG_LEVELS:
+ # no effect
+ return
+
+ LOG_LEVEL = LOG_LEVELS[level]
+
def set_mode(interactive):
global INTERACTIVE
if interactive:
head, msg = _split_msg('Info', msg)
_color_print(head, INFO_COLOR, msg)
+def verbose(msg):
+ head, msg = _split_msg('Verbose', msg)
+ _color_print(head, INFO_COLOR, msg, level = 'verbose')
+
def warning(msg):
head, msg = _split_msg('Warning', msg)
_color_perror(head, WARN_COLOR, msg)
+def debug(msg):
+ head, msg = _split_msg('Debug', msg)
+ _color_perror(head, ERR_COLOR, msg, level = 'debug')
+
def error(msg):
head, msg = _split_msg('Error', msg)
_color_perror(head, ERR_COLOR, msg)
#
import os, sys
-import logging
+from mic import msger
DEFAULT_PLUGIN_LOCATION = "/usr/lib/mic/plugins"
def addPluginDir(self, plugin_dir):
if not os.path.isdir(plugin_dir):
- logging.debug("Plugin dir is not a directory or does not exist: %s" % plugin_dir)
+ msger.debug("Plugin dir is not a directory or does not exist: %s" % plugin_dir)
return
if plugin_dir not in self.plugin_locations:
def pluginCheck(self, pymod):
if not hasattr(pymod, STRING_PLUGIN_MARK):
- logging.debug("Not a valid plugin: %s" % pymod.__file__)
- logging.debug("Please check whether %s given" % STRING_PLUGIN_MARK)
+ msger.debug("Not a valid plugin: %s" % pymod.__file__)
+ msger.debug("Please check whether %s given" % STRING_PLUGIN_MARK)
return False
plclass = getattr(pymod, STRING_PLUGIN_MARK)[1]
if not hasattr(plclass, STRING_PTYPE_MARK):
- logging.debug("Not a valid plugin: %s" % pymod.__file__)
- logging.debug("Please check whether %s given" % STRING_PTYPE_MARK)
+ msger.debug("Not a valid plugin: %s" % pymod.__file__)
+ msger.debug("Please check whether %s given" % STRING_PTYPE_MARK)
return False
pltype = getattr(plclass, STRING_PTYPE_MARK)
if not (pltype in self.plugin_types):
- logging.debug("Unsupported plugin type in %s: %s" % (pymod.__file__, plugintype))
+ msger.debug("Unsupported plugin type in %s: %s" % (pymod.__file__, plugintype))
return False
return True
return
if not plugin_filename.endswith(".py"):
- logging.debug("Not a python file: %s" % os.path.join(dir_path, plugin_filename))
+ msger.debug("Not a python file: %s" % os.path.join(dir_path, plugin_filename))
return
if plugin_filename == ".py":
- logging.debug("Empty module name: %s" % os.path.join(dir_path, plugin_filename))
+ msger.debug("Empty module name: %s" % os.path.join(dir_path, plugin_filename))
return
if plugin_filename == "__init__.py":
- logging.debug("Unsupported python file: %s" % os.path.join(dir_path, plugin_filename))
+ msger.debug("Unsupported python file: %s" % os.path.join(dir_path, plugin_filename))
return
modname = os.path.splitext(plugin_filename)[0]
if sys.modules.has_key(modname):
pymod = sys.modules[modname]
- logging.debug("Module %s already exists: %s" % (modname, pymod.__file__))
+ msger.debug("Module %s already exists: %s" % (modname, pymod.__file__))
else:
pymod = __import__(modname)
pymod.__file__ = os.path.join(dir_path, plugin_filename)
if not self.pluginCheck(pymod):
- logging.warn("Failed to check plugin: %s" % os.path.join(dir_path, plugin_filename))
+ msger.warning("Failed to check plugin: %s" % os.path.join(dir_path, plugin_filename))
return
(pname, pcls) = pymod.__dict__[STRING_PLUGIN_MARK]
def getPluginByCateg(self, categ = None):
if not (categ in self.plugin_types):
- logging.warn("Failed to get plugin category: %s" % categ)
+ msger.warning("Failed to get plugin category: %s" % categ)
return None
else:
return self.plugin_sets[categ]
pass
if __name__ == "__main__":
- logging.getLogger().setLevel(logging.DEBUG)
+ msger.set_loglevel('debug')
pluginmgr = PluginMgr()
pluginmgr.loadPlugins()
import os
import sys
import subprocess
-import logging
import tempfile
import re
import shutil
#convert disk format
if dstfmt != "raw":
raise CreatorError("Invalid destination image format: %s" % dstfmt)
- logging.debug("converting %s image to %s" % (srcimg, dstimg))
+ msger.debug("converting %s image to %s" % (srcimg, dstimg))
if srcfmt == "vmdk":
path = find_binary_path("qemu-img")
argv = [path, "convert", "-f", "vmdk", srcimg, "-O", dstfmt, dstimg]
rc = subprocess.call(argv)
if rc == 0:
- logging.debug("convert successful")
+ msger.debug("convert successful")
if rc != 0:
raise CreatorError("Unable to convert disk to %s" % dstfmt)
stdout=subprocess.PIPE)
(md5sum, errorstr) = p.communicate()
if p.returncode != 0:
- logging.warning("Can't generate md5sum for image %s/%s" %(destdir, f ))
+ msger.warning("Can't generate md5sum for image %s/%s" %(destdir, f ))
else:
md5sum = md5sum.split(" ")[0]
fd.write(md5sum+" "+f+"\n")
import os, sys, re
import rpm
import subprocess
-import logging
+from mic import msger
class RPMInstallCallback:
""" Command line callback class for callbacks from the RPM library.
sys.stdout.flush()
self.lastmsg = msg
if self.total_installed == self.total_actions:
- sys.stdout.write("\n")
- logging.info('\n'.join(self.logString))
+ msger.info('\n'.join(self.logString))
elif what == rpm.RPMCALLBACK_UNINST_START:
pass
import glob
import os
import sys
-import logging
import yum
import rpmUtils
from mic.utils.fs_related import *
from mic.pluginbase.backend_plugin import BackendPlugin
from mic.imager.baseimager import BaseImageCreator as ImageCreator
+from mic import msger
def getRPMCallback():
sys.path.append('/usr/share/yum-cli')
pkgs.remove(x)
self.tsInfo.conditionals[req] = pkgs
else:
- logging.warn("No such package %s to remove" %(pkg,))
+ msger.warning("No such package %s to remove" %(pkg,))
def selectGroup(self, grp, include = ksparser.GROUP_DEFAULT):
try:
if len(deps) != 0:
""" This isn't fatal, Ubuntu has this issue but it is ok. """
print deps
- logging.warn("Dependency check failed!")
+ msger.warning("Dependency check failed!")
rc = self.ts.order()
if rc != 0:
raise CreatorError("ordering packages for installation failed!")
#
import os, sys
-import logging
import mic.utils.misc as misc
import mic.utils.errors as errors
return optparser
def postoptparse(self):
- if self.options.verbose is True:
- logging.getLogger().setLevel(logging.INFO)
- if self.options.debug is True:
- logging.getLogger().setLevel(logging.DEBUG)
- pass
+ if self.options.verbose:
+ msger.set_loglevel('verbose')
+ if self.options.debug:
+ msger.set_loglevel('debug')
@cmdln.alias("cr")
def do_create(self, argv):
if __name__ == "__main__":
try:
mic = Mic()
- ret = mic.main()
- sys.exit(ret)
+ sys.exit(mic.main())
except errors.Usage, msg:
msger.error("Usage error: %s\n" % msg)