def removeBridge(self, bridge): ifdown(bridge.name) self._removeSourceRoute(bridge) execCmd([constants.EXT_BRCTL, 'delbr', bridge.name]) self.configApplier.removeBridge(bridge.name) if bridge.port: bridge.port.remove()
def _killSupervdsm(self): try: with open(PIDFILE, "r") as f: pid = int(f.read().strip()) misc.execCmd([constants.EXT_KILL, "-9", str(pid)]) except Exception, ex: self._log.debug("Could not kill old Super Vdsm %s", ex)
def _launchSupervdsm(self): self._authkey = str(uuid.uuid4()) self._log.debug("Launching Super Vdsm") superVdsmCmd = [constants.EXT_PYTHON, SUPERVDSM, self._authkey, str(os.getpid())] misc.execCmd(superVdsmCmd, sync=False) sleep(2)
def _removeFile(filename): """Remove file, umounting ovirt config files if needed.""" mounts = open('/proc/mounts').read() if ' /config ext3' in mounts and ' %s ext3' % filename in mounts: execCmd([constants.EXT_UMOUNT, '-n', filename]) utils.rmFile(filename) logging.debug("Removed file %s", filename)
def _removeFile(filename): """Remove file, umounting ovirt config files if needed.""" mounts = open("/proc/mounts").read() if " /config ext3" in mounts and " %s ext3" % filename in mounts: execCmd([constants.EXT_UMOUNT, "-n", filename]) utils.rmFile(filename) logging.debug("Removed file %s", filename)
def removeBridge(self, bridge): DynamicSourceRoute.addInterfaceTracking(bridge) ifdown(bridge.name) self._removeSourceRoute(bridge) execCmd([constants.EXT_BRCTL, "delbr", bridge.name]) self.configApplier.removeBridge(bridge.name) if bridge.port: bridge.port.remove()
def _persistentBackup(cls, filename): """ Persistently backup ifcfg-* config files """ if os.path.exists("/usr/libexec/ovirt-functions"): execCmd([constants.EXT_SH, "/usr/libexec/ovirt-functions", "unmount_config", filename]) logging.debug("unmounted %s using ovirt", filename) (dummy, basename) = os.path.split(filename) if os.path.exists(filename): content = open(filename).read() else: # For non-exists ifcfg-* file use predefined header content = cls.DELETED_HEADER + "\n" logging.debug("backing up %s: %s", basename, content) cls.writeBackupFile(netinfo.NET_CONF_BACK_DIR, basename, content)
def _genInitramfs(): logging.warning('Generating a temporary initramfs image') fd, path = tempfile.mkstemp() cmd = [_mkinitrd.cmd, "-f", path, _kernelVer] rc, out, err = execCmd(cmd) os.chmod(path, 0o644) return path
def runScanArgs(*args): cmd = [_virtAlignmentScan.cmd] cmd.extend(args) # TODO: remove the environment variable when the issue in # virt-alignment-scan/libvirt is resolved # http://bugzilla.redhat.com/1151838 return execCmd(cmd, env={'LIBGUESTFS_BACKEND': 'direct'})
def testExec(self): """ Tests that execCmd execs and returns the correct ret code """ ret, out, err = misc.execCmd([EXT_ECHO], sudo=False) self.assertEquals(ret, 0)
def writeLargeData(self): data = """The Doctor: Davros, if you had created a virus in your laboratory, something contagious and infectious that killed on contact, a virus that would destroy all other forms of life; would you allow its use? Davros: It is an interesting conjecture. The Doctor: Would you do it? Davros: The only living thing... The microscopic organism... reigning supreme... A fascinating idea. The Doctor: But would you do it? Davros: Yes; yes. To hold in my hand, a capsule that contained such power. To know that life and death on such a scale was my choice. To know that the tiny pressure on my thumb, enough to break the glass, would end everything. Yes! I would do it! That power would set me up above the gods! And through the Daleks, I shall have that power! """ # (C) BBC - Doctor Who data = data * ((4096 / len(data)) * 2) self.assertTrue(data > 4096) p = misc.execCmd([EXT_CAT], sync=False) self.log.info("Writing data to std out") p.stdin.write(data) p.stdin.flush() self.log.info("Written data reading") self.assertEquals(p.stdout.read(len(data)), data)
def udevTrigger(self, guid): self.__udevReloadRules(guid) cmd = [EXT_UDEVADM, 'trigger', '--verbose', '--action', 'change', '--property-match=DM_NAME=%s' % guid] rc, out, err = misc.execCmd(cmd, sudo=False) if rc: raise OSError(errno.EINVAL, "Could not trigger change for device \ %s, out %s\nerr %s" % (guid, out, err))
def __udevVersion(self): cmd = [EXT_UDEVADM, '--version'] rc, out, err = misc.execCmd(cmd, sudo=False) if rc: self.log.error("Udevadm version command failed rc=%s, " " out=\"%s\", err=\"%s\"", rc, out, err) raise RuntimeError("Could not get udev version number") return int(out[0])
def test(self): args = [EXT_SLEEP, "4"] sproc = misc.execCmd(args, sync=False, sudo=False) try: self.assertEquals(misc.getCmdArgs(sproc.pid), tuple(args)) finally: sproc.kill() sproc.wait()
def _ifup(netIf): rc, out, err = execCmd([constants.EXT_IFUP, netIf], raw=False) if rc != 0: # In /etc/sysconfig/network-scripts/ifup* the last line usually # contains the error reason. raise ConfigNetworkError(ne.ERR_FAILED_IFUP, out[-1] if out else "") return rc, out, err
def _ifup(netIf): rc, out, err = execCmd([constants.EXT_IFUP, netIf], raw=False) if rc != 0: # In /etc/sysconfig/network-scripts/ifup* the last line usually # contains the error reason. raise ConfigNetworkError(ne.ERR_FAILED_IFUP, out[-1] if out else '') return rc, out, err
def testWaitCond(self): ttl = 2 p = misc.execCmd([EXT_SLEEP, str(ttl + 10)], sudo=False, sync=False) startTime = time.time() p.wait(cond=lambda: time.time() - startTime > ttl) duration = time.time() - startTime self.assertTrue(duration < (ttl + 2)) self.assertTrue(duration > (ttl)) p.kill()
def testSudo(self): """ Tests that when running with sudo the user really is root (or other desired user). """ cmd = [EXT_WHOAMI] checkSudo(cmd) ret, stdout, stderr = misc.execCmd(cmd, sudo=True) self.assertEquals(stdout[0], SUDO_USER)
def testZombie(self): args = [EXT_SLEEP, "0"] sproc = misc.execCmd(args, sync=False, sudo=False) sproc.kill() try: test = lambda: self.assertEquals(misc.getCmdArgs(sproc.pid), tuple()) utils.retry(AssertionError, test, tries=10, sleep=0.1) finally: sproc.wait()
def testStdOut(self): """ Tests that execCmd correctly returns the standard output of the prog it executes. """ line = "All I wanted was to have some pizza, hang out with dad, " + \ "and not let your weirdness mess up my day" # (C) Nickolodeon - Invader Zim ret, stdout, stderr = misc.execCmd((EXT_ECHO, line), sudo=False) self.assertEquals(stdout[0], line)
def test(self): args = ["sleep", "3"] sproc = misc.execCmd(args, sync=False, sudo=False) stats = utils.pidStat(sproc.pid) pid = int(stats.pid) # procName comes in the format of (procname) name = stats.comm self.assertEquals(pid, sproc.pid) self.assertEquals(name, args[0]) sproc.kill() sproc.wait()
def __init__(self, vdsmServer, asserts): # check if the system supports configuring iSCSI target if not "rtslib" in globals().keys(): raise SkipTest("python-rtslib is not installed.") cmd = [_modprobe.cmd, "iscsi_target_mod"] rc, out, err = execCmd(cmd, sudo=True) asserts.assertEquals(rc, 0) super(IscsiServer, self).__init__(vdsmServer, asserts) self.address = '127.0.0.1'
def testValidInputFalse(self): """ Test that is work when given valid but incorrect input. """ count = 802 with tempfile.NamedTemporaryFile() as f: cmd = [EXT_DD, "bs=1", "if=/dev/urandom", 'of=%s' % f.name, 'count=%d' % count] rc, out, err = misc.execCmd(cmd, sudo=False) self.assertFalse(misc.validateDDBytes(err, count + 1))
def testNice(self): cmd = ["sleep", "10"] proc = misc.execCmd(cmd, sudo=False, nice=10, sync=False) def test(): nice = utils.pidStat(proc.pid).nice self.assertEquals(nice, 10) utils.retry(AssertionError, test, tries=10, sleep=0.1) proc.kill() proc.wait()
def test(self): data = """Striker: You are a Time Lord, a lord of time. Are there lords in such a small domain? The Doctor: And where do you function? Striker: Eternity. The endless wastes of eternity. """ # (C) BBC - Doctor Who p = misc.execCmd([EXT_CAT], sync=False) self.log.info("Writing data to std out") p.stdin.write(data) p.stdin.flush() self.log.info("Written data reading") self.assertEquals(p.stdout.read(len(data)), data)
def testStdErr(self): """ Tests that execCmd correctly returns the standard error of the prog it executes. """ line = "Hey Scully, is this display of boyish agility " + \ "turning you on at all?" # (C) Fox - The X Files code = "import sys; sys.stderr.write('%s')" % line ret, stdout, stderr = misc.execCmd([EXT_PYTHON, "-c", code], sudo=False) self.assertEquals(stderr[0], line)
def __udevReloadRules(self, guid): if self.__udevOperationReload(): reload = "--reload" else: reload = "--reload-rules" cmd = [EXT_UDEVADM, 'control', reload] rc, out, err = misc.execCmd(cmd, sudo=False) if rc: self.log.error("Udevadm reload-rules command failed rc=%s, " "out=\"%s\", err=\"%s\"", rc, out, err) raise OSError(errno.EINVAL, "Could not reload-rules for device " "%s" % guid)
def createFloppyImage(size): fd, path = mkstemp() with os.fdopen(fd, "w") as f: f.seek(size) f.write('\0') try: rc, out, err = execCmd(['/sbin/mkfs.ext2', "-F", path]) except OSError: try: rc, out, err = execCmd(['/usr/sbin/mkfs.ext2', "-F", path]) except OSError as e: if e.errno == errno.ENOENT: raise SkipTest("cannot execute mkfs.ext2") raise if rc != 0: raise Exception("Could not format image", out, err) try: yield path finally: os.unlink(path)
def test(self): sleepProcs = [] for i in range(3): sleepProcs.append(misc.execCmd([EXT_SLEEP, "3"], sync=False, sudo=False)) pids = misc.pgrep("sleep") for proc in sleepProcs: self.assertTrue(proc.pid in pids, "pid %d was not located by pgrep" % proc.pid) for proc in sleepProcs: proc.kill() proc.wait()
def testMutiWrite(self): data = """The Doctor: Androzani Major was becoming quite developed last time I passed this way. Peri: When was that? The Doctor: ...I don't remember. I'm pretty sure it wasn't the future. """ # (C) BBC - Doctor Who halfPoint = len(data) / 2 p = misc.execCmd([EXT_CAT], sync=False) self.log.info("Writing data to std out") p.stdin.write(data[:halfPoint]) self.log.info("Writing more data to std out") p.stdin.write(data[halfPoint:]) p.stdin.flush() self.log.info("Written data reading") self.assertEquals(p.stdout.read(len(data)), data)
def __init__(self, vdsmServer, asserts): # check if the system supports configuring iSCSI target if "rtslib" not in globals().keys(): raise SkipTest("python-rtslib is not installed.") cmd = [_modprobe.cmd, "iscsi_target_mod"] rc, out, err = execCmd(cmd, sudo=True) asserts.assertEquals(rc, 0) # mount the configfs for rtslib if it is not mounted m = Mount('configfs', '/sys/kernel/config') if not m.isMounted(): m.mount(mntOpts='rw', vfstype='configfs') super(IscsiServer, self).__init__(vdsmServer, asserts) self.address = '127.0.0.1'
def testSymlinkMount(self): checkSudo(["mount", "-o", "loop", "somefile", "target"]) checkSudo(["umount", "target"]) with namedTemporaryDir() as root_dir: backing_image = os.path.join(root_dir, 'backing.img') link_to_image = os.path.join(root_dir, 'link_to_image') mountpoint = os.path.join(root_dir, 'mountpoint') with open(backing_image, 'w') as f: os.ftruncate(f.fileno(), 1024**3) rc, out, err = execCmd(['/sbin/mkfs.ext2', "-F", backing_image], raw=True) if rc != 0: raise RuntimeError("Error creating filesystem: %s" % err) os.symlink(backing_image, link_to_image) os.mkdir(mountpoint) m = mount.Mount(link_to_image, mountpoint) m.mount(mntOpts="loop") try: self.assertTrue(m.isMounted()) finally: m.umount()
def __init__(self, vdsmServer, asserts): # check if the system supports configuring iSCSI target if not "rtslib" in globals().keys(): raise SkipTest("python-rtslib is not installed.") cmd = [_modprobe.cmd, "iscsi_target_mod"] rc, out, err = execCmd(cmd, sudo=True) asserts.assertEquals(rc, 0) # mount the configfs for rtslib if it is not mounted mountInfo = [] with open('/etc/mtab') as mtab: mountInfo = map(lambda line: line.strip(" \t\n").split(' '), mtab) if all([ info[0] != 'configfs' or info[1] != '/sys/kernel/config' for info in mountInfo ]): m = Mount('configfs', '/sys/kernel/config') m.mount(mntOpts='rw', vfstype='configfs') super(IscsiServer, self).__init__(vdsmServer, asserts) self.address = '127.0.0.1'
def runScanArgs(*args): cmd = [_virtAlignmentScan.cmd] cmd.extend(args) return execCmd(cmd)
def mkimage(imagepath, aligned=True): open(imagepath, "wb").truncate(4 * 1024**3) cmd = ["/sbin/sfdisk", "-uS", "--force", imagepath] cmd_input = "128,,\n" if aligned else "1,,\n" rc, out, err = execCmd(cmd, data=cmd_input) assert rc == 0
def ifdown(iface): "Bring down an interface" rc, out, err = execCmd([constants.EXT_IFDOWN, iface], raw=True) return rc
def setSafeNetworkConfig(): """Declare current network configuration as 'safe'""" execCmd([constants.EXT_VDSM_STORE_NET_CONFIG])
def genInitramfs(kernelVer): fd, path = tempfile.mkstemp() cmd = [_mkinitrd.cmd, "-f", path, kernelVer] rc, out, err = execCmd(cmd, sudo=False) os.chmod(path, 0644) return path
def listNFS(): rc, out, err = execCmd([_exportfs.cmd]) if rc != 0: raise RuntimeError("Can not list NFS export: %s\n" % err) return out
def unexportNFS(path): rc, out, err = execCmd([_exportfs.cmd, '-u', '127.0.0.1:%s' % path]) return rc
def exportNFS(path): rc, out, err = execCmd( [_exportfs.cmd, '-o', 'rw,insecure,sync', '127.0.0.1:%s' % path]) return rc
def execCmd(*args, **kwargs): # import only after config as been initialized from storage.misc import execCmd return execCmd(*args, **kwargs)
def readableBy(filePath, user): rc, out, err = execCmd([EXT_SUDO, '-u', user, 'head', '-c', '0', filePath]) return rc == 0