return self.chroot[key]
def dumpAllConfig(self):
+ # just for debug
sys.stdout.write("create options:\n")
for key in self.create.keys():
sys.stdout.write("%-8s= %s\n" % (key, self.create[key]))
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-import os
-import os.path
+import os, sys
import stat
-import sys
import tempfile
import shutil
import logging
from mic.utils.rpmmisc import *
from mic.utils.misc import *
from mic.utils import kickstart
+from mic import msger
class BaseImageCreator(object):
"""Installs a system to a chroot directory.
vdso_value = vdso_fh.read().strip()
vdso_fh.close()
if (int)(vdso_value) == 1:
- print "\n= WARNING ="
- print "vdso is enabled on your host, which might cause problems with arm emulations."
- print "You can disable vdso with following command before starting image build:"
- print "echo 0 | sudo tee /proc/sys/vm/vdso_enabled"
- print "= WARNING =\n"
+ msger.warning("vdso is enabled on your host, which might cause problems with arm emulations.\n" +
+ "\tYou can disable vdso with following command before starting image build:\n" +
+ "\techo 0 | sudo tee /proc/sys/vm/vdso_enabled")
return True
pass
def __run_post_scripts(self):
- print "Running scripts"
+ msger.info("Running scripts")
for s in kickstart.get_post_scripts(self.ks):
(fd, path) = tempfile.mkstemp(prefix = "ks-script-",
dir = self._instroot + "/tmp")
self.__save_repo_keys(repodata)
kickstart.MoblinRepoConfig(self._instroot).apply(ksh.repo, repodata)
except:
- print "Failed to apply configuration to image"
+ msger.warning("Failed to apply configuration to image")
raise
self._create_bootconfig()
"""
if launch:
- print "Launching shell. Exit to continue."
- print "----------------------------------"
+ msger.info("Launching shell. Exit to continue.")
subprocess.call(["/bin/bash"], preexec_fn = self._chroot)
def do_genchecksum(self, image_name):
img_location = os.path.join(self._outdir,self._img_name)
if self.__img_compression_method == "bz2":
bzip2 = find_binary_path('bzip2')
- print "Compressing %s with bzip2. Please wait..." % img_location
+ msger.info("Compressing %s with bzip2. Please wait..." % img_location)
rc = subprocess.call([bzip2, "-f", img_location])
if rc:
raise CreatorError("Failed to compress image %s with %s." % (img_location, self.__img_compression_method))
for bootimg in glob.glob(os.path.dirname(img_location) + "/*-boot.bin"):
- print "Compressing %s with bzip2. Please wait..." % bootimg
+ msger.info("Compressing %s with bzip2. Please wait..." % bootimg)
rc = subprocess.call([bzip2, "-f", bootimg])
if rc:
raise CreatorError("Failed to compress image %s with %s." % (bootimg, self.__img_compression_method))
self.package(self.destdir)
def print_outimage_info(self):
- print "Your new image can be found here:"
+ msger.info("Your new image can be found here:")
self.outimage.sort()
for file in self.outimage:
- print os.path.abspath(file)
+ msger.raw(os.path.abspath(file))
def check_depend_tools(self):
for tool in self._dep_checks:
dst = "%s/%s-%s.tar.%s" % (destdir, self.name, image_format, comp)
else:
dst = "%s/%s-%s.tar" % (destdir, self.name, image_format)
- print "creating %s" % dst
+ msger.info("creating %s" % dst)
tar = tarfile.open(dst, "w:" + comp)
for file in self.outimage:
- print "adding %s to %s" % (file, dst)
+ msger.info("adding %s to %s" % (file, dst))
tar.add(file, arcname=os.path.join("%s-%s" % (self.name, image_format), os.path.basename(file)))
if os.path.isdir(file):
shutil.rmtree(file, ignore_errors = True)
from livecd import LiveCDImageCreator
from mic.utils.errors import *
from mic.utils.partitionedfs import PartitionedMount
+from mic import msger
class LiveUSBImageCreator(LiveCDImageCreator):
def __init__(self, *args):
text = text.replace("liveimg", "liveimg " + kernelargs)
if overlaysizemb > 0:
- print "Initializing persistent overlay file"
+ msger.info("Initializing persistent overlay file")
overfile = "overlay" + overlaysuffix
if fstype == "vfat":
args = [ddcmd, "if=/dev/zero", "of=" + usbmnt + "/LiveOS/" + overfile, "count=%d" % overlaysizemb, "bs=1M"]
text = text.replace(" ro ", " rw ")
if swapsizemb > 0:
- print "Initializing swap file"
+ msger.info("Initializing swap file")
swapfile = usbmnt + "/LiveOS/" + "swap.img"
args = [ddcmd, "if=/dev/zero", "of=" + swapfile, "count=%d" % swapsizemb, "bs=1M"]
rc = subprocess.call(args)
raise CreatorError("Can't mkswap on swap file")
if homesizemb > 0:
- print "Initializing persistent /home"
+ msger.info("Initializing persistent /home")
homefile = usbmnt + "/LiveOS/" + homefile
if fstype == "vfat":
args = [ddcmd, "if=/dev/zero", "of=" + homefile, "count=%d" % homesizemb, "bs=1M"]
usbloop.cleanup()
#Need to do this after image is unmounted and device mapper is closed
- print "set MBR"
+ msger.info("set MBR")
mbrfile = "/usr/lib/syslinux/mbr.bin"
if not os.path.exists(mbrfile):
mbrfile = "/usr/share/syslinux/mbr.bin"
import errors
import misc
import fs_related as fs
+from mic import msger
import pykickstart.commands as kscommands
import pykickstart.constants as ksconstants
def call(self, args):
if not os.path.exists("%s/%s" %(self.instroot, args[0])):
- print "%s/%s" %(self.instroot, args[0])
+ msger.warning("%s/%s" %(self.instroot, args[0]))
raise errors.KickstartError("Unable to run %s!" %(args))
subprocess.call(args, preexec_fn = self.chroot)
WARN_COLOR = 33 # yellow
ERR_COLOR = 31 # red
ASK_COLOR = 34 # blue
+NO_COLOR = 0
PREFIX_RE = re.compile('^<(.*?)>\s*(.*)')
def _color_print(head, color, msg = None, stream = sys.stdout):
colored = True
- if not stream.isatty():
- colored = False
- elif os.getenv('ANSI_COLORS_DISABLED') is not None:
+ if color == NO_COLOR or \
+ not stream.isatty() or \
+ os.getenv('ANSI_COLORS_DISABLED') is not None:
colored = False
+ if head.startswith('\r'):
+ # need not \n at last
+ newline = False
+ else:
+ newline = True
+
if colored:
- head = '\033[%dm%s:\033[0m' %(color, head)
+ head = '\033[%dm%s:\033[0m ' %(color, head)
+ if not newline:
+ # ESC cmd to clear line
+ head = '\033[2K' + head
else:
- head += ':'
+ if head:
+ head += ': '
if msg:
- stream.write('%s %s\n' % (head, msg))
+ stream.write('%s%s' % (head, msg))
+ if newline:
+ stream.write('\n')
else:
stream.write('%s ' % head)
+ stream.flush()
+
def _color_perror(head, color, msg):
_color_print(head, color, msg, sys.stderr)
def _split_msg(head, msg):
if msg.startswith('\n'):
+ # means print \n at first
msg = msg.lstrip()
head = '\n' + head
+ elif msg.startswith('\r'):
+ # means print \r at first
+ msg = msg.lstrip()
+ head = '\r' + head
+
m = PREFIX_RE.match(msg)
if m:
head += ' <%s>' % m.group(1)
msg = m.group(2)
+
return head, msg
def set_mode(interactive):
else:
INTERACTIVE = False
+def raw(msg):
+ head, msg = _split_msg('', msg)
+ _color_print(head, NO_COLOR, msg)
+
def info(msg):
head, msg = _split_msg('Info', msg)
_color_print(head, INFO_COLOR, msg)
return self.plugin_sets['hook']
def listAllPlugins(self):
+ # just for debug
for key in self.plugin_sets.keys():
sys.stdout.write("plugin type (%s) :::\n" % key)
for item in self.plugin_sets[key]:
def start(self, filename, url, *args, **kwargs):
self.url = url
self.termwidth = terminal_width()
- if sys.stdout.isatty():
- sys.stdout.write("\r%-*s" % (self.termwidth, " "))
- if self.total is None:
- sys.stdout.write("\rRetrieving %s ..." % truncate_url(self.url, self.termwidth - 15))
- else:
- sys.stdout.write("\rRetrieving %s [%d/%d] ..." % (truncate_url(self.url, self.termwidth - 25), self.counter, self.total))
+ msger.info("\r%-*s" % (self.termwidth, " "))
+ if self.total is None:
+ msger.info("\rRetrieving %s ..." % truncate_url(self.url, self.termwidth - 15))
else:
- sys.stdout.write("Retrieving %s ..." % truncate_url(self.url, self.termwidth - 15))
-
- sys.stdout.flush()
+ msger.info("\rRetrieving %s [%d/%d] ..." % (truncate_url(self.url, self.termwidth - 25), self.counter, self.total))
def update(self, *args):
pass
def end(self, *args):
- if self.counter == self.total or not sys.stdout.isatty():
- sys.stdout.write("\n")
- sys.stdout.flush()
+ if self.counter == self.total:
+ msger.info("\n")
+
self.counter += 1
def find_binary_path(binary):
from errors import *
from fs_related import *
+from mic import msger
+
def setlocale():
import locale
import codecs
output += "%s=%s\n" % (option, siteconf.get(section, option))
output += "\n\n"
- print output
+ msger.info(output)
return output
def get_repostrs_from_ks(ks):
repokey = get_metadata_from_repo(baseurl, proxies, cachedir, reponame, "repodata/repomd.xml.key")
except CreatorError:
repokey = None
- print "Warning: can't get %s/%s" % (baseurl, "repodata/repomd.xml.key")
+ msger.warning("can't get %s/%s" % (baseurl, "repodata/repomd.xml.key"))
my_repo_metadata.append({"name":reponame, "baseurl":baseurl, "repomd":repomd, "primary":primary, "cachedir":cachedir, "proxies":proxies, "patterns":patterns, "comps":comps, "repokey":repokey})
return kickstarts
def select_ks(ksfiles):
- print "Available kickstart files:"
+ msger.info("Available kickstart files:")
i = 0
for ks in ksfiles:
i += 1
- print "\t%d. %s (%s)" % (i, ks["description"], os.path.basename(ks["filename"]))
+ msger.raw("\t%d. %s (%s)" % (i, ks["description"], os.path.basename(ks["filename"])))
+
while True:
choice = raw_input("Please input your choice and press ENTER. [1..%d] ? " % i)
if choice.lower() == "q":
return updated_list
def get_local_distro():
- print "Local linux distribution:"
+ msger.info("Local linux distribution:")
for file in glob.glob("/etc/*-release"):
fd = open(file, "r")
content = fd.read()
fd.close()
- print content
+ msger.info(content)
if os.path.exists("/etc/issue"):
fd = open("/etc/issue", "r")
content = fd.read()
fd.close()
- print content
- print "Local Kernel version: " + os.uname()[2]
+ msger.info(content)
+
+ msger.info("Local Kernel version: " + os.uname()[2])
def check_mic_installation(argv):
creator_name = os.path.basename(argv[0])
src_repometadata = get_source_repometadata(repometadata)
if not src_repometadata:
- print "No source repo found"
+ msger.warning("No source repo found")
return None
src_pkgs = []
if src_pkg:
shutil.copy(src_pkg, destdir)
src_pkgs.append(src_pkg)
- print '--------------------------------------------------'
- print "%d source packages gotten from cache" %cached_count
+ msger.info("%d source packages gotten from cache" %cached_count)
return src_pkgs