def enable_puppet(self): cfg = Puppet().retrieve() conf = File("/etc/puppet/puppet.conf") conf_builder = "" for line in conf: try: item = re.match(r'^#?\s+(\w+) =', line).group(1) if item in cfg and cfg[item] is not '': if re.match(r'^#.*', line): line = re.sub(r'^#', '', line) conf_builder += re.sub(r'(^.*?' + item + ' =).*', r'\1 "' + cfg[item] + '"', line) else: conf_builder += line except: conf_builder += line conf.write(conf_builder, "w") fs.Config().persist("/etc/puppet/puppet.conf") try: system.service("puppet", "stop") utils.process.pipe("puppet agent --waitforcert 60 " "--test", shell=True, check=True) system.service("puppet", "start") fs.Config().persist("/var/lib/puppet") except: self.logger.debug("Couldn't start puppet agent", exc_info=True) raise RuntimeError("Synchronization with the puppet master timed " "out.\nCheck whether a certificate is waiting " "for signing on the master or a certificate " "for this hostname already exists and needs to" " be revoked.")
def find_grub_cfg(): cfg_path = None if is_efi(): mount_efi(target="/liveos") cfg_path = "/liveos/EFI/redhat/grub.cfg" elif os.path.ismount("/dev/.initramfs/live"): if Bootloader.is_grub2(): cfg_path = "/dev/.initramfs/live/grub2/grub.cfg" else: cfg_path = "/dev/.initramfs/live/grub/grub.conf" elif os.path.ismount("/run/.initramfs/live"): cfg_path = "/liveos/grub/grub.conf" elif Filesystem.by_label("Boot"): cfg_path = "/boot/grub/grub.conf" else: raise RuntimeError("Failed to find the path for grub.[cfg|conf]") cfg = File(cfg_path) if not cfg.exists(): raise RuntimeError("Grub config file does not exist: %s" % cfg.filename) return cfg
def enable_puppet(self): cfg = Puppet().retrieve() conf = File("/etc/puppet/puppet.conf") conf_builder = "" for line in conf: try: item = re.match(r'^#?\s+(\w+) =', line).group(1) if item in cfg and cfg[item] is not '': if re.match(r'^#.*', line): line = re.sub(r'^#', '', line) conf_builder += re.sub(r'(^.*?' + item + ' =).*', r'\1 "' + cfg[item] + '"', line) else: conf_builder += line except: conf_builder += line conf.write(conf_builder, "w") fs.Config().persist("/etc/puppet/puppet.conf") system.service("puppet", "stop") utils.process.check_call("puppet agent --waitforcert 60 --test", shell=True) system.service("puppet", "start") fs.Config().persist("/var/lib/puppet")
def commit(self): self.logger.info("Connecting to Puppet server") cfg = Puppet().retrieve() conf = File("/etc/puppet/puppet.conf") conf_builder = "" for line in conf: try: item = re.match(r'^#?\s+(\w+) =', line).group(1) if item in cfg and cfg[item] is not '': if re.match(r'^#.*', line): line = re.sub(r'^#', '', line) conf_builder += re.sub(r'(^.*?' + item + ' =).*', r'\1 "' + cfg[item] + '"', line) else: conf_builder += line except: conf_builder += line conf.write(conf_builder, "w") fs.Config().persist("/etc/puppet/puppet.conf") system.service("puppet", "stop") utils.process.check_call("puppet agent --waitforcert 60 --test", shell=True) system.service("puppet", "start")
def mode(self, ifname, text_only=True): """Return the mode used for this bond Args: text_only: If only the textual mode representation shall be returned """ mode = File(self.bond_mode_path % ifname).read() if text_only: mode = mode.split()[0] return mode
def rng_status(self): rng_bytes = None disable_aes_ni = False status = namedtuple("rngstatus", ["rng_bytes", "disable_aes_ni"]) f = File("/etc/profile") if f.findall(r"SSH_USE_STRONG_RNG=\d+"): rng_bytes = f.findall(r"SSH_USE_STRONG_RNG=\d+")[0].split("=")[1] if f.findall(r"DISABLE_AES_NI="): disable_aes_ni = True rng_status = status(rng_bytes, disable_aes_ni) return rng_status
def rng_status(self): rng_bytes = None disable_aes_ni = False status = namedtuple("rngstatus", ["rng_bytes", "disable_aes_ni"]) f = File("/etc/profile") if f.findall(r'SSH_USE_STRONG_RNG=\d+'): rng_bytes = f.findall(r'SSH_USE_STRONG_RNG=\d+')[0].split('=')[1] if f.findall(r'DISABLE_AES_NI='): disable_aes_ni = True rng_status = status(rng_bytes, disable_aes_ni) return rng_status
def __get_domain(self): domain = None nfs_config = File(self.configfilename) for line in nfs_config: if "Domain =" in line: domain = line.replace("Domain =", "").strip() return domain
def has_link(self): """Determin if L1 is up on a given interface >>> NIC("lo").has_link() True Args: ifname: The interface to be checked Returns: True if L1 (the-link-is-up) is detected (depends on driver support) """ if not self.exists(): raise UnknownNicError("Unknown network interface: '%s'" % self.ifname) if is_nm_managed(self.ifname): try: device = _nm_client.get_device_by_iface(self.ifname) if device: return device.get_carrier() except: LOGGER.debug("Failed to retrieve carrier with NM") # Fallback has_carrier = False try: content = File("/sys/class/net/%s/carrier" % self.ifname).read() has_carrier = "1" in content except: LOGGER.debug("Carrier down for %s" % self.ifname) return has_carrier
def disable_puppet(self): item_args = ["server", "certname"] conf = File("/etc/puppet/puppet.conf") conf_builder = "" for line in conf: for item in item_args: line = re.sub(r'(^.*?' + item + ' =).*', r'#\1 "' '"', line) if item in line else line conf_builder += line conf.write(conf_builder, "w") fs.Config().persist("/etc/puppet/puppet.conf") system.service("puppet", "stop") Puppet().clear()
def __init__(self, dry=False, path=None): if not dry: if not path: self.__handle = Bootloader.find_grub_cfg() else: self.__handle = File(path) self.__mount = Mount.find_by_path(self.__handle.filename) self.items = self.__get_arguments()
def slaves(self, ifname): """Find all slaves of the bond master ifname """ path = self.bond_slaves_path % ifname slaves = [] if self.is_bond(ifname): slaves = File(path).read().split() return slaves
def disable_puppet(self): item_args = ["server", "certname"] conf = File("/etc/puppet/puppet.conf") conf_builder = "" for line in conf: for item in item_args: line = re.sub(r'(^.*?' + item + ' =).*', r'#\1 "''"', line) if item in line else line conf_builder += line conf.write(conf_builder, "w") fs.Config().persist("/etc/puppet/puppet.conf") system.service("puppet", "stop") Puppet().clear()
def commit(self): # Copy the initial net rules to a file that get's not # overwritten at each boot, rhbz#773495 rulesfile = "/etc/udev/rules.d/70-persistent-net.rules" newrulesfile = "/etc/udev/rules.d/71-persistent-node-net.rules" if File(rulesfile).exists(): process.check_call("cp %s %s" % (rulesfile, newrulesfile)) fs.Config().persist(newrulesfile)
def _read_attr_config(self, config_file, attr): """ Read Attribute value from a config file config_file -- A .conf file attr -- The attribute for reading the value assigned Returns The value for attribute or None (No attribute found) """ value = None f = File(config_file) if attr in f.read(): value = [line.strip().split("=")[1] for line in f if attr in line][0] return value
def get_hostkey(self, variant="rsa"): fn_hostkey = "/etc/ssh/ssh_host_%s_key.pub" % variant if not os.path.exists(fn_hostkey): raise Exception("SSH hostkey does not yet exist.") hostkey = File(fn_hostkey).read() hostkey_fp_cmd = "ssh-keygen -l -f '%s'" % fn_hostkey fingerprint = process.pipe(hostkey_fp_cmd).strip().split(" ")[1] return (fingerprint, hostkey)
def commit(self): self.logger.info("Connecting to Puppet server") cfg = Puppet().retrieve() lines = File("/etc/puppet/puppet.conf").read() conf = File("/etc/puppet/puppet.conf", "w") for line in lines: try: item = re.match(r'^\s+(\w+) =', line).group(1) if item in cfg: conf.write(re.sub(r'(^.*?' + item + ' =).*', r'\1 "' + cfg[item] + '"', line)) except: conf.write(line) system.service("puppet", "stop") utils.process.check_call("puppet agent --test") system.service("puppet", "start")
def which(cmd): """Simulates the behavior of which Args: cmd: The cmd to be found in PATH Returns: The cmd with the absolute path if it was found in any path given in $PATH. Otherwise None (if not found in any path in $PATHS). """ ret = None if os.path.isabs(cmd): if File(cmd).exists(): ret = cmd else: for dirname in os.environ["PATH"].split(":"): fn = os.path.join(dirname, cmd) if File(fn).exists() and File(fn).access(os.X_OK): ret = fn break return ret
def commit(self): from ovirtnode.storage import storage_auto if storage_auto(): # store /etc/shadow if adminpw/rootpw are set, # handled already in ovirt-early args = File("/proc/cmdline").read() if "adminpw" in args or "rootpw" in args: print "Storing /etc/shadow" Config().persist("/etc/passwd") Config().persist("/etc/shadow") else: raise RuntimeError("Automatic installation failed. " + "Please review /var/log/ovirt.log")
def __set_domain(self, domain): cfg = File(self.configfilename) if domain: # Uncomment Domain line and set new domain cfg.sub(r"^[#]?Domain =.*", "Domain = %s" % domain) else: # Comment out Domain line cfg.sub(r"^[#]?(Domain =.*)", r"#\1")
def find_grub_cfg(): cfg_path = None if Filesystem.by_label("Boot"): cfg_path = "/boot/grub/grub.conf" elif os.path.ismount("/dev/.initramfs/live"): if not Bootloader.is_grub2(): cfg_path = "/dev/.initramfs/live/grub/grub.conf" else: cfg_path = "/dev/.initramfs/live/grub2/grub.cfg" elif os.path.ismount("/run/initramfs/.live"): cfg_path = "/liveos/grub/grub.conf" else: raise RuntimeError("Failed to find the path for grub.[cfg|conf]") return File(cfg_path)
def has_link(self): """Determin if L1 is up on a given interface >>> NIC("lo").has_link() True Args: ifname: The interface to be checked Returns: True if L1 (the-link-is-up) is detected (depends on driver support) """ if not self.exists(): raise UnknownNicError("Unknown network interface: '%s'" % self.ifname) if is_nm_managed(self.ifname): try: device = _nm_client.get_device_by_iface(self.ifname) if device: return device.get_carrier() except: LOGGER.debug("Failed to retrieve carrier with NM") # Fallback has_carrier = False i = 5 while i > 0: try: cmd = "ip link set dev {ifname} up".format(ifname=self.ifname) process.check_call(cmd, shell=True) except process.CalledProcessError: LOGGER.debug("Failed to set dev %s link up" % self.ifname) try: content = File("/sys/class/net/%s/carrier" % self.ifname).\ read() has_carrier = "1" in content except: LOGGER.debug("Carrier down for %s" % self.ifname) if not has_carrier: import time time.sleep(1) i -= 1 else: break return has_carrier
def cpu_details(): """Return details for the CPU of this machine """ fields = [ "Model name", "Architecture", "CPU MHz", "Virtualization", "CPU(s)", "Socket(s)", "Core(s) per socket", "Thread(s) per core" ] data = process.pipe(["lscpu"]) cpu = _parse_lscpu(data) # Fallback for some values cpuinfo = _parse_lscpu(File("/proc/cpuinfo").read()) cpu["Model name"] = \ cpu.get("Model name", "") or cpuinfo.get("model name", "") cpu_details = ("%s: %s" % (f, cpu.get(f, "(Unknown)")) for f in fields) return "\n".join(cpu_details)
def __update_profile(self, rng_num_bytes, disable_aes): additional_lines = [] process.check_call("sed -ic '/OPENSSL_DISABLE_AES_NI/d' /etc/profile", shell=True) if disable_aes: additional_lines += ["export OPENSSL_DISABLE_AES_NI=1"] process.check_call("sed -ic '/SSH_USE_STRONG_RNG/d' /etc/profile", shell=True) if rng_num_bytes: additional_lines += [ "export SSH_USE_STRONG_RNG=%s" % rng_num_bytes ] if additional_lines: self.logger.debug("Updating /etc/profile") lines = "\n" + "\n".join(additional_lines) File("/etc/profile").write(lines, "a") self.restart()
def parse_cfg(self): if not os.path.exists(self.cfgfilename): raise RuntimeError("vlans ain't enabled.") vlans = {} try: data = File(self.cfgfilename) data_block = False for line in data: if line.startswith("Name-Type"): data_block = True continue if not data_block: continue vdev, _, hdev = [field.strip() for field in line.split("|")] if not hdev in vlans: vlans[hdev] = [] vlans[hdev].append(vdev) except IOError as e: self.logger.warning("Could not read vlan config: %s" % e.message) return vlans
def update_args(self, arg, remove=False): replacement = arg # Check if it's parameterized if '=' in arg: arg = re.match(r'^(.*?)=.*', arg).groups()[0] self.__mount.remount(rw=True) lines = self.__get_lines() grub_cfg = "" for line in lines: if re.match(r'.*?\s%s' % arg, line): if remove: line = re.sub(r' %s(=.*?\s?)?' % arg, '', line) else: if arg != replacement: line = re.sub(r'%s(=.*?\s?)?' % arg, ' %s ' % replacement, line) elif re.match(r'^.*?vmlinuz', line): # Not in the kernel line. Add it. line = line.strip() + " %s\n" % replacement grub_cfg += line File(self.__handle.filename).write(grub_cfg, "w") self.__mount.remount(rw=False)
def __update_profile(self, rng_num_bytes, disable_aes): import ovirtnode.ovirtfunctions as ofunc additional_lines = [] ofunc.unmount_config("/etc/profile") process.check_call("sed -i '/OPENSSL_DISABLE_AES_NI/d' /etc/profile") if disable_aes: additional_lines += ["export OPENSSL_DISABLE_AES_NI=1"] process.check_call("sed -i '/SSH_USE_STRONG_RNG/d' /etc/profile") if rng_num_bytes: additional_lines += [ "export SSH_USE_STRONG_RNG=%s" % rng_num_bytes ] if additional_lines: self.logger.debug("Updating /etc/profile") lines = "\n" + "\n".join(additional_lines) File("/etc/profile").write(lines, "a") ofunc.ovirt_store_config("/etc/profile") self.restart()
def commit(self): self.logger.info("Connecting to Puppet server") cfg = Puppet().retrieve() lines = File("/etc/puppet/puppet.conf").read() conf = File("/etc/puppet/puppet.conf") for line in lines: try: item = re.match(r'^\s+(\w+) =', line).group(1) if item in cfg: conf.write( re.sub(r'(^.*?' + item + ' =).*', r'\1 "' + cfg[item] + '"', line)) except: conf.write(line) system.service("puppet", "stop") utils.process.check_call("puppet agent --test", shell=True) system.service("puppet", "start")
def kernel_cmdline_arguments(cmdline=None): """Return the arguments of the currently booted kernel """ cmdline = cmdline or File("/proc/cmdline").read() return _parse_cmdline_args(cmdline)
def update_args(self, arg, remove=False): self.__mount.remount(rw=True) grub_cfg = self._parse_config(self.__get_lines(), arg, remove) File(self.__handle.filename).write(grub_cfg, "w") self.__mount.remount(rw=False)
def cpe(self): """Return the CPE URI """ return File(self.CPE_FILE).read().strip()
def kernel_cmdline_arguments(): """Return the arguments of the currently booted kernel """ return _parse_cmdline_args(File("/proc/cmdline").read())
def is_bond(self, ifname): """Determins if ifname is a bond device """ return File(self.bond_slaves_path % ifname).exists()
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2016 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ovirt.node.utils.fs import File f = File("/etc/ovirt-hosted-engine-ha/agent.conf") f.sed("s/.*base-score.*/base-score=3400/")
def __get_domain(self): nfs_config = File(self.configfilename) matches = nfs_config.findall("^Domain = (.*)") return matches[0] if matches else None