本文整理汇总了Python中pylorax.executils.runcmd函数的典型用法代码示例。如果您正苦于以下问题:Python runcmd函数的具体用法?Python runcmd怎么用?Python runcmd使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了runcmd函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: mkfsimage
def mkfsimage(fstype, rootdir, outfile, size=None, mkfsargs=None, mountargs="", graft=None):
'''Generic filesystem image creation function.
fstype should be a filesystem type - "mkfs.${fstype}" must exist.
graft should be a dict: {"some/path/in/image": "local/file/or/dir"};
if the path ends with a '/' it's assumed to be a directory.
Will raise CalledProcessError if something goes wrong.'''
mkfsargs = mkfsargs or []
graft = graft or {}
preserve = (fstype not in ("msdos", "vfat"))
if not size:
size = estimate_size(rootdir, graft, fstype)
with LoopDev(outfile, size) as loopdev:
try:
runcmd(["mkfs.%s" % fstype] + mkfsargs + [loopdev])
except CalledProcessError as e:
logger.error("mkfs exited with a non-zero return code: %d", e.returncode)
logger.error(e.output)
sys.exit(e.returncode)
with Mount(loopdev, mountargs) as mnt:
if rootdir:
copytree(rootdir, mnt, preserve)
do_grafts(graft, mnt, preserve)
# Make absolutely sure that the data has been written
runcmd(["sync"])
示例2: rebuild_initrds
def rebuild_initrds(self, add_args=[], backup="", prefix=""):
'''Rebuild all the initrds in the tree. If backup is specified, each
initrd will be renamed with backup as a suffix before rebuilding.
If backup is empty, the existing initrd files will be overwritten.
If suffix is specified, the existing initrd is untouched and a new
image is built with the filename "${prefix}-${kernel.version}.img"
'''
dracut = ["dracut", "--nomdadmconf", "--nolvmconf"] + add_args
if not backup:
dracut.append("--force")
# Hush some dracut warnings. TODO: bind-mount proc in place?
open(joinpaths(self.vars.inroot,"/proc/modules"),"w")
for kernel in self.kernels:
if prefix:
idir = os.path.dirname(kernel.initrd.path)
outfile = joinpaths(idir, prefix+'-'+kernel.version+'.img')
else:
outfile = kernel.initrd.path
logger.info("rebuilding %s", outfile)
if backup:
initrd = joinpaths(self.vars.inroot, outfile)
os.rename(initrd, initrd + backup)
cmd = dracut + [outfile, kernel.version]
runcmd(cmd, root=self.vars.inroot)
os.unlink(joinpaths(self.vars.inroot,"/proc/modules"))
示例3: generate_module_data
def generate_module_data(self):
root = self.vars.root
moddir = joinpaths(root, "lib/modules/")
for kver in os.listdir(moddir):
ksyms = joinpaths(root, "boot/System.map-%s" % kver)
logger.info("doing depmod and module-info for %s", kver)
runcmd(["depmod", "-a", "-F", ksyms, "-b", root, kver])
generate_module_info(moddir+kver, outfile=moddir+"module-info")
示例4: copytree
def copytree(src, dest, preserve=True):
'''Copy a tree of files using cp -a, thus preserving modes, timestamps,
links, acls, sparse files, xattrs, selinux contexts, etc.
If preserve is False, uses cp -R (useful for modeless filesystems)
raises CalledProcessError if copy fails.'''
logger.debug("copytree %s %s", src, dest)
cp = ["cp", "-a"] if preserve else ["cp", "-R", "-L"]
cp += [join(src, "."), os.path.abspath(dest)]
runcmd(cp)
示例5: dm_attach
def dm_attach(dev, size, name=None):
'''Attach a devicemapper device to the given device, with the given size.
If name is None, a random name will be chosen. Returns the device name.
raises CalledProcessError if dmsetup fails.'''
if name is None:
name = tempfile.mktemp(prefix="lorax.imgutils.", dir="")
runcmd(["dmsetup", "create", name, "--table",
"0 %i linear %s 0" % (size/512, dev)])
return name
示例6: mkqcow2
def mkqcow2(outfile, size, options=None):
'''use qemu-img to create a file of the given size.
options is a list of options passed to qemu-img
Default format is qcow2, override by passing "-f", fmt
in options.
'''
options = options or []
if "-f" not in options:
options.extend(["-f", "qcow2"])
runcmd(["qemu-img", "create"] + options + [outfile, str(size)])
示例7: gconfset
def gconfset(self, path, keytype, value, outfile=None):
'''
gconfset PATH KEYTYPE VALUE [OUTFILE]
Set the given gconf PATH, with type KEYTYPE, to the given value.
OUTFILE defaults to /etc/gconf/gconf.xml.defaults if not given.
Example:
gconfset /apps/metacity/general/num_workspaces int 1
'''
if outfile is None:
outfile = self._out("etc/gconf/gconf.xml.defaults")
cmd = ["gconftool-2", "--direct",
"--config-source=xml:readwrite:%s" % outfile,
"--set", "--type", keytype, path, value]
runcmd(cmd)
示例8: generate_module_data
def generate_module_data(self):
root = self.vars.root
moddir = joinpaths(root, "lib/modules/")
# Generate_module_data creates a file called "module-info" in this
# directory. If we don't do something to exclude this file, depmod will fail
# on the second path of this loop. Let's check to see if kver is a directory
# before generating module info from it.
for kver in os.listdir(moddir):
if os.path.isdir(kver):
ksyms = joinpaths(root, "boot/System.map-%s" % kver)
logger.info("doing depmod and module-info for %s", kver)
runcmd(["depmod", "-a", "-F", ksyms, "-b", root, kver])
generate_module_info(moddir+kver, outfile=moddir+"module-info")
示例9: mount
def mount(dev, opts="", mnt=None):
'''Mount the given device at the given mountpoint, using the given opts.
opts should be a comma-separated string of mount options.
if mnt is none, a temporary directory will be created and its path will be
returned.
raises CalledProcessError if mount fails.'''
if mnt is None:
mnt = tempfile.mkdtemp(prefix="lorax.imgutils.")
logger.debug("make tmp mountdir %s", mnt)
cmd = ["mount"]
if opts:
cmd += ["-o", opts]
cmd += [dev, mnt]
runcmd(cmd)
return mnt
示例10: umount
def umount(mnt, lazy=False, maxretry=3, retrysleep=1.0):
'''Unmount the given mountpoint. If lazy is True, do a lazy umount (-l).
If the mount was a temporary dir created by mount, it will be deleted.
raises CalledProcessError if umount fails.'''
cmd = ["umount"]
if lazy: cmd += ["-l"]
cmd += [mnt]
count = 0
while maxretry > 0:
try:
rv = runcmd(cmd)
except CalledProcessError:
count += 1
if count == maxretry:
raise
logger.warn("failed to unmount %s. retrying (%d/%d)...",
mnt, count, maxretry)
if logger.getEffectiveLevel() <= logging.DEBUG:
fuser = execWithCapture("fuser", ["-vm", mnt])
logger.debug("fuser -vm:\n%s\n", fuser)
sleep(retrysleep)
else:
break
if 'lorax.imgutils' in mnt:
os.rmdir(mnt)
logger.debug("remove tmp mountdir %s", mnt)
return (rv == 0)
示例11: rebuild_initrds
def rebuild_initrds(self, add_args=None, backup="", prefix=""):
'''Rebuild all the initrds in the tree. If backup is specified, each
initrd will be renamed with backup as a suffix before rebuilding.
If backup is empty, the existing initrd files will be overwritten.
If suffix is specified, the existing initrd is untouched and a new
image is built with the filename "${prefix}-${kernel.version}.img"
If the initrd doesn't exist its name will be created based on the
name of the kernel.
'''
add_args = add_args or []
dracut = ["dracut", "--nomdadmconf", "--nolvmconf"] + add_args
if not backup:
dracut.append("--force")
if not self.kernels:
raise Exception("No kernels found, cannot rebuild_initrds")
# Hush some dracut warnings. TODO: bind-mount proc in place?
open(joinpaths(self.vars.inroot,"/proc/modules"),"w")
for kernel in self.kernels:
if prefix:
idir = os.path.dirname(kernel.path)
outfile = joinpaths(idir, prefix+'-'+kernel.version+'.img')
elif hasattr(kernel, "initrd"):
# If there is an existing initrd, use that
outfile = kernel.initrd.path
else:
# Construct an initrd from the kernel name
outfile = kernel.path.replace("vmlinuz-", "initrd-") + ".img"
logger.info("rebuilding %s", outfile)
if backup:
initrd = joinpaths(self.vars.inroot, outfile)
if os.path.exists(initrd):
os.rename(initrd, initrd + backup)
cmd = dracut + [outfile, kernel.version]
runcmd(cmd, root=self.vars.inroot)
# ppc64 cannot boot images > 32MiB, check size and warn
if self.vars.arch.basearch in ("ppc64", "ppc64le") and os.path.exists(outfile):
st = os.stat(outfile)
if st.st_size > 32 * 1024 * 1024:
logging.warning("ppc64 initrd %s is > 32MiB", outfile)
os.unlink(joinpaths(self.vars.inroot,"/proc/modules"))
示例12: create_runtime
def create_runtime(self, outfile="/var/tmp/squashfs.img", compression="xz", compressargs=[], size=2):
# make live rootfs image - must be named "LiveOS/rootfs.img" for dracut
workdir = joinpaths(os.path.dirname(outfile), "runtime-workdir")
if size:
fssize = size * (1024*1024*1024) # 2GB sparse file compresses down to nothin'
else:
fssize = None # Let mkext4img figure out the needed size
os.makedirs(joinpaths(workdir, "LiveOS"))
imgutils.mkext4img(self.vars.root, joinpaths(workdir, "LiveOS/rootfs.img"),
label="Anaconda", size=fssize)
# Reset selinux context on new rootfs
with imgutils.LoopDev( joinpaths(workdir, "LiveOS/rootfs.img") ) as loopdev:
with imgutils.Mount(loopdev) as mnt:
cmd = [ "setfiles", "-e", "/proc", "-e", "/sys", "-e", "/dev", "/etc/selinux/targeted/contexts/files/file_contexts", "/"]
runcmd(cmd, root=mnt)
# squash the live rootfs and clean up workdir
imgutils.mksquashfs(workdir, outfile, compression, compressargs)
remove(workdir)
示例13: systemctl
def systemctl(self, cmd, *units):
'''
systemctl [enable|disable|mask] UNIT [UNIT...]
Enable, disable, or mask the given systemd units.
Examples:
systemctl disable lvm2-monitor.service
systemctl mask fedora-storage-init.service fedora-configure.service
'''
if cmd not in ('enable', 'disable', 'mask'):
raise ValueError('unsupported systemctl cmd: %s' % cmd)
if not units:
logger.debug("systemctl: no units given for %s, ignoring", cmd)
return
self.mkdir("/run/systemd/system") # XXX workaround for systemctl bug
systemctl = ('systemctl', '--root', self.outroot, '--no-reload',
'--quiet', cmd)
# XXX for some reason 'systemctl enable/disable' always returns 1
try:
cmd = systemctl + units
runcmd(cmd)
except CalledProcessError:
pass
示例14: loop_waitfor
def loop_waitfor(loop_dev, outfile):
"""Make sure the loop device is attached to the outfile.
It seems that on rare occasions losetup can return before the /dev/loopX is
ready for use, causing problems with mkfs. This tries to make sure that the
loop device really is associated with the backing file before continuing.
Raise RuntimeError if it isn't setup after 5 tries.
"""
for _x in range(0,5):
runcmd(["udevadm", "settle", "--timeout", "300"])
## XXX Note that losetup --list output can be truncated to 64 bytes in some
## situations. Don't use it to lookup backing file, go the other way
## and lookup the loop for the backing file. See util-linux lib/loopdev.c
## loopcxt_get_backing_file()
if get_loop_name(outfile) == os.path.basename(loop_dev):
return
# If this really is a race, give it some time to settle down
time.sleep(1)
raise RuntimeError("Unable to setup %s on %s" % (loop_dev, outfile))
示例15: mkrootfsimg
def mkrootfsimg(rootdir, outfile, label, size=2, sysroot=""):
"""
Make rootfs image from a directory
:param str rootdir: Root directory
:param str outfile: Path of output image file
:param str label: Filesystem label
:param int size: Size of the image in GiB, if None computed automatically
:param str sysroot: path to system (deployment) root relative to physical root
"""
if size:
fssize = size * (1024*1024*1024) # 2GB sparse file compresses down to nothin'
else:
fssize = None # Let mkext4img figure out the needed size
mkext4img(rootdir, outfile, label=label, size=fssize)
# Reset selinux context on new rootfs
with LoopDev(outfile) as loopdev:
with Mount(loopdev) as mnt:
cmd = [ "setfiles", "-e", "/proc", "-e", "/sys", "-e", "/dev", "-e", "/install",
"/etc/selinux/targeted/contexts/files/file_contexts", "/"]
root = join(mnt, sysroot.lstrip("/"))
runcmd(cmd, root=root)