def commit(self): aug = AugeasWrapper() localhost_entry = None for entry in aug.match("/files/etc/hosts/*"): if aug.get(entry + "/ipaddr") == "127.0.0.1": localhost_entry = entry break if not localhost_entry: raise RuntimeError("Couldn't find entry for localhost") # Remove all aliases for alias_entry in aug.match(localhost_entry + "/alias"): aug.remove(alias_entry, False) # ... and create a new one aliases = ["localhost", "localhost.localdomain"] if self.hostname: aliases.append(self.hostname) for _idx, alias in enumerate(aliases): idx = _idx + 1 p = "%s/alias[%s]" % (localhost_entry, idx) aug.set(p, alias, False) config.network.hostname(self.hostname) fs.Config().persist("/etc/hosts") fs.Config().persist("/etc/hostname") fs.Config().persist("/etc/sysconfig/network") utils.network.reset_resolver()
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 disable_snmpd(): system.service("snmpd", "stop") # copy to /tmp for enable/disable toggles w/o reboot process.check_call(["cp", "/etc/snmp/snmpd.conf", "/tmp"]) process.check_call("sed -c -ie '/^createUser root/d' %s" % snmp_conf, shell=True) configs = [snmp_conf, snmp_dir] [fs.Config().unpersist(c) for c in configs if fs.Config().exists(c)]
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 enable_snmpd(password): def change_password(oldpwd): system.service("snmpd", "start") pwd_change_cmd = (("snmpusm -v 3 -u root -n \"\" -l authNoPriv " + "-a SHA -A %s localhost passwd %s %s -x AES") % (oldpwd, oldpwd, password)) process.check_call(pwd_change_cmd, shell=True) # Only reached when no excepion occurs process.call(["rm", "-rf", "/tmp/snmpd.conf"]) # Check for an old password if os.path.exists("/tmp/snmpd.conf"): conf = "/tmp/snmpd.conf" else: conf = snmp_conf cmd = "cat %s | grep createUser | grep -v '^#' | awk '{print $4}'" % conf oldpwd = process.pipe(cmd, shell=True).strip() if len(oldpwd) > 0: change_password(oldpwd) else: system.service("snmpd", "stop") # create user account process.check_call(["net-snmp-create-v3-user", "-A", password, "-a", "SHA", "-x", "AES", "root"]) system.service("snmpd", "start") fs.Config().persist(snmp_dir) firewall.open_port(port="161", proto="udp")
def writeConfFile(self, fileName, configuration): '''Backs up the previous contents of the file referenced by fileName writes the new configuration and sets the specified access mode.''' self._backup(fileName) configuration = self.CONFFILE_HEADER + '\n' + configuration logging.debug('Writing to file %s configuration:\n%s', fileName, configuration) with open(fileName, 'w') as confFile: confFile.write(configuration) os.chmod(fileName, 0o664) try: # filname can be of 'unicode' type. restorecon calls into a C API # that needs a char *. Thus, it is necessary to encode unicode to # a utf-8 string. selinux.restorecon(fileName.encode('utf-8')) except: logging.debug( 'ignoring restorecon error in case ' 'SElinux is disabled', exc_info=True) # make sure that ifcfg files are always persisted by the node if self.unifiedPersistence and utils.isOvirtNode(): node_fs.Config().persist(fileName)
def commit(self): nfsv4 = storage.NFSv4() nfsv4.domain(domain) fs.Config().persist(nfsv4.configfilename) system.service("rpcidmapd", "restart") process.check_call("nfsidmap -c")
def _write(self, cfg): lines = [] # Sort the dict, looks nicer lines.append('[environment:default]') for key in sorted(cfg.iterkeys()): lines.append('%s=%s:%s' % (key, common.typeName(cfg[key]), cfg[key])) contents = "\n".join(lines) + "\n" # The following logic is mainly needed to allow an "offline" testing config_fs = fs.Config() if config_fs.is_enabled(): os.unlink(self.filename) with config_fs.open_file(self.filename, "w") as dst: os.fchmod(f.fileno(), 0o600) dst.write(contents) else: try: self.logger.debug("configuration filename : %s", self.filename) fs.atomic_write(self.filename, contents) except Exception as e: self.logger.warning("Atomic write failed: %s" % e) with open(self.filename, "w") as dst: dst.write(contents)
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 _remove_ifcfg_configs(self): pat = NicConfig.IfcfgBackend.filename_tpl % "*" remaining_ifcfgs = glob.glob(pat) self.logger.debug("Attemtping to remove remaining ifcfgs: %s" % remaining_ifcfgs) pcfg = fs.Config() for fn in remaining_ifcfgs: pcfg.delete(fn)
def _upgrade_seal(upgrade): seal_file = _upgrade_seal_path(upgrade) try: touchFile(seal_file) except (OSError, IOError): _get_upgrade_log().exception("Failed to seal upgrade %s", upgrade.name) else: if isOvirtNode(): from ovirt.node.utils import fs fs.Config().persist(seal_file) _get_upgrade_log().debug("Upgrade %s successfully performed", upgrade.name)
def commit(self): m = Network().retrieve() aug = AugeasWrapper() bond = NicBonding().retrieve() if bond["slaves"]: NicBonding().transaction().commit() has_network = m["iface"] is not None if has_network: topology = NetworkLayout().retrieve()["layout"] if topology == "bridged": self.__write_bridged_config() else: self.__write_direct_config() else: topology = NetworkLayout().configure_direct() aug.set("/files/etc/sysconfig/network/NETWORKING", "yes" if has_network else "no") fs.Config().persist("/etc/sysconfig/network") fs.Config().persist("/etc/hosts")
def enable_snmpd(password): system.service("snmpd", "stop") # get old password # if os.path.exists("/tmp/snmpd.conf"): conf = "/tmp/snmpd.conf" else: conf = snmp_conf cmd = "cat %s|grep createUser| grep -v '^#' | awk '{print $4}'" % conf oldpwd = process.pipe(cmd, shell=True).strip() process.call("sed -c -ie '/^createUser root/d' %s" % snmp_conf, shell=True) f = open(snmp_conf, "a") # create user account f.write("createUser root SHA %s AES\n" % password) f.close() # change existing password if len(oldpwd) > 0: system.service("snmpd", "start") pwd_change_cmd = (("snmpusm -v 3 -u root -n \"\" -l authNoPriv -a " + "SHA -A %s localhost passwd %s %s -x AES") % (oldpwd, oldpwd, password)) process.check_call(pwd_change_cmd, shell=True) # Only reached when no excepion occurs process.call(["rm", "-rf", "/tmp/snmpd.conf"]) system.service("snmpd", "stop") fs.Config().persist(snmp_conf) if not any([ x for x in open('/etc/snmp/snmpd.conf').readlines() if 'rwuser root' in x ]): with open('/etc/snmp/snmpd.conf', 'a') as f: f.write("rwuser root") fs.Config().persist("/etc/snmp/snmpd.conf") system.service("snmpd", "start")
def _insert_ssh_key(key_file_name, key): """Insert the downloaded public ssh key into authorized key file Args key_file_name - full path to authorized key file key - String of public ssh key """ keys = [] if os.path.exists(key_file_name): for line in open(key_file_name): if not line.endswith('\n'): line += '\n' if line != '\n' and not line.endswith(" ovirt-engine\n") or \ line.startswith("#"): keys.append(line) if not key.endswith('\n'): key += '\n' keys.append(key) with tempfile.NamedTemporaryFile(dir=os.path.dirname(key_file_name), delete=False) as f: f.write(''.join(keys)) if os.path.exists('/etc/rhev-hypervisor-release') or \ glob.glob('/etc/ovirt-node-*-release'): fs.Config().unpersist(key_file_name) os.rename(f.name, key_file_name) if os.path.exists('/etc/rhev-hypervisor-release') or \ glob.glob('/etc/ovirt-node-*-release'): fs.Config().persist(key_file_name)
def write(self): """Write a ifcfg file from the cfg """ data = {} for k in self.cfg._keys: data[k.upper()] = self.cfg.__dict__.get(k) ShellVarFile.write(self, data, True) pcfg = fs.Config() if pcfg.is_enabled(): pcfg.persist(self.filename) return data
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 _write(self, cfg): lines = [] # Sort the dict, looks nicer for key in sorted(cfg.iterkeys()): lines.append("%s=\"%s\"" % (key, cfg[key])) contents = "\n".join(lines) + "\n" # The following logic is mainly needed to allow an "offline" testing config_fs = fs.Config() if config_fs.is_enabled(): with config_fs.open_file(self.filename, "w") as dst: dst.write(contents) else: try: fs.atomic_write(self.filename, contents) except Exception as e: self.logger.warning("Atomic write failed: %s" % e) with open(self.filename, "w") as dst: dst.write(contents)
def _add_authorized_ssh_key(key): """Check the dependencies, like creation ssh dir, chmod, persist file in case of ovirt node and selinux stuff to insert the ssh public key to authorized key file Args key - String of public ssh key """ _PATH_ROOT_SSH = pwd.getpwnam('root').pw_dir + '/.ssh' _PATH_ROOT_AUTH_KEYS = _PATH_ROOT_SSH + '/authorized_keys' if not os.path.exists(_PATH_ROOT_SSH): os.mkdir(_PATH_ROOT_SSH, 0o700) _silent_restorecon(_PATH_ROOT_SSH) _insert_ssh_key(_PATH_ROOT_AUTH_KEYS, key) os.chmod(_PATH_ROOT_AUTH_KEYS, 0o644) _silent_restorecon(_PATH_ROOT_AUTH_KEYS) if os.path.exists('/etc/rhev-hypervisor-release') or \ glob.glob('/etc/ovirt-node-*-release'): fs.Config().persist(_PATH_ROOT_AUTH_KEYS)
from ovirt.node.utils import fs file_name = "/etc/redhat-release" fs.Config().unpersist(file_name) fs.Config().persist(file_name)
def save_rules(): process.check_call("iptables-save -c > %s" % rules, shell=True) fs.Config().persist(rules)
def delete(self): pcfg = fs.Config() if pcfg.is_enabled(): pcfg.unpersist(self.filename) self._fileobj.delete()