コード例 #1
0
    def postgres_startup(self):

        cmd = "postgresql-setup initdb"
        from ovirt.node.utils import process
        res = process.pipe(cmd)

        cmd = "systemctl start postgresql"

        res = process.pipe(cmd)
コード例 #2
0
 def postgres_startup(self):
     
     cmd = "postgresql-setup initdb"
     from ovirt.node.utils import process
     res=process.pipe(cmd)
     
     cmd = "systemctl start postgresql"
     
     res=process.pipe(cmd)        
コード例 #3
0
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")
コード例 #4
0
ファイル: snmp_model.py プロジェクト: oVirt/Node
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)
コード例 #5
0
ファイル: snmp_model.py プロジェクト: Zealsathish/ovirt-node
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")
コード例 #6
0
ファイル: snmp_model.py プロジェクト: ianjw11/ovirt-node
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)
コード例 #7
0
ファイル: system.py プロジェクト: haiyangd/ovirt-node
 def _raw_nvr(self):
     cmd = ["rpm", "-q", self.name]
     nvr = process.pipe(cmd).strip().split("\n")
     self.logger.debug("Found build: %s" % nvr)
     if len(nvr) != 1:
         raise RuntimeError("Failed to retrieve nvr for %s: %s" % (self.name, nvr))
     return nvr[0]
コード例 #8
0
 def sed(self, expr, inplace=True):
     """Run a sed expression on the file
     """
     cmd = ["sed", "-c"]
     if inplace:
         cmd.append("-i")
     cmd += ["-e", expr, self.filename]
     return process.pipe(cmd)
コード例 #9
0
ファイル: system.py プロジェクト: xiaowenhao111/ovirt-node
 def _raw_nvr(self):
     cmd = ["rpm", "-q", self.name]
     nvr = process.pipe(cmd).strip().split("\n")
     self.logger.debug("Found build: %s" % nvr)
     if len(nvr) != 1:
         raise RuntimeError("Failed to retrieve nvr for %s: %s" %
                            (self.name, nvr))
     return nvr[0]
コード例 #10
0
ファイル: fs.py プロジェクト: vafaronaghi/ovirt-node
 def sed(self, expr, inplace=True):
     """Run a sed expression on the file
     """
     cmd = ["sed", "-c"]
     if inplace:
         cmd.append("-i")
     cmd += ["-e", expr, self.filename]
     return process.pipe(cmd)
コード例 #11
0
ファイル: rhn_model.py プロジェクト: kanalun/ovirt-node
            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")
コード例 #12
0
ファイル: network.py プロジェクト: aiminickwong/ovirt_config
 def _default_fallback(self):
     # Fallback
     gw = None
     cmd = "ip route list"
     for line in process.pipe(cmd).split("\n"):
         token = re.split("\s+", line)
         if line.startswith("default via"):
             gw = token[2]
     return gw
コード例 #13
0
ファイル: system.py プロジェクト: xiaowenhao111/ovirt-node
def journal(unit=None, this_boot=True):
    """Convenience function to access the journal
    """
    cmd = ["journalctl"]
    if unit:
        cmd += ["--unit", unit]
    if this_boot:
        cmd += ["--this-boot"]
    return process.pipe(cmd)
コード例 #14
0
 def _default_fallback(self):
     # Fallback
     gw = None
     cmd = ["ip", "route", "list"]
     for line in process.pipe(cmd).split("\n"):
         token = re.split("\s+", line)
         if line.startswith("default via"):
             gw = token[2]
     return gw
コード例 #15
0
ファイル: system.py プロジェクト: haiyangd/ovirt-node
def journal(unit=None, this_boot=True):
    """Convenience function to access the journal
    """
    cmd = ["journalctl"]
    if unit:
        cmd += ["--unit", unit]
    if this_boot:
        cmd += ["--this-boot"]
    return process.pipe(cmd)
コード例 #16
0
ファイル: ping.py プロジェクト: fabiand/ovirt-node
    def run(self):
        try:
            ui_thread = self.p.application.ui.thread_connection()
            stdoutdump = self.p.widgets["ping.result"]

            self.p.widgets["ping.do_ping"].enabled(False)
            ui_thread.call(lambda: stdoutdump.text("Pinging ..."))
            out = process.pipe(self.cmd, shell=True)
            ui_thread.call(lambda: stdoutdump.text(out))
        except:
            self.p.logger.exception("Exception while pinging")
        finally:
            self.p.widgets["ping.do_ping"].enabled(True)
コード例 #17
0
ファイル: ping.py プロジェクト: GregSutcliffe/ovirt-node
    def run(self):
        try:
            ui_thread = self.p.application.ui.thread_connection()
            stdoutdump = self.p.widgets["ping.result"]

            self.p.widgets["ping.do_ping"].enabled(False)
            ui_thread.call(lambda: stdoutdump.text("Pinging ..."))
            out = process.pipe(self.cmd, shell=True)
            ui_thread.call(lambda: stdoutdump.text(out))
        except:
            self.p.logger.exception("Exception while pinging")
        finally:
            self.p.widgets["ping.do_ping"].enabled(True)
