def enable_snmpd(password): from ovirtnode.ovirtfunctions import ovirt_store_config process.call("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|awk '{print $4}'" % conf oldpwd, stderr = process.pipe(cmd) oldpwd = oldpwd.stdout.read().strip() process.call("sed -c -ie '/^createUser root/d' %s" % snmp_conf) f = open(snmp_conf, "a") # create user account f.write("createUser root SHA %s AES\n" % password) f.close() process.check_call("service snmpd start") # change existing password if len(oldpwd) > 0: 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) # Only reached when no excepion occurs process.call("rm -rf /tmp/snmpd.conf") ovirt_store_config(snmp_conf)
def _install_new_initramfs(self, new_initrd, pri_initrd): LOGGER.info("Installing the new initramfs " "%r to %r" % (new_initrd, pri_initrd)) backup_initrd = "/var/tmp/initrd0.img.backup" try: check_call(["cp", pri_initrd, backup_initrd]) except: LOGGER.error("Failed to create the backupfile") # Still trying to unlink, maybe setting attrs failed self.try_unlink(backup_initrd) raise try: check_call(["mv", new_initrd, pri_initrd]) # Only remove the backup in case that the new on got installed self.try_unlink(backup_initrd) except: LOGGER.error("Failed to put the new initrd in place") LOGGER.error(" Please cleanup manually") LOGGER.error(" Backup: %r" % backup_initrd) LOGGER.error(" initrd location: %r" % pri_initrd) self.try_unlink(new_initrd) raise
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() # 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") 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") cfg = fs.File(snmp_conf) # create user account cfg.write("createUser root SHA %s AES\n" % password) system.service("snmpd", "start") fs.Config().persist(snmp_conf) firewall.open_port(port="161", proto="udp")
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) fs.Config().unpersist(snmp_conf)
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 commit(self): nfsv4 = storage.NFSv4() nfsv4.domain(domain) fs.Config().persist(nfsv4.configfilename) system.service("rpcidmapd", "restart") process.check_call("nfsidmap -c")
def enable_snmpd(password): from ovirtnode.ovirtfunctions import ovirt_store_config 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|awk '{print $4}'" % conf oldpwd, stderr = process.pipe(cmd) oldpwd = oldpwd.stdout.read().strip() process.call("sed -c -ie '/^createUser root/d' %s" % snmp_conf) f = open(snmp_conf, "a") # create user account f.write("createUser root SHA %s AES\n" % password) f.close() system.service("snmpd", "start") # change existing password if len(oldpwd) > 0: 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) # Only reached when no excepion occurs process.call("rm -rf /tmp/snmpd.conf") ovirt_store_config(snmp_conf)
def disable_snmpd(): from ovirtnode.ovirtfunctions import remove_config 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) remove_config(snmp_conf)
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 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"])
def commit(self): action = "restart" if enabled else "stop" try: process.check_call("service ovirt-cim %s 2>/dev/null" % action) self.logger.debug("Configured CIM successfully") except RuntimeError: raise TransactionError("CIM configuration failed")
def commit(self): def check_for_errors(smreg_output): mapping = {"Invalid credentials": "Invalid username" "/password combination", "already been taken": "This hostname is " "already registered", "Organization": "Organization must be " "specified with " "Satellite 6"} for k, v in mapping.items(): if k in smreg_output: raise RuntimeError(v) # Fallthrough raise RuntimeError("Registration Failed") self.logger.info("Registering with subscription-manager") self.logger.info(Vars.argbuilder.get_commandlist(string=True, filtered=True) ) # This may block if waiting for input with check_output. # pipe doesn't block smreg_output = process.pipe( Vars.argbuilder.get_commandlist()) if "been registered" not in smreg_output: check_for_errors(smreg_output) # If we made it down here, we registered successfully else: system.service("rhsmcertd", "start") configs = ["/var/lib/rhsm/cache/installed_products.json", "/var/lib/rhsm/facts/facts.json"] for conf in configs: Config().persist(conf) Config().persist("/etc/pki/consumer/key.pem") Config().persist("/etc/pki/consumer/cert.pem") if cfg["url"]: self.logger.info("System %s successfully " "registered to %s" % (cfg["profile"], cfg["url"])) else: self.logger.info("System %s successfully " "registered to SAM" % cfg["profile"]) # This isn't strictly necessary if RHN().retrieve()["activationkey"]: cmd = ["subscription-manager", "auto-attach"] try: process.check_call(cmd) except process.CalledProcessError: raise RuntimeError("Registration succeded, but " "there was a problem while " "auto-attaching with the " "provided key")
def __set_domain(self, domain): current_domain = self.__get_domain() if current_domain.startswith("#"): current_domain = ("#Domain = %s" % current_domain.replace("# ", "")) process.check_call("sed -i 's/%s/Domain = %s/g' %s" % (current_domain, domain, self.configfilename)) else: process.check_call("sed -i '/^Domain/ s/%s/%s/g' %s" % (current_domain, domain, self.configfilename))
def commit(self): initial_args = ["subscription-manager"] initial_args.extend(["config"]) host = None port = None prefix = None if cfg["url"]: host, port, prefix = RHN().parse_host_uri(cfg["url"]) # Default to /rhsm for Satellite 6 if cfg["ca_cert"] and \ DEFAULT_CA_SAT6 in cfg["ca_cert"] and \ cfg["rhntype"] == "satellite": prefix = "/rhsm" else: # Default values for public SAM host = "subscription.rhn.redhat.com" prefix = "/subscription" # Assume https unless we matched another scheme, probably http port = str(port) if port else "443" mapping = {"--server.hostname": host, "--server.port": port, } # Figure out what other arguments need to be set # If there's a ca certificate or it's satellite, it's sat6 if cfg["ca_cert"] and DEFAULT_CA_SAT6 in cfg["ca_cert"] and \ cfg["rhntype"] and cfg["rhntype"] == "satellite": mapping["--server.prefix"] = prefix else: prefix = "%s/%s" % (host, prefix) if prefix else \ "%s/pulp/repos" % host mapping["--rhsm.baseurl"] = prefix # FIXME: Why are we setting a default value if this was set? # Feels like it should be the other way. Investigate if cfg["ca_cert"]: mapping["--rhsm.repo_ca_cert"] = \ "/etc/rhsm/ca/candlepin-local.pem" ab = ArgBuilder(initial_args, mapping) try: process.check_call(ab.get_commandlist()) Config().persist("/etc/rhsm/rhsm.conf") except process.CalledProcessError: self.logger.debug("Calling subscription-manager with " "'%s' failed!" % ab.get_commandlist( string=True)) raise RuntimeError("Error updating subscription manager " "configuration")
def _run_command(mapping): ab = ArgBuilder(initial_args, mapping) try: process.check_call(ab.get_commandlist()) except process.CalledProcessError: self.logger.debug("Updating subscription-manager proxy" " configuration with '%s' failed!" % ab.get_commandlist(string=True, filtered=True)) raise RuntimeError("Error updating subscription " "manager proxy configuration")
def commit(self): initial_args = ["subscription-manager"] initial_args.extend(["config"]) host = None port = None prefix = None if cfg["url"]: host, port, prefix = RHN().parse_host_uri(cfg["url"]) # Default to /rhsm for Satellite 6 if cfg["ca_cert"].endswith(".pem") and \ cfg["rhntype"] == "satellite": prefix = "/rhsm" else: # Default values for public SAM host = "subscription.rhn.redhat.com" prefix = "/subscription" # Assume https unless we matched another scheme, probably http port = str(port) if port else "443" mapping = {"--server.hostname": host, "--server.port": port, } # Figure out what other arguments need to be set # If there's a ca certificate or it's satellite, it's sat6 if cfg["ca_cert"] and not cfg["ca_cert"].endswith(".pem") or \ cfg["rhntype"] == "satellite": mapping["--server.prefix"] = prefix else: prefix = "%s/%s" % (host, prefix) if prefix else \ "%s/pulp/repos" % host mapping["--rhsm.baseurl"] = prefix # FIXME: Why are we setting a default value if this was set? # Feels like it should be the other way. Investigate if cfg["ca_cert"]: mapping["--rhsm.repo_ca_cert"] = \ "/etc/rhsm/ca/candlepin-local.pem" ab = ArgBuilder(initial_args, mapping) try: process.check_call(ab.get_commandlist()) Config().persist("/etc/rhsm/rhsm.conf") except process.CalledProcessError: self.logger.debug("Calling subscription-manager with " "'%s' failed!" % ab.get_commandlist( string=True)) raise RuntimeError("Error updating subscription manager " "configuration")
def __set_domain(self, domain): current_domain = self.__get_domain() cmd = None if current_domain.startswith("#"): current_domain = ("#Domain = %s" % current_domain.replace("# ", "")) cmd = ['sed', '-i', '-c', 's/%s/Domain = %s/g' % (current_domain, domain), self.configfilename] else: cmd = ['sed', '-i', '-c', '/^Domain/ s/%s/%s/g' % (current_domain, domain), self.configfilename] process.check_call(cmd)
def setup_firewalld(port, proto): port_conf = "" rule_dict = {"port": port, "proto": proto} port_conf += FIREWALLD_PORT_XML % rule_dict port_dict = {"port_section": port_conf} with open(PLUGIN_XML_OUT, "w") as f: f.write(FIREWALLD_XML_TEMPLATE % port_dict) process.call(["firewall-cmd", "--reload"]) process.call( ["firewall-cmd", "--permanent", "--add-service", "node-plugin"]) process.check_call(["firewall-cmd", "--reload"])
def _setup_firewalld(port, proto): port_conf = "" rule_dict = {"port": port, "proto": proto } port_conf += FIREWALLD_PORT_XML % rule_dict port_dict = {"port_section": port_conf} with open(PLUGIN_XML_OUT, "w") as f: f.write(FIREWALLD_XML_TEMPLATE % port_dict) process.call(["firewall-cmd", "--reload"]) process.call(["firewall-cmd", "--permanent", "--add-service", "node-plugin"]) process.check_call(["firewall-cmd", "--reload"])
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 rhn_check(): filebased = True registered = False if filebased: # The following file exists when the sys is registered with rhn registered = os.path.exists("/etc/sysconfig/rhn/systemid") else: if process.check_call("rhn_check"): registered = True return registered
def __init__(self, fake=False, refresh=False): super(Devices, self).__init__() if fake: self._fake_devices = {} for n in range(1, 4): args = ["%s%s" % (k, n) for k in "path", "bus", "name", "size", "desc", "serial", "model"] self._fake_devices[args[1]] = Device(*tuple(args)) else: if refresh: try: process.check_call(["udevadm", "trigger", "--action=change", "--subsystem-match=block"]) process.check_call(["udevadm", "settle", "--timeout=10"]) except process.CalledProcessError: self.logger.error("Couldn't refresh udev block devices") import ovirtnode.storage self._storage = ovirtnode.storage.Storage()
def commit(self): self.logger.info("Registering to RHN account...") # Filter out passwords from the log logged_args = Vars.argbuilder.get_commandlist(string=True, filtered=True) self.logger.debug(logged_args) try: process.check_call(Vars.argbuilder.get_commandlist()) Config().persist("/etc/sysconfig/rhn/up2date") Config().persist("/etc/sysconfig/rhn/systemid") if cfg["url"]: self.logger.info("System %s successfully registered to" " %s" % (cfg["profile"], cfg["url"])) else: self.logger.info("System successfully registered to" "RHN classic") except process.CalledProcessError: self.logger.exception("Failed to call: %s" % logged_args) raise RuntimeError("Error registering to RHN account")
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 __init__(self, fake=False, refresh=False): super(Devices, self).__init__() if fake: self._fake_devices = {} for n in range(1, 4): args = [ "%s%s" % (k, n) for k in "path", "bus", "name", "size", "desc", "serial", "model" ] self._fake_devices[args[1]] = Device(*tuple(args)) else: if refresh: try: process.check_call([ "udevadm", "trigger", "--action=change", "--subsystem-match=block" ]) process.check_call(["udevadm", "settle", "--timeout=10"]) except process.CalledProcessError: self.logger.error("Couldn't refresh udev block devices") import ovirtnode.storage self._storage = ovirtnode.storage.Storage()
def set_active_profile(profile): """Sets the active tuned profile on the system. Returns: A boolean based on the return of tuned-adm """ try: if (profile == "None" or profile == "off"): ret = process.check_call("/usr/sbin/tuned-adm off") if not ret == 0: raise Exception("DISABLE") raise Exception("Failed to disable tuned") elif profile not in get_available_profiles(): raise Exception("%s is not a known profile" % profile) else: ret = process.check_call("/usr/sbin/tuned-adm profile %s" % profile) if not ret == 0: raise Exception("Failed to set profile to %s" % profile) except Exception as e: print e return False return True
def enable_snmpd(password): from ovirtnode.ovirtfunctions import ovirt_store_config 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|awk '{print $4}'" % conf oldpwd, stderr = process.pipe(cmd, shell=True) oldpwd = oldpwd.stdout.read().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: 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"]) ovirt_store_config(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") ovirt_store_config('/etc/snmp/snmpd.conf') system.service("snmpd", "start")
def mount_efi(target="/liveos/efi"): """Mount the EFI config partition """ if os.path.ismount(target): return True if is_iscsi() or Filesystem.by_label("Boot"): efi_part = Filesystem.by_label("Boot").device else: efi_part = Filesystem.by_label("Root").device # Get the first partition on the disk efi_part = efi_part[:-1] + "1" if not os.path.exists(target): if not process.check_call(["mkdir", "-v", "-p", target]): LOGGER.exception("Unable to create mount target for EFI " "partition") raise RuntimeError("Unable to create mount target for EFI " "partition") Mount(target, efi_part, "vfat").mount()
def create_cim_user(username="******", shell="/sbin/nologin", main_group="cim", group_list=["sfcb"]): from ovirtnode.ovirtfunctions import check_user_exists, add_user if not check_user_exists(username): add_user(username, shell, main_group, group_list) else: userinfo = pwd.getpwnam(username) if not userinfo.pw_gid == grp.getgrnam(main_group).gr_gid: process.check_call("usermod -g %s %s" % (main_group, username)) if not userinfo.pw_shell == shell: process.check_call("usermod -s %s %s" % (shell, username)) for group in group_list: if username not in grp.getgrnam(group).gr_mem: process.check_call("usermod -G %s %s" % (",".join(group_list), username)) break
def open_port(): cmd = [ "iptables", "-I", "INPUT", "1", "-p", proto, "--dport", port, "-j", "ACCEPT" ] process.check_call(cmd)
def open_port(): cmd = ["iptables", "-I", "INPUT", "1", "-p", proto, "--dport", port, "-j", "ACCEPT"] process.check_call(cmd)
def save_rules(): process.check_call("iptables-save -c > %s" % rules, shell=True) fs.Config().persist(rules)
def load_rules(): process.check_call("iptables-restore -c < %s" % rules, shell=True)
def setup_iptables(port, proto): cmd = ["iptables", "-I", "INPUT", "1", "-p", proto, "--dport", port, "-j", "ACCEPT"] process.check_call(cmd, shell=True)
def commit(self): def check_for_errors(smreg_output): mapping = {"Invalid credentials": "Invalid username" "/password combination", "already been taken": "This hostname is " "already registered", "Organization": "Organization not found " "on Satellite 6"} for k, v in mapping.items(): if k in smreg_output: raise RuntimeError(v) # Fallthrough raise RuntimeError("Registration Failed") self.logger.info("Registering with subscription-manager") self.logger.info(Vars.argbuilder.get_commandlist(string=True, filtered=True) ) # This may block if waiting for input with check_output. # pipe doesn't block smreg_output = process.pipe( Vars.argbuilder.get_commandlist()) if "been registered" not in smreg_output: check_for_errors(smreg_output) # If we made it down here, we registered successfully else: # Truncate the classic rhn cron job in favor of RHSM rhn_cronjob = "/etc/cron.d/rhn-virtualization.cron" with open(rhn_cronjob, "w"): pass Config().persist(rhn_cronjob) system.service("rhsmcertd", "start") configs = ["/var/lib/rhsm/cache/installed_products.json", "/var/lib/rhsm/facts/facts.json"] for conf in configs: Config().persist(conf) Config().persist("/etc/pki/consumer/key.pem") Config().persist("/etc/pki/consumer/cert.pem") if cfg["url"]: self.logger.info("System %s successfully " "registered to %s" % (cfg["profile"], cfg["url"])) else: self.logger.info("System %s successfully " "registered to RHSM" % cfg["profile"]) # This isn't strictly necessary if RHN().retrieve()["activationkey"]: cmd = ["subscription-manager", "auto-attach"] try: process.check_call(cmd) except process.CalledProcessError: raise RuntimeError("Registration succeded, but " "there was a problem while " "auto-attaching with the " "provided key")
def check_status(self): try: process.check_call(["ipmitool", "-I", "open", "chassis", "status"]) return True except CalledProcessError: return False
def commit(self): cfg = RHN().retrieve() self.logger.debug(cfg) # rhntype = cfg["rhntype"] org = cfg["org"] serverurl = cfg["url"] cacert = cfg["ca_cert"] activationkey = cfg["activationkey"] username = cfg["username"] profilename = cfg["profile"] proxy = cfg["proxy"] proxyuser = cfg["proxyuser"] if os.path.exists("/etc/sysconfig/rhn/systemid"): remove_config("/etc/sysconfig/rhn/systemid") extra_args = ['--force'] if not activationkey: extra_args.append("--autosubscribe") sm = ['/usr/sbin/subscription-manager'] args = list(sm) args.append('register') if activationkey and org: args.append('--activationkey') args.append(activationkey) args.append('--org') args.append(org) elif username: args.append('--username') args.append(username) if password: args.append('--password') args.append(password) else: # skip RHN registration when neither activationkey # nor username/password is supplied # return success for AUTO w/o rhn_* parameters return if serverurl: (host, port) = parse_host_port(serverurl) parsed_url = urlparse(serverurl) prefix = parsed_url.path if port == 0: port = "443" else: port = str(port) else: prefix = "/subscription" host = "subscription.rhn.redhat.com" port = "443" location = "/etc/rhsm/ca/candlepin-local.pem" if cacert: if not os.path.exists(cacert): self.logger.info("Downloading CA cert.....") RHN().retrieveCert(cacert, location) if os.path.isfile(location): if os.stat(location).st_size > 0: ovirt_store_config(location) else: raise RuntimeError("Error Downloading CA cert!") smconf = list(sm) smconf.append('config') smconf.append('--server.hostname') smconf.append(host) smconf.append('--server.port') smconf.append(port) smconf.append('--server.prefix') smconf.append(prefix) if cacert: smconf.append('--rhsm.repo_ca_cert') smconf.append('/etc/rhsm/ca/candlepin-local.pem') try: subprocess.check_call(smconf) ovirt_store_config("/etc/rhsm/rhsm.conf") except: raise RuntimeError("Error updating subscription manager \ configuration") if profilename: args.append('--name') args.append(profilename) if proxy: try: (host, port) = proxy.split(":") process.check_call(["subscription-manager", "config", "--server.proxy_hostname", host]) process.check_call(["subscription-manager", "config", "--server.proxy_port", port]) if proxyuser: args.append('--proxyuser') args.append(proxyuser) cmd = ["subscription-manager", "config", "--server.proxy_user", proxyuser] process.check_call(cmd) if proxypass: args.append('--proxypassword') args.append(proxypass) cmd = ["subscription-manager", "config", "--server.proxy_password", proxypass] logged_args = list(cmd) remove_values_from_args = [ "--server.proxy_password"] for idx, arg in enumerate(cmd): if arg in remove_values_from_args: logged_args[idx+1] = "XXXXXXX" logged_args = str(logged_args) self.logger.info(logged_args) subprocess.check_call(cmd) except: raise RuntimeError("Error updating subscription \ manager proxy configuration") args.extend(extra_args) self.logger.info("Registering to RHN account.....") rhsm_configs = (["/var/lib/rhsm/cache/installed_products.json", "/var/lib/rhsm/facts/facts.json"]) unmount_config(rhsm_configs) unmount_config(glob.glob("/etc/pki/consumer/*pem")) def unlink_if_exists(f): if os.path.exists(f): os.unlink(f) for f in rhsm_configs: unlink_if_exists(f) logged_args = list(args) remove_values_from_args = ["--password", "--proxypassword"] for idx, arg in enumerate(logged_args): if arg in remove_values_from_args: logged_args[idx+1] = "XXXXXXX" logged_args = str(logged_args) self.logger.info(logged_args) smreg_output = process.pipe(args) self.logger.debug(smreg_output) if "been registered" not in smreg_output: if "Invalid credentials" in smreg_output: raise RuntimeError("Invalid Username / Password") elif "already been taken" in smreg_output: raise RuntimeError("Hostname is already " + "registered") else: raise RuntimeError("Registration Failed") else: ovirt_store_config(rhsm_configs) ovirt_store_config("/etc/pki/consumer/key.pem") ovirt_store_config("/etc/pki/consumer/cert.pem") self.logger.info("System %s sucessfully registered \ to %s" % (profilename, serverurl))
def commit(self): cfg = RHN().retrieve() self.logger.debug(cfg) # rhntype = cfg["rhntype"] org = cfg["org"] serverurl = cfg["url"] cacert = cfg["ca_cert"] activationkey = cfg["activationkey"] username = cfg["username"] profilename = cfg["profile"] proxy = cfg["proxy"] proxyuser = cfg["proxyuser"] if os.path.exists("/etc/sysconfig/rhn/systemid"): remove_config("/etc/sysconfig/rhn/systemid") extra_args = ['--force'] if not activationkey: extra_args.append("--autosubscribe") sm = ['/usr/sbin/subscription-manager'] args = list(sm) args.append('register') if activationkey and org: args.append('--activationkey') args.append(activationkey) args.append('--org') args.append(org) elif username: args.append('--username') args.append(username) if password: args.append('--password') args.append(password) else: # skip RHN registration when neither activationkey # nor username/password is supplied # return success for AUTO w/o rhn_* parameters return if serverurl: (host, port) = parse_host_port(serverurl) parsed_url = urlparse(serverurl) prefix = parsed_url.path if port == 0: port = "443" else: port = str(port) else: prefix = "/subscription" host = "subscription.rhn.redhat.com" port = "443" location = "/etc/rhsm/ca/candlepin-local.pem" if cacert: if not os.path.exists(cacert): self.logger.info("Downloading CA cert.....") RHN().retrieveCert(cacert, location) if os.path.isfile(location): if os.stat(location).st_size > 0: ovirt_store_config(location) else: raise RuntimeError("Error Downloading CA cert!") smconf = list(sm) smconf.append('config') smconf.append('--server.hostname') smconf.append(host) smconf.append('--server.port') smconf.append(port) smconf.append('--server.prefix') smconf.append(prefix) if cacert: smconf.append('--rhsm.repo_ca_cert') smconf.append('/etc/rhsm/ca/candlepin-local.pem') try: subprocess.check_call(smconf) ovirt_store_config("/etc/rhsm/rhsm.conf") except: raise RuntimeError("Error updating subscription manager \ configuration") if profilename: args.append('--name') args.append(profilename) if proxy: try: (host, port) = proxy.split(":") process.check_call([ "subscription-manager", "config", "--server.proxy_hostname", host ]) process.check_call([ "subscription-manager", "config", "--server.proxy_port", port ]) if proxyuser: args.append('--proxyuser') args.append(proxyuser) cmd = [ "subscription-manager", "config", "--server.proxy_user", proxyuser ] process.check_call(cmd) if proxypass: args.append('--proxypassword') args.append(proxypass) cmd = [ "subscription-manager", "config", "--server.proxy_password", proxypass ] logged_args = list(cmd) remove_values_from_args = [ "--server.proxy_password" ] for idx, arg in enumerate(cmd): if arg in remove_values_from_args: logged_args[idx + 1] = "XXXXXXX" logged_args = str(logged_args) self.logger.info(logged_args) subprocess.check_call(cmd) except: raise RuntimeError("Error updating subscription \ manager proxy configuration") args.extend(extra_args) self.logger.info("Registering to RHN account.....") rhsm_configs = ([ "/var/lib/rhsm/cache/installed_products.json", "/var/lib/rhsm/facts/facts.json" ]) unmount_config(rhsm_configs) unmount_config(glob.glob("/etc/pki/consumer/*pem")) def unlink_if_exists(f): if os.path.exists(f): os.unlink(f) for f in rhsm_configs: unlink_if_exists(f) logged_args = list(args) remove_values_from_args = ["--password", "--proxypassword"] for idx, arg in enumerate(logged_args): if arg in remove_values_from_args: logged_args[idx + 1] = "XXXXXXX" logged_args = str(logged_args) self.logger.info(logged_args) smreg_output = process.pipe(args) self.logger.debug(smreg_output) if "been registered" not in smreg_output: if "Invalid credentials" in smreg_output: raise RuntimeError("Invalid Username / Password") elif "already been taken" in smreg_output: raise RuntimeError("Hostname is already " + "registered") else: raise RuntimeError("Registration Failed") else: ovirt_store_config(rhsm_configs) ovirt_store_config("/etc/pki/consumer/key.pem") ovirt_store_config("/etc/pki/consumer/cert.pem") self.logger.info("System %s sucessfully registered \ to %s" % (profilename, serverurl))