def _unconfigure(interface): """ Remove config file for specified interface """ filename = _get_config_name(interface) if os.path.exists(filename): utils.rmFile(filename)
def _cleanup(self): networks_caps = self.vdsm_proxy.netinfo.networks bonds_caps = self.vdsm_proxy.netinfo.bondings NETSETUP = { net: { 'remove': True } for net in self.setup_networks if net in networks_caps } BONDSETUP = { bond: { 'remove': True } for bond in self.setup_bonds if bond in bonds_caps } status, msg = self.vdsm_proxy.setupNetworks(NETSETUP, BONDSETUP, NOCHK) nics_used = [ attr['nic'] for attr in six.itervalues(self.setup_networks) if 'nic' in attr ] for attr in six.itervalues(self.setup_bonds): nics_used += attr['nics'] for nic in nics_used: utils.rmFile(IFCFG_PREFIX + nic) return status, msg
def normalize_device_filename(device): """ Attempts to detect a device ifcfg file and rename it to a vdsm supported format. In case of multiple ifcfg files that treat the same device, all except the first are deleted. """ device_files = [] paths = glob.iglob(NET_CONF_PREF + '*') for ifcfg_file in paths: with open(ifcfg_file) as f: for line in f: if line.startswith('#'): continue key, value = line.rstrip().split('=', 1) if value and value[0] == '\"' and value[-1] == '\"': value = value[1:-1] if key.upper() == 'DEVICE': if value == device: device_files.append(ifcfg_file) break if device_files: os.rename(device_files[0], NET_CONF_PREF + device) for filepath in device_files[1:]: utils.rmFile(filepath)
def _removeFile(filename): """Remove file (directly or using oVirt node's library)""" if utils.isOvirtNode(): node_fs.Config().delete(filename) # unpersists and shreds the file else: 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: subprocess.call([constants.EXT_UMOUNT, '-n', filename]) utils.rmFile(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 _unconfigure(interface): """ Remove config file for specified interface """ filename = _get_config_name(interface) if os.path.exists(filename): utils.unpersist(filename) utils.rmFile(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: utils.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 restoreAtomicBackup(self): logging.info("Rolling back configuration (restoring atomic backup)") for confFile, content in self._backups.iteritems(): if content is None: utils.rmFile(confFile) logging.debug("Removing empty configuration backup %s", confFile) else: open(confFile, "w").write(content) logging.info("Restored %s", confFile)
def testInit(self): filePath = os.path.join(self.tempdir, 'nets', NETWORK) try: with open(filePath, 'w') as networkFile: json.dump(NETWORK_ATTRIBUTES, networkFile) persistence = Config(self.tempdir) self.assertEqual(persistence.networks[NETWORK], NETWORK_ATTRIBUTES) finally: rmFile(filePath)
def _kill_and_rm_pid(pid, pid_file): try: os.kill(pid, signal.SIGTERM) except OSError as e: if e.errno == os.errno.ESRCH: # Already exited pass else: raise if pid_file is not None: rmFile(pid_file)
def restoreAtomicBackup(self): logging.info("Rolling back configuration (restoring atomic backup)") for confFile, content in self._backups.iteritems(): if content is None: utils.rmFile(confFile) logging.debug('Removing empty configuration backup %s', confFile) else: open(confFile, 'w').write(content) logging.info('Restored %s', confFile)
def testInit(self): filePath = os.path.join(self.tempdir, "nets", NETWORK) try: with open(filePath, "w") as networkFile: json.dump(NETWORK_ATTRIBUTES, networkFile) persistence = Config(self.tempdir) self.assertEqual(persistence.networks[NETWORK], NETWORK_ATTRIBUTES) finally: rmFile(filePath)
def _create(cls, dom, imgUUID, volUUID, size, volFormat, preallocate, volParent, srcImgUUID, srcVolUUID, volPath): """ Class specific implementation of volumeCreate. All the exceptions are properly handled and logged in volume.create() """ if preallocate == volume.SPARSE_VOL: volSize = "%s" % config.get("irs", "volume_utilization_chunk_mb") else: volSize = "%s" % ((size + SECTORS_TO_MB - 1) / SECTORS_TO_MB) lvm.createLV(dom.sdUUID, volUUID, volSize, activate=True, initialTag=TAG_VOL_UNINIT) utils.rmFile(volPath) os.symlink(lvm.lvPath(dom.sdUUID, volUUID), volPath) if not volParent: cls.log.info( "Request to create %s volume %s with size = %s " "sectors", volume.type2name(volFormat), volPath, size) if volFormat == volume.COW_FORMAT: qemuimg.create(volPath, size * BLOCK_SIZE, volume.fmt2str(volFormat)) else: # Create hardlink to template and its meta file cls.log.info("Request to create snapshot %s/%s of volume %s/%s", imgUUID, volUUID, srcImgUUID, srcVolUUID) volParent.clone(volPath, volFormat) with cls._tagCreateLock: mdSlot = dom.getVolumeMetadataSlot(volUUID, VOLUME_MDNUMBLKS) mdTags = [ "%s%s" % (TAG_PREFIX_MD, mdSlot), "%s%s" % (TAG_PREFIX_PARENT, srcVolUUID), "%s%s" % (TAG_PREFIX_IMAGE, imgUUID) ] lvm.changeLVTags(dom.sdUUID, volUUID, delTags=[TAG_VOL_UNINIT], addTags=mdTags) try: lvm.deactivateLVs(dom.sdUUID, volUUID) except se.CannotDeactivateLogicalVolume: cls.log.warn("Cannot deactivate new created volume %s/%s", dom.sdUUID, volUUID, exc_info=True) return (dom.sdUUID, mdSlot)
def _cleanOldFiles(self): for f in os.listdir(constants.P_VDSM_RUN): try: vmId, fileType = f.split(".", 1) exts = ["guest.socket", "monitor.socket", "stdio.dump", "recovery"] if fileType in exts and vmId not in self.vmContainer: self.log.debug("removing old file " + f) utils.rmFile(constants.P_VDSM_RUN + f) except: pass
def restoreAtomicBackup(self): logging.info("Rolling back configuration (restoring atomic backup)") for confFilePath, content in self._backups.iteritems(): if content is None: utils.rmFile(confFilePath) logging.debug('Removing empty configuration backup %s', confFilePath) else: with open(confFilePath, 'w') as confFile: confFile.write(content) logging.info('Restored %s', confFilePath)
def rmAppropriateSCSIDevice(device_name, udev_path): rule_file = _UDEV_RULE_FILE_NAME % ('scsi', device_name) _log.debug("Removing rule %s", rule_file) utils.rmFile(rule_file) _log.debug('Changing ownership (to root:disk) of device %s', udev_path) cmd = [EXT_CHOWN, 'root:disk', udev_path] rc, out, err = commands.execCmd(cmd) if err: raise OSError(errno.EINVAL, 'Could not change ownership' 'out %s\nerr %s' % (out, err))
def clean_vm_files(cif): for f in os.listdir(constants.P_VDSM_RUN): try: vmId, fileType = f.split(".", 1) except ValueError: # If file is missing type extention - ignore it pass else: if fileType == "recovery" and vmId not in cif.vmContainer: cif.log.debug("cleaning old file " + f) utils.rmFile(constants.P_VDSM_RUN + f)
def _cleanOldFiles(self): for f in os.listdir(constants.P_VDSM_RUN): try: vmId, fileType = f.split(".", 1) exts = [ "guest.socket", "monitor.socket", "stdio.dump", "recovery" ] if fileType in exts and vmId not in self.vmContainer: self.log.debug("removing old file " + f) utils.rmFile(constants.P_VDSM_RUN + f) except: pass
def rmAppropriateSCSIDevice(device_name, udev_path): rule_file = _UDEV_RULE_FILE_NAME % ('scsi', device_name) _log.debug("Removing rule %s", rule_file) utils.rmFile(rule_file) _log.debug('Changing ownership (to root:disk) of device %s', udev_path) cmd = [EXT_CHOWN, 'root:disk', udev_path] rc, out, err = commands.execCmd(cmd) if err: raise OSError( errno.EINVAL, 'Could not change ownership' 'out %s\nerr %s' % (out, err))
def _create(cls, dom, imgUUID, volUUID, size, volFormat, preallocate, volParent, srcImgUUID, srcVolUUID, imgPath, volPath): """ Class specific implementation of volumeCreate. All the exceptions are properly handled and logged in volume.create() """ if preallocate == volume.SPARSE_VOL: volSize = "%s" % config.get("irs", "volume_utilization_chunk_mb") else: volSize = "%s" % ((size + SECTORS_TO_MB - 1) / SECTORS_TO_MB) lvm.createLV(dom.sdUUID, volUUID, volSize, activate=True, initialTag=TAG_VOL_UNINIT) utils.rmFile(volPath) os.symlink(lvm.lvPath(dom.sdUUID, volUUID), volPath) if not volParent: cls.log.info("Request to create %s volume %s with size = %s " "sectors", volume.type2name(volFormat), volPath, size) if volFormat == volume.COW_FORMAT: volume.createVolume(None, None, volPath, size, volFormat, preallocate) else: # Create hardlink to template and its meta file cls.log.info("Request to create snapshot %s/%s of volume %s/%s", imgUUID, volUUID, srcImgUUID, srcVolUUID) volParent.clone(imgPath, volUUID, volFormat, preallocate) with cls._tagCreateLock: mdSlot = dom.mapMetaOffset(volUUID, VOLUME_MDNUMBLKS) mdTags = ["%s%s" % (TAG_PREFIX_MD, mdSlot), "%s%s" % (TAG_PREFIX_PARENT, srcVolUUID), "%s%s" % (TAG_PREFIX_IMAGE, imgUUID)] lvm.changeLVTags(dom.sdUUID, volUUID, delTags=[TAG_VOL_UNINIT], addTags=mdTags) try: lvm.deactivateLVs(dom.sdUUID, volUUID) except se.CannotDeactivateLogicalVolume: cls.log.warn("Cannot deactivate new created volume %s/%s", dom.sdUUID, volUUID, exc_info=True) return (dom.sdUUID, mdSlot)
def _cleanOldFiles(self): for f in os.listdir(constants.P_VDSM_RUN): try: vmId, fileType = f.split(".", 1) if fileType in ["guest.socket", "monitor.socket", "pid", "stdio.dump", "recovery"]: if vmId in self.vmContainer: continue if f == 'vdsmd.pid': continue if f == 'respawn.pid': continue if f == 'svdsm.pid': continue if f == 'svdsm.sock': continue else: continue self.log.debug("removing old file " + f) utils.rmFile(constants.P_VDSM_RUN + f) except: pass
def shutdown(self): try: pid = int(open(self.pidFile).readline().strip()) except IOError as e: if e.errno == os.errno.ENOENT: pass else: raise else: try: os.kill(pid, signal.SIGTERM) except OSError as e: if e.errno == os.errno.ESRCH: pass else: raise rmFile(self.pidFile)
def _create(cls, dom, imgUUID, volUUID, size, volFormat, preallocate, volParent, srcImgUUID, srcVolUUID, volPath, initialSize=None): """ Class specific implementation of volumeCreate. All the exceptions are properly handled and logged in volume.create() """ lvSize = cls.calculate_volume_alloc_size(preallocate, size, initialSize) lvm.createLV(dom.sdUUID, volUUID, "%s" % lvSize, activate=True, initialTags=(sc.TAG_VOL_UNINIT,)) utils.rmFile(volPath) os.symlink(lvm.lvPath(dom.sdUUID, volUUID), volPath) if not volParent: cls.log.info("Request to create %s volume %s with size = %s " "sectors", sc.type2name(volFormat), volPath, size) if volFormat == sc.COW_FORMAT: qemuimg.create(volPath, size=size * BLOCK_SIZE, format=sc.fmt2str(volFormat), qcow2Compat=dom.qcow2_compat()) else: # Create hardlink to template and its meta file cls.log.info("Request to create snapshot %s/%s of volume %s/%s", imgUUID, volUUID, srcImgUUID, srcVolUUID) volParent.clone(volPath, volFormat) with dom.acquireVolumeMetadataSlot( volUUID, sc.VOLUME_MDNUMBLKS) as slot: mdTags = ["%s%s" % (sc.TAG_PREFIX_MD, slot), "%s%s" % (sc.TAG_PREFIX_PARENT, srcVolUUID), "%s%s" % (sc.TAG_PREFIX_IMAGE, imgUUID)] lvm.changeLVTags(dom.sdUUID, volUUID, delTags=[sc.TAG_VOL_UNINIT], addTags=mdTags) try: lvm.deactivateLVs(dom.sdUUID, [volUUID]) except se.CannotDeactivateLogicalVolume: cls.log.warn("Cannot deactivate new created volume %s/%s", dom.sdUUID, volUUID, exc_info=True) return (dom.sdUUID, slot)
def _cleanup(self): networks_caps = self.vdsm_proxy.netinfo.networks bonds_caps = self.vdsm_proxy.netinfo.bondings NETSETUP = {net: {'remove': True} for net in self.setup_networks if net in networks_caps} BONDSETUP = {bond: {'remove': True} for bond in self.setup_bonds if bond in bonds_caps} status, msg = self.vdsm_proxy.setupNetworks(NETSETUP, BONDSETUP, NOCHK) nics_used = [attr['nic'] for attr in six.itervalues(self.setup_networks) if 'nic' in attr] for attr in six.itervalues(self.setup_bonds): nics_used += attr['nics'] for nic in nics_used: utils.rmFile(IFCFG_PREFIX + nic) return status, msg
def _create(cls, dom, imgUUID, volUUID, size, volFormat, preallocate, volParent, srcImgUUID, srcVolUUID, volPath, initialSize=None): """ Class specific implementation of volumeCreate. All the exceptions are properly handled and logged in volume.create() """ lvSize = cls.calculate_volume_alloc_size(preallocate, size, initialSize) lvm.createLV(dom.sdUUID, volUUID, "%s" % lvSize, activate=True, initialTags=(sc.TAG_VOL_UNINIT,)) utils.rmFile(volPath) os.symlink(lvm.lvPath(dom.sdUUID, volUUID), volPath) if not volParent: cls.log.info("Request to create %s volume %s with size = %s " "sectors", sc.type2name(volFormat), volPath, size) if volFormat == sc.COW_FORMAT: qemuimg.create( volPath, size * BLOCK_SIZE, sc.fmt2str(volFormat)) else: # Create hardlink to template and its meta file cls.log.info("Request to create snapshot %s/%s of volume %s/%s", imgUUID, volUUID, srcImgUUID, srcVolUUID) volParent.clone(volPath, volFormat) with dom.acquireVolumeMetadataSlot( volUUID, sc.VOLUME_MDNUMBLKS) as slot: mdTags = ["%s%s" % (sc.TAG_PREFIX_MD, slot), "%s%s" % (sc.TAG_PREFIX_PARENT, srcVolUUID), "%s%s" % (sc.TAG_PREFIX_IMAGE, imgUUID)] lvm.changeLVTags(dom.sdUUID, volUUID, delTags=[sc.TAG_VOL_UNINIT], addTags=mdTags) try: lvm.deactivateLVs(dom.sdUUID, [volUUID]) except se.CannotDeactivateLogicalVolume: cls.log.warn("Cannot deactivate new created volume %s/%s", dom.sdUUID, volUUID, exc_info=True) return (dom.sdUUID, slot)
def mkIsoFs(vmId, files, volumeName=None): dirname = isopath = None try: dirname = tempfile.mkdtemp() _decodeFilesIntoDir(files, dirname) isopath = _getFileName(vmId, files) command = [EXT_MKISOFS, '-R', '-J', '-o', isopath] if volumeName is not None: command.extend(['-V', volumeName]) command.extend([dirname]) mode = 0o640 # pre-create the destination iso path with the right permissions; # mkisofs/genisoimage will truncate the content and keep the # permissions. if os.path.exists(isopath): logging.warning("iso file %r exists, removing", isopath) rmFile(isopath) fd = os.open(isopath, os.O_CREAT | os.O_RDONLY | os.O_EXCL, mode) os.close(fd) rc, out, err = execCmd(command, raw=True) if rc: # clean up after ourselves in case of error removeFs(isopath) # skip _commonCleanFs step for missing iso isopath = None raise OSError( errno.EIO, "could not create iso file: " "code %s, out %s\nerr %s" % (rc, out, err)) _check_attributes(isopath, mode) finally: _commonCleanFs(dirname, isopath) return isopath
def mkIsoFs(vmId, files, volumeName=None): dirname = isopath = None try: dirname = tempfile.mkdtemp() _decodeFilesIntoDir(files, dirname) isopath = _getFileName(vmId, files) command = [EXT_MKISOFS, '-R', '-J', '-o', isopath] if volumeName is not None: command.extend(['-V', volumeName]) command.extend([dirname]) mode = 0o640 # pre-create the destination iso path with the right permissions; # mkisofs/genisoimage will truncate the content and keep the # permissions. if os.path.exists(isopath): logging.warning("iso file %r exists, removing", isopath) rmFile(isopath) fd = os.open(isopath, os.O_CREAT | os.O_RDONLY | os.O_EXCL, mode) os.close(fd) rc, out, err = execCmd(command, raw=True) if rc: # clean up after ourselves in case of error removeFs(isopath) # skip _commonCleanFs step for missing iso isopath = None raise OSError(errno.EIO, "could not create iso file: " "code %s, out %s\nerr %s" % (rc, out, err)) _check_attributes(isopath, mode) finally: _commonCleanFs(dirname, isopath) return isopath
def wrapper(*args, **kwargs): directory_existed = False if not functional: old_vdsm_hooks = constants.P_VDSM_HOOKS constants.P_VDSM_HOOKS = tempfile.mkdtemp() hook_path = constants.P_VDSM_HOOKS + '/' + hook_dir try: os.mkdir(hook_path) except OSError as mkdir_error: if mkdir_error.errno == errno.EEXIST: directory_existed = True else: raise cookie_file = _createHookScript(hook_path, hook_name, hook_script) output = None try: kwargs['hook_cookiefile'] = cookie_file output = test_function(*args, **kwargs) finally: if directory_existed: utils.rmFile(hook_path + '/' + hook_name) else: utils.rmTree(hook_path) utils.rmFile(cookie_file) if not functional: constants.P_VDSM_HOOKS = old_vdsm_hooks return output
def _cleanOldFiles(self): for f in os.listdir(constants.P_VDSM_RUN): try: vmId, fileType = f.split(".", 1) if fileType in [ "guest.socket", "monitor.socket", "pid", "stdio.dump", "recovery" ]: if vmId in self.vmContainer: continue if f == 'vdsmd.pid': continue if f == 'respawn.pid': continue if f == 'supervdsmd.pid': continue if f == 'supervdsm_respawn.pid': continue else: continue self.log.debug("removing old file " + f) utils.rmFile(constants.P_VDSM_RUN + f) except: pass
def _cleanup(self): with self._volPrepareLock: for drive in self._devices[DISK_DEVICES]: try: self.cif.teardownVolumePath(drive) except: self.log.error("Drive teardown failure for %s", drive, exc_info=True) if self.conf.get('volatileFloppy'): try: self.log.debug("Floppy %s cleanup" % self.conf['floppy']) utils.rmFile(self.conf['floppy']) except: pass try: self.guestAgent.stop() except: pass utils.rmFile(self._guestSocektFile) utils.rmFile(self._recoveryFile)
def shareVolumeRollback(cls, taskObj, volPath): cls.log.info("Volume rollback for volPath=%s", volPath) utils.rmFile(volPath)
def cleanup_guest_socket(sock): if os.path.islink(sock): rmFile(os.path.realpath(sock)) rmFile(sock)
def cleanup(self): with self._lock: utils.rmFile(self._path) self._path = None
def _removeFile(filename): utils.rmFile(filename) logging.debug("Removed file %s", filename)
def delete_dhclient_leases(iface, dhcpv4=False, dhcpv6=False): if dhcpv4: rmFile(DHCLIENT_LEASE.format('', iface)) if dhcpv6: rmFile(DHCLIENT_LEASE.format('6', iface))
def delete_dhclient_leases(iface, dhcpv4=False, dhcpv6=False, el6=False): lease_file = DHCLIENT_LEASE_EL6 if el6 else DHCLIENT_LEASE if dhcpv4: rmFile(lease_file.format('', iface)) if dhcpv6: rmFile(lease_file.format('6', iface))
def _removeConfig(path): utils.rmFile(path)
def _normalize_device_filenames(device, device_files): if device_files: os.rename(device_files[0], NET_CONF_PREF + device) for filepath in device_files[1:]: utils.rmFile(filepath)
def removeInterfaceTracking(device): rmFile(DynamicSourceRoute.getTrackingFilePath(device))
def main(): def bind(func): def wrapper(_SuperVdsm, *args, **kwargs): return func(*args, **kwargs) return wrapper for name, func in listPublicFunctions(): setattr(_SuperVdsm, name, logDecorator(bind(func))) try: logging.config.fileConfig(LOG_CONF_PATH) except: logging.basicConfig(filename='/dev/stdout', filemode='w+', level=logging.DEBUG) log = logging.getLogger("SuperVdsm.Server") log.warn("Could not init proper logging", exc_info=True) log = logging.getLogger("SuperVdsm.Server") try: log.debug("Making sure I'm root - SuperVdsm") if os.geteuid() != 0: sys.exit(errno.EPERM) pidfile = P_VDSM_RUN + 'supervdsmd.pid' pid = str(os.getpid()) with open(pidfile, 'w') as f: f.write(pid + "\n") log.debug("Parsing cmd args") address = sys.argv[1] log.debug("Cleaning old socket %s", address) if os.path.exists(address): os.unlink(address) log.debug("Setting up keep alive thread") try: log.debug("Creating remote object manager") manager = _SuperVdsmManager(address=address, authkey='') manager.register('instance', callable=_SuperVdsm) server = manager.get_server() servThread = threading.Thread(target=server.serve_forever) servThread.setDaemon(True) servThread.start() chown(address, getpwnam(VDSM_USER).pw_uid, METADATA_GROUP) log.debug("Started serving super vdsm object") threading.Thread(target=sourceRouteThread.subscribeToInotifyLoop(), name='sourceRoute').start() # Python bug of thread.join() will block signal # http://bugs.python.org/issue1167930 while servThread.isAlive(): servThread.join(5) finally: if os.path.exists(address): utils.rmFile(address) except Exception: log.error("Could not start Super Vdsm", exc_info=True) sys.exit(1)
def clear(self): self._log.debug('clearing XML for container %s', self._name) rmFile(self.path)