コード例 #18
0
ファイル: network.py プロジェクト: gvsurenderreddy/ovirt-node
 def vendor(self):
     vendor = self.__get_property("ID_VENDOR_FROM_DATABASE")
     if not vendor:
         # fallback method for older udev versions
         try:
             dpath = self.__get_property("DEVPATH")
             pci_addr = dpath.split("/")[-3]
             cmd = ["lspci", "-m", "-s", pci_addr]
             lspci_out = process.pipe(cmd, check=True)
             # shelx needs str not unicode
             vendor = shlex.split(str(lspci_out))[2]
         except:
             self.logger.debug("Failed to fetch vendor name for %s" % dpath,
                               exc_info=True)
     return vendor
コード例 #19
0
 def vendor(self):
     vendor = self.__get_property("ID_VENDOR_FROM_DATABASE")
     if not vendor:
         # fallback method for older udev versions
         try:
             dpath = self.__get_property("DEVPATH")
             pci_addr = dpath.split("/")[-3]
             cmd = ["lspci", "-m", "-s", pci_addr]
             lspci_out = process.pipe(cmd, check=True)
             # shelx needs str not unicode
             vendor = shlex.split(str(lspci_out))[2]
         except:
             self.logger.debug("Failed to fetch vendor name for %s" % dpath,
                               exc_info=True)
     return vendor
コード例 #20
0
    def ip_addresses(self, families=["inet", "inet6"]):
        """Get IP addresses for an ifname

        FIXME NM _client.get_device_by_iface(ifname).get_ip?_config()
        """
        if not self.exists():
            raise UnknownNicError("Unknown network interface: '%s'" %
                                  self.ifname)

        addresses = dict((f, IPAddress(None, None)) for f in families)

        if False:
            # FIXME to hackish to convert addr - is_nm_managed(ifname):
            device = _nm_client.get_device_by_iface(self.ifname)
            LOGGER.debug("Got '%s' for '%s'" % (device, self.ifname))
            if device:
                for family, cfgfunc, sf in [
                    ("inet", device.get_ip4_config, socket.AF_INET),
                    ("inet6", device.get_ip6_config, socket.AF_INET6)
                ]:
                    cfg = cfgfunc()
                    if not cfg:
                        LOGGER.debug("No %s configuration for %s" %
                                     (family, self.ifname))
                        break
                    addrs = cfg.get_addresses()
                    addr = addrs[0].get_address() if len(addrs) > 0 else None
                    addresses[family] = _nm_address_to_str(sf, addr) if addr \
                        else None
            return addresses

        # Fallback
        cmd = "ip -o addr show {ifname}".format(ifname=self.ifname)
        for line in process.pipe(cmd, shell=True).split("\n"):
            matches = re.search(
                "\s(inet[6]?)\s(.+)/([^\s]+)"
                ".*scope ([^\s]+).*", line)
            if matches and matches.groups():
                family, addr, mask, scope = matches.groups()
                if family not in families:
                    continue
                if family == "inet":
                    mask = calcDottedNetmask(mask)
                if scope == "global" or addresses[family].address is None:
                    addresses[family] = IPAddress(addr, mask, scope)

        return addresses
コード例 #21
0
ファイル: network.py プロジェクト: gvsurenderreddy/ovirt-node
    def ip_addresses(self, families=["inet", "inet6"]):
        """Get IP addresses for an ifname

        FIXME NM _client.get_device_by_iface(ifname).get_ip?_config()
        """
        if not self.exists():
            raise UnknownNicError("Unknown network interface: '%s'" %
                                  self.ifname)

        addresses = dict((f, IPAddress(None, None)) for f in families)

        if False:
            # FIXME to hackish to convert addr - is_nm_managed(ifname):
            device = _nm_client.get_device_by_iface(self.ifname)
            LOGGER.debug("Got '%s' for '%s'" % (device, self.ifname))
            if device:
                for family, cfgfunc, sf in [("inet", device.get_ip4_config,
                                             socket.AF_INET),
                                            ("inet6", device.get_ip6_config,
                                             socket.AF_INET6)]:
                    cfg = cfgfunc()
                    if not cfg:
                        LOGGER.debug("No %s configuration for %s" %
                                     (family, self.ifname))
                        break
                    addrs = cfg.get_addresses()
                    addr = addrs[0].get_address() if len(addrs) > 0 else None
                    addresses[family] = _nm_address_to_str(sf, addr) if addr \
                        else None
            return addresses

        # Fallback
        cmd = "ip -o addr show {ifname}".format(ifname=self.ifname)
        for line in process.pipe(cmd, shell=True).split("\n"):
            matches = re.search("\s(inet[6]?)\s(.+)/([^\s]+)"
                                ".*scope ([^\s]+).*", line)
            if matches and matches.groups():
                family, addr, mask, scope = matches.groups()
                if family not in families:
                    continue
                if family == "inet":
                    mask = calcDottedNetmask(mask)
                if scope == "global" or addresses[family].address is None:
                    addresses[family] = IPAddress(addr, mask, scope)

        return addresses
