continue
chrootmounts.append(fs_related.BindChrootMount(srcdst[0], chrootdir, srcdst[1]))
-
+
"""Default bind mounts"""
for pt in BIND_MOUNTS:
chrootmounts.append(fs_related.BindChrootMount(pt, chrootdir, None))
for kernel in os.listdir("/lib/modules"):
chrootmounts.append(fs_related.BindChrootMount("/lib/modules/" + kernel, chrootdir, None, "ro"))
-
+
return chrootmounts
def bind_mount(chrootmounts):
chroot_lock = os.path.join(chrootdir, ".chroot.lock")
chroot_lockfd = open(chroot_lock, "w")
- return globalmounts
+ return globalmounts
def cleanup_chrootenv(chrootdir, bindmounts = None, globalmounts = []):
global chroot_lockfd, chroot_lock
shutil.rmtree(tmpdir, ignore_errors = True)
else:
print "Warning: dir %s isn't empty." % tmpdir
-
+
chroot_lockfd.close()
bind_unmount(globalmounts)
dev_null = os.open("/dev/null", os.O_WRONLY)
files_to_check = ["/bin/bash", "/sbin/init"]
-
+
architecture_found = False
""" Register statically-linked qemu-arm if it is an ARM fs """
for ftc in files_to_check:
ftc = "%s/%s" % (chrootdir,ftc)
-
+
# Return code of 'file' is "almost always" 0 based on some man pages
# so we need to check the file existance first.
if not os.path.exists(ftc):
continue
filecmd = misc.find_binary_path("file")
-
+
for line in subprocess.Popen([filecmd, ftc],
stdout=subprocess.PIPE,
stderr=dev_null).communicate()[0].strip().splitlines():
if 'Intel' in line:
architecture_found = True
break
-
+
if architecture_found:
break
-
+
os.close(dev_null)
if not architecture_found:
raise errors.CreatorError("Failed to get architecture from any of the following files %s from chroot." % files_to_check)
finally:
cleanup_chrootenv(chrootdir, bindmounts, globalmounts)
if qemu_emulator:
- os.unlink(chrootdir + qemu_emulator)
+ os.unlink(chrootdir + qemu_emulator)
optparser.add_option('-d', '--debug', action='store_true', help='print debug info')
optparser.add_option('-v', '--verbose', action='store_true', help='verbose output')
#optparser.add_option('-o', '--outdir', type='string', action='store', dest='outdir', default=None, help='output directory')
- return optparser
+ return optparser
def preoptparse(self, argv):
pass
filesystem labels
"""
- self.pkgmgr = pkgmgr
+ self.pkgmgr = pkgmgr
if createopts:
# A pykickstart.KickstartParser instance."""
if not os.path.exists("/usr/bin/qemu-arm") or not is_statically_linked("/usr/bin/qemu-arm"):
self._dep_checks.append("qemu-arm-static")
-
+
if os.path.exists("/proc/sys/vm/vdso_enabled"):
vdso_fh = open("/proc/sys/vm/vdso_enabled","r")
vdso_value = vdso_fh.read().strip()
"""
def get_kernel_versions(self, instroot):
ret = {}
- versions = set()
+ versions = set()
files = glob.glob(instroot + "/boot/vmlinuz-*")
for file in files:
version = os.path.basename(file)[8:]
(name, baseurl, mirrorlist, inc, exc, proxy, proxy_username, proxy_password, debuginfo, source, gpgkey, disable) = repo
yr = pkg_manager.addRepository(name, baseurl, mirrorlist, proxy, proxy_username, proxy_password, inc, exc)
-
+
if kickstart.exclude_docs(self.ks):
rpm.addMacro("_excludedocs", "1")
rpm.addMacro("__file_context_path", "%{nil}")
import re
import time
-import mic.utils.kickstart as kickstart
+import mic.utils.kickstart as kickstart
import mic.utils.fs_related as fs_related
import mic.utils.rpmmisc as rpmmisc
import mic.utils.misc as misc
This class serves as a base class for the architecture-specific LiveCD
image creator subclass, LiveImageCreator.
-
+
LiveImageCreator creates a bootable ISO containing the system image,
bootloader, bootloader configuration, kernel and initramfs.
"""
LoopImageCreator.__init__(self, creatoropts, pkgmgr)
#Controls whether to use squashfs to compress the image.
- self.skip_compression = False
+ self.skip_compression = False
#Controls whether an image minimizing snapshot should be created.
#
#order to minimize the amount of data that needs to be copied; simply,
#it makes it possible to create a version of the image's filesystem with
#no spare space.
- self.skip_minimize = False
+ self.skip_minimize = False
#A flag which indicates i act as a convertor default false
self.actasconvertor = False
-
+
#The bootloader timeout from kickstart.
if self.ks:
self._timeout = kickstart.get_timeout(self.ks, 10)
This is the hook where subclasses must create the booloader
configuration in order to allow a bootable ISO to be built.
-
+
isodir -- the directory where the contents of the ISO are to be staged
"""
raise CreatorError("Bootloader configuration is arch-specific, "
This is the hook where subclasses may specify a set of kernel options
which should be included in the images bootloader configuration.
-
+
A sensible default implementation is provided.
"""
if self.ks is None:
This is the hook where subclasses may specify additional arguments to
mkisofs, e.g. to enable a bootable ISO to be built.
-
+
By default, an empty list is returned.
"""
return []
is_xen = self.__copy_kernel_and_initramfs(isodir, version, index)
default = self.__is_default_kernel(kernel, kernels)
-
-
+
if default:
long = "Boot %s" % self.distro_name
elif kernel.startswith("kernel-"):
This method takes the same arguments as ImageCreator.__init__() with
the addition of:
-
+
fslabel -- A string used as a label for any filesystems created.
"""
BaseImageCreator.__init__(self, creatoropts, pkgmgr)
#mke2fs silently truncates the label, but mkisofs aborts if the label is too
#long. So, for convenience sake, any string assigned to this attribute is
#silently truncated to FSLABEL_MAXLEN (32) characters.
-
fslabel = property(__get_fslabel, __set_fslabel)
#
#This is the path to the filesystem image. Subclasses may use this path
#in order to package the image in _stage_final_image().
- #
+ #
#Note, this directory does not exist before ImageCreator.mount() is called.
#
#Note also, this is a read-only attribute.
#
#Note, only ext2 and ext3 are currently supported.
#
- #Note also, this attribute may only be set before calling mount().
+ #Note also, this attribute may only be set before calling mount().
_fstype = property(__get_fstype, __set_fstype)
This method should be used by subclasses when staging the final image
in order to reduce the actual space taken up by the sparse image file
to be as little as possible.
-
+
This is done by resizing the filesystem to the minimal size (thereby
eliminating any space taken up by deleted files) and then resizing it
back to the supplied size.
-
+
size -- the size in, in bytes, which the filesystem image should be
resized to after it has been minimized; this defaults to None,
causing the original size specified by the kickstart file to
import subprocess
import logging
-import mic.utils.kickstart as kickstart
+import mic.utils.kickstart as kickstart
import mic.utils.fs_related as fs_related
import urlgrabber.progress as progress
from baseimager import BaseImageCreator
if os.path.exists(self._instroot + "/usr/bin/Xorg"):
subprocess.call(["/bin/chmod", "u+s", "/usr/bin/Xorg"], preexec_fn = chroot)
BaseImageCreator.configure(self, repodata)
-
+
def _get_fstab(self):
s = ""
for mp in self.__instloop.mountOrder:
raise CreatorError("Failed to create disks, no --fstype specified in partition line of ks file")
size = parts[i].size * 1024L * 1024L
-
+
found = False
for j in range(len(disks)):
if disks[j]['name'] == disk:
disks[j]['size'] = disks[j]['size'] + size
found = True
break
- else:
+ else:
found = False
if not found:
disks.append({ 'name': disk, 'size': size })
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))
- shutil.move(src,dst)
+ shutil.move(src,dst)
self._write_image_xml()
def _write_image_xml(self):
def do_unpack(self):
pass
-# [a, b]: a is for subcmd name, b is for plugin class
+# [a, b]: a is for subcmd name, b is for plugin class
mic_plugin = ["", None]
# intial plugin sets
for plugintype in self.plugin_types:
self.plugin_sets[plugintype] = []
-
+
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)
logging.warn("Failed to get plugin category: %s" % categ)
return None
else:
- return self.plugin_sets[categ]
+ return self.plugin_sets[categ]
def getImagerPlugins(self):
return self.plugin_sets['imager']
if not os.path.exists(file):
return ret
dev_null = os.open("/dev/null", os.O_WRONLY)
- rc = subprocess.call([fuser, "-s", file], stderr=dev_null)
+ rc = subprocess.call([fuser, "-s", file], stderr=dev_null)
if rc == 0:
fuser_proc = subprocess.Popen([fuser, file], stdout=subprocess.PIPE, stderr=dev_null)
pids = fuser_proc.communicate()[0].strip().split()
def remove(self, ignore_errors = False):
if not self.__created:
return
-
+
time.sleep(2)
rc = subprocess.call([self.dmsetupcmd, "remove", self.__name])
if not ignore_errors and rc != 0:
def set_encrypted(self, password):
self.call(["/usr/sbin/usermod", "-p", password, "root"])
- def set_unencrypted(self, password):
+ def set_unencrypted(self, password):
for p in ("/bin/echo", "/usr/sbin/chpasswd"):
if not os.path.exists("%s/%s" %(self.instroot, p)):
- raise errors.KickstartError("Unable to set unencrypted password due to lack of %s" % p)
-
+ raise errors.KickstartError("Unable to set unencrypted password due to lack of %s" % p)
+
p1 = subprocess.Popen(["/bin/echo", "root:%s" %password],
stdout = subprocess.PIPE,
preexec_fn = self.chroot)
args = repostr.split()
repoobj = ks.handler.repo.parse(args[1:])
if repoobj and repoobj not in ks.handler.repo.repoList:
- ks.handler.repo.repoList.append(repoobj)
+ ks.handler.repo.repoList.append(repoobj)
def remove_all_repos(ks):
while len(ks.handler.repo.repoList) != 0:
continue
"""
- But we also must handle such cases, use zypp but repo only has comps,
+ But we also must handle such cases, use zypp but repo only has comps,
use yum but repo only has patterns, use zypp but use_comps is true,
use yum but use_comps is false.
"""
if (not use_comps and repo["patterns"]) or (not repo["comps"] and repo["patterns"]):
groupfile = repo["patterns"]
get_pkglist_handler = misc.get_pkglist_in_patterns
-
+
if groupfile:
i = 0
while True:
target_repo = repo
break
con.close()
- if target_repo:
+ if target_repo:
makedirs("%s/%s/packages" % (target_repo["cachedir"], target_repo["name"]))
url = str(target_repo["baseurl"] + "/" + pkgpath)
filename = str("%s/%s/packages/%s" % (target_repo["cachedir"], target_repo["name"], os.path.basename(pkgpath)))
""" Create release directory and files """
os.system ("cp %s %s/%s.ks" % (config, destdir, name))
- # When building a release we want to make sure the .ks
+ # When building a release we want to make sure the .ks
# file generates the same build even when --release= is not used.
fd = open(config, "r")
kscont = fd.read()
m = re.match("(.*)-(\d+.*)-(\d+\.\d+).src.rpm", srpm)
if m:
return m.group(1)
- return None
+ return None
src_repometadata = get_source_repometadata(repometadata)
for repo in src_repometadata:
cachepath = "%s/%s/packages/*.src.rpm" %(cachedir, repo["name"])
lpkgs_path += glob.glob(cachepath)
-
+
for lpkg in lpkgs_path:
lpkg_name = get_src_name(os.path.basename(lpkg))
lpkgs_dict[lpkg_name] = lpkg
localpkgs = lpkgs_dict.keys()
-
+
cached_count = 0
destdir = instroot+'/usr/src/SRPMS'
if not os.path.exists(destdir):
os.makedirs(destdir)
-
+
srcpkgset = set()
for _pkg in pkgs:
srcpkg_name = get_source_name(_pkg, repometadata)
if not srcpkg_name:
return None
srcpkgset.add(srcpkg_name)
-
+
for pkg in list(srcpkgset):
if pkg in localpkgs:
cached_count += 1
else:
src_pkg = get_package(pkg, src_repometadata, 'src')
if src_pkg:
- shutil.copy(src_pkg, destdir)
+ shutil.copy(src_pkg, destdir)
src_pkgs.append(src_pkg)
print '--------------------------------------------------'
print "%d source packages gotten from cache" %cached_count
'mapped': False, # True if kpartx mapping exists
'numpart': 0, # Number of allocate partitions
'partitions': [], # indexes to self.partitions
- # Partitions with part num higher than 3 will
+ # Partitions with part num higher than 3 will
# be put inside extended partition.
'extended': 0, # Size of extended partition
# Sector 0 is used by the MBR and can't be used
def __format_disks(self):
logging.debug("Assigning partitions to disks")
-
+
mbr_sector_skipped = False
-
+
for n in range(len(self.partitions)):
p = self.partitions[n]
if not self.disks.has_key(p['disk']):
raise MountError("No disk %s for partition %s" % (p['disk'], p['mountpoint']))
-
+
if not mbr_sector_skipped:
# This hack is used to remove one sector from the first partition,
# that is the used to the MBR.
if self.skipformat:
logging.debug("Skipping disk format, because skipformat flag is set.")
return
-
+
for dev in self.disks.keys():
d = self.disks[dev]
logging.debug("Initializing partition table for %s" % (d['disk'].device))
p1 = subprocess.Popen([self.parted, "-s", d['disk'].device, "mklabel", "msdos"],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
- (out,err) = p1.communicate()
+ (out,err) = p1.communicate()
logging.debug(out)
-
+
if p1.returncode != 0:
# NOTE: We don't throw exception when return code is not 0, because
# parted always fails to reload part table with loop devices.
d = self.disks[p['disk']]
if p['num'] == 5:
self.__create_part_to_image(d['disk'].device,"extended",None,p['start'],d['extended'])
-
+
if p['fstype'] == "swap":
parted_fs_type = "linux-swap"
elif p['fstype'] == "vfat":
# Type for ext2/ext3/ext4/btrfs
parted_fs_type = "ext2"
- # Boot ROM of OMAP boards require vfat boot partition to have an
+ # Boot ROM of OMAP boards require vfat boot partition to have an
# even number of sectors.
if p['mountpoint'] == "/boot" and p['fstype'] in ["vfat","msdos"] and p['size'] % 2:
logging.debug("Substracting one sector from '%s' partition to get even number of sectors for the partition." % (p['mountpoint']))
p['size'] -= 1
-
- p1 = self.__create_part_to_image(d['disk'].device,p['type'],
- parted_fs_type, p['start'],
+
+ p1 = self.__create_part_to_image(d['disk'].device,p['type'],
+ parted_fs_type, p['start'],
p['size'])
if p1.returncode != 0:
logging.debug(boot_cmd)
p1 = subprocess.Popen(boot_cmd,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
- (out,err) = p1.communicate()
+ (out,err) = p1.communicate()
logging.debug(out)
if p1.returncode != 0:
logging.debug("Adding partx mapping for %s" % d['disk'].device)
p1 = subprocess.Popen([self.kpartx, "-v", "-a", d['disk'].device],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
-
+
(out,err) = p1.communicate()
logging.debug(out)
-
+
if p1.returncode != 0:
# Make sure that the device maps are also removed on error case.
# The d['mapped'] isn't set to True if the kpartx fails so
break
pdisk.fsopts = ",".join(opts)
break
-
+
if len(self.subvolumes) == 0:
""" Return directly if no subvolumes """
return
if p1.returncode != 0:
raise MountError("Failed to create subvolume snapshot '%s' for '%s', return code: %d." % (snapshotpath, subvolpath, p1.returncode))
self.snapshot_created = True
-
+
def mount(self):
for dev in self.disks.keys():
d = self.disks[dev]
if p['fstype'] == "btrfs" and not p['fsopts']:
p['fsopts'] = "subvolid=0"
-
+
pdisk = myDiskMount(RawDisk(p['size'] * self.sector_size, p['device']),
self.mountdir + p['mountpoint'],
p['fstype'],
fmt = "\r %-10.10s: " + bar + " " + done
else:
bar = fmt_bar % (self.mark * marks, )
- fmt = " %-10.10s: " + bar + " " + done
+ fmt = " %-10.10s: " + bar + " " + done
return fmt
def _logPkgString(self, hdr):
# log stuff
#pkgtup = self._dopkgtup(hdr)
self.logString.append(self._logPkgString(hdr))
-
elif what == rpm.RPMCALLBACK_INST_PROGRESS:
if h is not None:
elif what == rpm.RPMCALLBACK_UNINST_STOP:
self.total_removed += 1
-
+
elif what == rpm.RPMCALLBACK_REPACKAGE_START:
pass
elif what == rpm.RPMCALLBACK_REPACKAGE_STOP:
return arch
# dict mapping arch -> ( multicompat, best personality, biarch personality )
-multilibArches = {
+multilibArches = {
"x86_64": ( "athlon", "x86_64", "athlon" ),
"sparc64v": ( "sparc", "sparcv9v", "sparc64v" ),
"sparc64": ( "sparc", "sparcv9", "sparc64" ),
finally:
os.close(dev_null)
- return ret
+ return ret
def checkSig(ts, package):
""" Takes a transaction set and a package, check it's sigs,
if not isinstance(creator, ImageCreator):
raise CreatorError("Invalid argument: creator")
yum.YumBase.__init__(self)
-
+
self.creator = creator
-
+
if self.creator.target_arch:
if rpmUtils.arch.arches.has_key(self.creator.target_arch):
self.arch.setup_arch(self.creator.target_arch)
try:
self.downloadPkgs(dlpkgs)
# FIXME: sigcheck?
-
+
self.initActionTs()
self.populateTs(keepold=0)
deps = self.ts.check()
rc = self.ts.order()
if rc != 0:
raise CreatorError("ordering packages for installation failed!")
-
+
# FIXME: callback should be refactored a little in yum
sys.path.append('/usr/share/yum-cli')
import callback
""" Select a given package or package pattern, can be specified with name.arch or name* or *name """
if not self.Z:
self.__initialize_zypp()
-
+
found = False
startx = pkg.startswith("*")
endx = pkg.endswith("*")
def deselectPackage(self, pkg):
"""Deselect package. Can be specified as name.arch or name*"""
-
+
if not self.Z:
self.__initialize_zypp()
-
+
startx = pkg.startswith("*")
endx = pkg.endswith("*")
ispattern = startx or endx
item.status().resetTransact(zypp.ResStatus.USER)
if name in self.packages:
self.packages.remove(name)
- break
+ break
else:
if startx and name.endswith(sp[0][1:]):
if item.status().isToBeInstalled():
item.status().resetTransact(zypp.ResStatus.USER)
if name in self.packages:
self.packages.remove(name)
-
- def __selectIncpkgs(self):
+
+ def __selectIncpkgs(self):
found = False
for pkg in self.incpkgs:
for item in self.Z.pool():
if name not in self.packages:
self.packages.append(name)
item.status().setToBeInstalled (zypp.ResStatus.USER)
- break
+ break
if not found:
raise CreatorError("Unable to find package: %s" % (pkg,))
-
- def __selectExcpkgs(self):
- found = False
+
+ def __selectExcpkgs(self):
+ found = False
for pkg in self.excpkgs:
for item in self.Z.pool():
kind = "%s" % item.kind()
if name not in self.packages:
self.packages.append(name)
item.status().setToBeInstalled (zypp.ResStatus.USER)
- break
+ break
if not found:
raise CreatorError("Unable to find package: %s" % (pkg,))
-
def selectGroup(self, grp, include = pykickstart.parser.GROUP_DEFAULT):
if not self.Z:
self.__initialize_zypp()
self.patterns.append(name)
item.status().setToBeInstalled (zypp.ResStatus.USER)
break
-
+
if found:
if include == pykickstart.parser.GROUP_REQUIRED:
map(lambda p: self.deselectPackage(p), grp.default_packages.keys())
self.__selectIncpkgs()
if self.excpkgs:
self.__selectExcpkgs()
-
+
os.environ["HOME"] = "/"
self.buildTransaction()
print "downloading packages..."
self.downloadPkgs(dlpkgs, download_count)
self.installPkgs(dlpkgs)
-
+
except RepoError, e:
raise CreatorError("Unable to download from repo : %s" % (e,))
except RpmError, e:
shutil.rmtree(self.creator.cachedir + "/etc", ignore_errors = True)
shutil.rmtree(self.creator.cachedir + "/raw", ignore_errors = True)
shutil.rmtree(self.creator.cachedir + "/solv", ignore_errors = True)
-
+
zypp.KeyRing.setDefaultAccept( zypp.KeyRing.ACCEPT_UNSIGNED_FILE
| zypp.KeyRing.ACCEPT_VERIFICATION_FAILED
| zypp.KeyRing.ACCEPT_UNKNOWNKEY
self.repo_manager_options.repoRawCachePath = zypp.Pathname(self.creator.cachedir + "/raw")
self.repo_manager_options.repoSolvCachePath = zypp.Pathname(self.creator.cachedir + "/solv")
self.repo_manager_options.repoPackagesCachePath = zypp.Pathname(self.creator.cachedir + "/packages")
-
+
self.repo_manager = zypp.RepoManager(self.repo_manager_options)
elif self.creator.target_arch == "armv7nhl":
arch_map["armv7nhl"] = zypp.Arch_armv7nhl()
elif self.creator.target_arch == "armv7hl":
- arch_map["armv7hl"] = zypp.Arch_armv7hl()
+ arch_map["armv7hl"] = zypp.Arch_armv7hl()
zconfig.setSystemArchitecture(arch_map[self.creator.target_arch])
print "zypp architecture: %s" % zconfig.systemArchitecture()
proxies = {}
if proxy:
proxies = {str(proxy.split(":")[0]):str(proxy)}
-
+
location = zypp.asKindPackage(po).location()
location = location.filename().__str__()
if location.startswith("./"):
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)
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:
print '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"
-
+
creator.configure(createopts["repomd"])
creator.unmount()
creator.package(createopts["outdir"])
finally:
creator.cleanup()
print "Finished."
- return 0
-
+
+ return 0
+
@classmethod
def do_chroot(self, target):#chroot.py parse opts&args
try:
finally:
chroot.cleanup_after_chroot("dir", None, None, None)
return 1
-
+
mic_plugin = ["fs", FsPlugin]
creatoropts = cfgmgr.create
plgmgr = pluginmgr.PluginMgr()
plgmgr.loadPlugins()
-
+
for (key, pcls) in plgmgr.getBackendPlugins():
if key == creatoropts['pkgmgr']:
pkgmgr = pcls
creatoropts = cfgmgr.create
cfgmgr.setProperty("ksconf", args[0])
plgmgr = pluginmgr.PluginMgr()
- plgmgr.loadPlugins()
+ plgmgr.loadPlugins()
for (key, pcls) in plgmgr.getBackendPlugins():
if key == creatoropts['pkgmgr']:
import mic.utils.misc as misc
import mic.utils.cmdln as cmdln
import mic.utils.fs_related as fs_related
-from mic.utils.errors import *
+from mic.utils.errors import *
import mic.configmgr as configmgr
import mic.pluginmgr as pluginmgr
import mic.imager.loop as loop
plgmgr = pluginmgr.PluginMgr()
plgmgr.loadPlugins()
-
+
for (key, pcls) in plgmgr.getBackendPlugins():
if key == creatoropts['pkgmgr']:
pkgmgr = pcls
creator = loop.LoopImageCreator(creatoropts, pkgmgr)
try:
creator.check_depend_tools()
- creator.mount(None, creatoropts["cachedir"])
+ creator.mount(None, creatoropts["cachedir"])
creator.install()
creator.configure(creatoropts["repomd"])
creator.unmount()
finally:
creator.cleanup()
print "Finished."
- return 0
-
+ return 0
+
@classmethod
def do_chroot(cls, target):#chroot.py parse opts&args
#import pdb
try:
chroot.chroot(extmnt, None, "/bin/env HOME=/root /bin/bash")
except:
- raise CreatorError("Failed to chroot to %s." %img)
+ raise CreatorError("Failed to chroot to %s." %img)
finally:
chroot.cleanup_after_chroot("img", extloop, None, extmnt)
@classmethod
def do_unpack(cls, srcimg):
image = os.path.join(tempfile.mkdtemp(dir = "/var/tmp", prefix = "tmp"), "meego.img")
- print "Copying file system..."
+ print "Copying file system..."
shutil.copyfile(srcimg, image)
return image
-
mic_plugin = ["loop", LoopPlugin]
cfgmgr.setProperty("ksconf", ksconf)
plgmgr = pluginmgr.PluginMgr()
plgmgr.loadPlugins()
-
+
for (key, pcls) in plgmgr.getBackendPlugins():
if key == creatoropts['pkgmgr']:
pkgmgr = pcls
creator.cleanup()
print "Finished."
return 0
-
- @classmethod
+
+ @classmethod
def do_chroot(cls, target):
img = target
imgsize = misc.get_file_size(img) * 1024L * 1024L
imgmnt = misc.mkdtemp()
imgloop = PartitionedMount({'/dev/sdb':disk}, imgmnt, skipformat = True)
img_fstype = "ext3"
-
+
# Check the partitions from raw disk.
p1 = subprocess.Popen([partedcmd,"-s",img,"unit","B","print"],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out,err = p1.communicate()
lines = out.strip().split("\n")
-
+
root_mounted = False
partition_mounts = 0
# because parted can be translated we can't refer to any text lines.
if not line or not line[0].isdigit():
continue
-
+
# Some vars have extra , as list seperator.
line = line.replace(",","")
-
+
# Example of parted output lines that are handled:
# Number Start End Size Type File system Flags
# 1 512B 3400000511B 3400000000B primary
if len(partition_info) < 6 or partition_info[5] in ["boot"]:
# No filesystem can be found from partition line. Assuming
- # btrfs, because that is the only MeeGo fs that parted does
+ # btrfs, because that is the only MeeGo fs that parted does
# not recognize properly.
# TODO: Can we make better assumption?
fstype = "btrfs"
boot = True
else:
boot = False
-
+
print "Size: %s Bytes, fstype: %s, mountpoint: %s, boot: %s" % ( size, fstype, mountpoint, boot )
# TODO: add_partition should take bytes as size parameter.
imgloop.add_partition((int)(size)/1024/1024, "/dev/sdb", mountpoint, fstype = fstype, boot = boot)
-
+
try:
imgloop.mount()
except MountError, e:
try:
chroot.chroot(imgmnt, None, "/bin/env HOME=/root /bin/bash")
except:
- raise CreatorError("Failed to chroot to %s." %img)
+ raise CreatorError("Failed to chroot to %s." %img)
finally:
chroot.cleanup_after_chroot("img", imgloop, None, imgmnt)
-
+
@classmethod
def do_unpack(cls, srcimg):
srcimgsize = (misc.get_file_size(srcimg)) * 1024L * 1024L
import mic.creator as creator
class Mic(cmdln.Cmdln):
- """ Usage: mic SUBCOMMAND [OPTS] [ARGS...]
+ """
+ Usage: mic SUBCOMMAND [OPTS] [ARGS...]
- MeeGo Image Creator Tool.
+ Image Creator
${command_list}
${help_list}
@cmdln.alias("cv")
def do_convert(self, subcmd, opts, *args):
"""${cmd_name}: convert an image format to another one
-
+
usage:
- mic convert <imagefile> <destformat>
+ mic convert <imagefile> <destformat>
"""
if len(args) == 0:
self.emptyline()
@cmdln.option("-v", "--verbose", action="store_true", help="verbose infomation")
@cmdln.alias("ch")
def do_chroot(self, subcmd, opts, *args):
- """${cmd_name}: chroot an image
+ """${cmd_name}: chroot into an image
usage:
mic chroot <imagefile>