コード例 #22
0
ファイル: system.py プロジェクト: gvsurenderreddy/ovirt-node
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)
コード例 #23
0
ファイル: system.py プロジェクト: xiaowenhao111/ovirt-node
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)
コード例 #24
0
ファイル: network.py プロジェクト: aiminickwong/ovirt_config
    def ip_addresses(self, families=["inet", "inet6"]):
        """Get IP addresses for an iface

        FIXME NM client.get_device_by_iface(iface).get_ip?_config()
        """
        if not self.exists():
            raise UnknownNicError("Unknown network interface: '%s'" %
                                  self.iface)

        #addresses = {f: (None, None) for f in families}
	addresses = dict((f, (None, None)) for f in families)
        if False:
            # FIXME to hackish to convert addr - is_nm_managed(iface):
            device = _nm_client.get_device_by_iface(self.iface)
            LOGGER.debug("Got '%s' for '%s'" % (device, self.iface))
            if device:
                for family, cfgfunc, sf in [("inet", device.get_ip4_config,
                                             socket.AF_INET),
                                            ("inet6", device.get_ip6_config,
                                             socket.AF_INET6)]:
                    cfg = cfgfunc()
                    if not cfg:
                        LOGGER.debug("No %s configuration for %s" %
                                     (family, self.iface))
                        break
                    addrs = cfg.get_addresses()
                    addr = addrs[0].get_address() if len(addrs) > 0 else None
                    addresses[family] = _nm_address_to_str(sf, addr) if addr \
                        else None
            return addresses

        # Fallback
        cmd = "ip -o addr show {iface}".format(iface=self.iface)
        for line in process.pipe(cmd).split("\n"):
            token = re.split("\s+", line)
            if re.search("\sinet[6]?\s", line):
                addr, mask = token[3].split("/")
                family = token[2]
                if family == "inet":
                    mask = calcDottedNetmask(mask)
                addresses[family] = IPAddress(addr, mask)

        return addresses
コード例 #25
0
ファイル: snmp_model.py プロジェクト: gordongong/ovirt-node
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")
コード例 #26
0
ファイル: snmp_model.py プロジェクト: vafaronaghi/ovirt-node
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")
コード例 #27
0
ファイル: rhn_model.py プロジェクト: Zealsathish/ovirt-node
            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"]
                conf = Config()
                if os.path.exists("/etc/sysconfig/rhn/systemid"):
                    conf.unpersist("/etc/sysconfig/rhn/systemid")

                extra_args = ['--force']

                # Don't autosubscribe for now, since it may cause entitlement
                # problems with SAM and Sat6
                # 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)
                    if org:
                        args.append('--org')
                        args.append(org)
                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 cacert.endswith(".pem") and rhntype == "satellite":
                        prefix = "/rhsm"
                    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:
                            conf.persist(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)
                if cacert and not cacert.endswith(".pem") or \
                   rhntype == "satellite":
                    smconf.append('--server.prefix')
                    smconf.append(prefix)
                else:
                    smconf.append('--rhsm.baseurl')
                    if prefix:
                        smconf.append("%s/%s" % (host, prefix))
                    else:
                        smconf.append(host + '/pulp/repos')
                if cacert:
                    smconf.append('--rhsm.repo_ca_cert')
                    smconf.append('/etc/rhsm/ca/candlepin-local.pem')
                try:
                    subprocess.check_call(smconf)
                    conf.persist("/etc/rhsm/rhsm.conf")
                except:
                    raise RuntimeError("Error updating subscription manager \
                                       configuration")
                if profilename:
                    args.append('--name')
                    args.append(profilename)

                if proxy:
                    try:
                        args.append('--proxy')
                        args.append(proxy)
                        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"])
                [Config().unpersist(f) for f in rhsm_configs]
                [Config().unpersist(f) for f in
                 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)

                # This may block if waiting for input with check_output.
                # pipe doesn't block
                smreg_output = process.pipe(args)
                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")

                    if "Organization" in smreg_output:
                        raise RuntimeError("Organization must be specified "
                                           "with Satellite 6")

                    if activationkey:
                        cmd = ["subscription-manager", "auto-attach"]
                        try:
                            subprocess.check_call(cmd)
                        except:
                            raise RuntimeError("Error Setting Auto Attach")
                    else:
                        raise RuntimeError("Registration Failed")
                else:
                    for cfg in rhsm_configs:
                        conf.persist(cfg)
                    conf.persist("/etc/pki/consumer/key.pem")
                    conf.persist("/etc/pki/consumer/cert.pem")
                    self.logger.info("System %s sucessfully registered \
                                      to %s" % (profilename, serverurl))
コード例 #28
0
            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")
コード例 #29
0
ファイル: rhn_model.py プロジェクト: gordongong/ovirt-node
            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))
コード例 #30
0
ファイル: rhn_model.py プロジェクト: gordongong/ovirt-node
            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))