예제 #1
0
파일: register.py 프로젝트: kvaps/vdsm
    def host_uuid(self):
        """
        Determine host UUID and if there is no existing /etc/vdsm/vdsm.id
        it will genereate UUID and save/persist in /etc/vdsm/vdsm.id
        """
        if self.reg_protocol == "legacy":
            # REQUIRED_FOR: Engine 3.3
            # The legacy version uses the format: UUID_MACADDRESS
            self.uuid = getHostUUID(legacy=True)
            self.url_reg += "&vds_unique_id={u}".format(u=self.uuid)
        else:
            # Non legacy version uses the format: UUID
            self.uuid = getHostUUID(legacy=False)
            self.url_reg += "&uniqueId={u}".format(u=self.uuid)

        self.logger.debug("Registration via: {u}".format(u=self.url_reg))

        __VDSM_ID = "/etc/vdsm/vdsm.id"
        if not os.path.exists(__VDSM_ID):
            with open(__VDSM_ID, 'w') as f:
                f.write(self.uuid)

            if utils.isOvirtNode():
                from ovirt.node.utils.fs import Config
                Config().persist(__VDSM_ID)

        self.logger.info("Host UUID: {u}".format(u=self.uuid))
예제 #2
0
    def host_uuid(self):
        """
        Determine host UUID and if there is no existing /etc/vdsm/vdsm.id
        it will genereate UUID and save/persist in /etc/vdsm/vdsm.id
        """

        if self.vdsm_uuid:
            self.uuid = self.vdsm_uuid
        else:
            self.uuid = getHostUUID(legacy=False)

        self.url_reg += "&uniqueId={u}".format(u=self.uuid)

        self.logger.debug("Registration via: {u}".format(u=self.url_reg))

        __VDSM_ID = "/etc/vdsm/vdsm.id"

        if self.vdsm_uuid and os.path.exists(__VDSM_ID):
            if utils.isOvirtNode():
                from ovirt.node.utils.fs import Config
                Config().unpersist(__VDSM_ID)
            os.unlink(__VDSM_ID)

        if not os.path.exists(__VDSM_ID):
            with open(__VDSM_ID, 'w') as f:
                f.write(self.uuid)

            if utils.isOvirtNode():
                from ovirt.node.utils.fs import Config
                Config().persist(__VDSM_ID)

        self.logger.info("Host UUID: {u}".format(u=self.uuid))
예제 #3
0
파일: register.py 프로젝트: fancyKai/vdsm
    def host_uuid(self):
        """
        Determine host UUID and if there is no existing /etc/vdsm/vdsm.id
        it will genereate UUID and save/persist in /etc/vdsm/vdsm.id
        """

        if self.vdsm_uuid:
            self.uuid = self.vdsm_uuid
        else:
            self.uuid = getHostUUID(legacy=False)

        self.url_reg += "&uniqueId={u}".format(u=self.uuid)

        self.logger.debug("Registration via: {u}".format(u=self.url_reg))

        __VDSM_ID = "/etc/vdsm/vdsm.id"

        if self.vdsm_uuid and os.path.exists(__VDSM_ID):
            if utils.isOvirtNode():
                from ovirt.node.utils.fs import Config
                Config().unpersist(__VDSM_ID)
            os.unlink(__VDSM_ID)

        if not os.path.exists(__VDSM_ID):
            with open(__VDSM_ID, 'w') as f:
                f.write(self.uuid)

            if utils.isOvirtNode():
                from ovirt.node.utils.fs import Config
                Config().persist(__VDSM_ID)

        self.logger.info("Host UUID: {u}".format(u=self.uuid))
예제 #4
0
def getUUID():
    """
    Printing host uuid
    """
    hostUUID = getHostUUID(False)
    if hostUUID is None:
        raise RuntimeError('Cannot retrieve host UUID')
    sys.stdout.write(hostUUID)
    return 0
예제 #5
0
def get():
    caps = {}

    caps['kvmEnabled'] = \
        str(config.getboolean('vars', 'fake_kvm_support') or
            os.path.exists('/dev/kvm')).lower()

    cpuInfo = CpuInfo()
    cpuTopology = CpuTopology()
    if config.getboolean('vars', 'report_host_threads_as_cores'):
        caps['cpuCores'] = str(cpuTopology.threads())
    else:
        caps['cpuCores'] = str(cpuTopology.cores())

    caps['cpuThreads'] = str(cpuTopology.threads())
    caps['cpuSockets'] = str(cpuTopology.sockets())
    caps['cpuSpeed'] = cpuInfo.mhz()
    if config.getboolean('vars', 'fake_kvm_support'):
        caps['cpuModel'] = 'Intel(Fake) CPU'
        flags = set(cpuInfo.flags() + ['vmx', 'sse2', 'nx'])
        caps['cpuFlags'] = ','.join(flags) + 'model_486,model_pentium,' \
            'model_pentium2,model_pentium3,model_pentiumpro,model_qemu32,' \
            'model_coreduo,model_core2duo,model_n270,model_Conroe,' \
            'model_Penryn,model_Nehalem,model_Opteron_G1'
    else:
        caps['cpuModel'] = cpuInfo.model()
        caps['cpuFlags'] = ','.join(cpuInfo.flags() +
                                    _getCompatibleCpuModels())

    caps.update(dsaversion.version_info)
    caps.update(netinfo.get())

    try:
        caps['hooks'] = hooks.installed()
    except:
        logging.debug('not reporting hooks', exc_info=True)

    caps['operatingSystem'] = osversion()
    caps['uuid'] = utils.getHostUUID()
    caps['packages2'] = _getKeyPackages()
    caps['emulatedMachines'] = _getEmulatedMachines()
    caps['ISCSIInitiatorName'] = _getIscsiIniName()
    caps['HBAInventory'] = storage.hba.HBAInventory()
    caps['vmTypes'] = ['kvm']

    caps['memSize'] = str(utils.readMemInfo()['MemTotal'] / 1024)
    caps['reservedMem'] = str(config.getint('vars', 'host_mem_reserve') +
                              config.getint('vars', 'extra_mem_reserve'))
    caps['guestOverhead'] = config.get('vars', 'guest_ram_overhead')

    return caps
예제 #6
0
파일: caps.py 프로젝트: ekohl/vdsm
def get():
    caps = {}

    caps["kvmEnabled"] = str(config.getboolean("vars", "fake_kvm_support") or os.path.exists("/dev/kvm")).lower()

    cpuInfo = CpuInfo()
    caps["cpuCores"] = str(cpuInfo.cores())
    caps["cpuSockets"] = str(cpuInfo.sockets())
    caps["cpuSpeed"] = cpuInfo.mhz()
    if config.getboolean("vars", "fake_kvm_support"):
        caps["cpuModel"] = "Intel(Fake) CPU"
        flags = set(cpuInfo.flags() + ["vmx", "sse2", "nx"])
        caps["cpuFlags"] = (
            ",".join(flags) + "model_486,model_pentium,"
            "model_pentium2,model_pentium3,model_pentiumpro,model_qemu32,"
            "model_coreduo,model_core2duo,model_n270,model_Conroe,"
            "model_Penryn,model_Nehalem,model_Opteron_G1"
        )
    else:
        caps["cpuModel"] = cpuInfo.model()
        caps["cpuFlags"] = ",".join(cpuInfo.flags() + _getCompatibleCpuModels())

    caps.update(dsaversion.version_info)
    caps.update(netinfo.get())

    try:
        caps["hooks"] = hooks.installed()
    except:
        logging.debug("not reporting hooks", exc_info=True)

    caps["operatingSystem"] = osversion()
    caps["uuid"] = utils.getHostUUID()
    caps["packages2"] = _getKeyPackages()
    caps["emulatedMachines"] = _getEmulatedMachines()
    caps["ISCSIInitiatorName"] = _getIscsiIniName()
    caps["HBAInventory"] = storage.hba.HBAInventory()
    caps["vmTypes"] = ["kvm"]

    caps["memSize"] = str(utils.readMemInfo()["MemTotal"] / 1024)
    caps["reservedMem"] = str(config.getint("vars", "host_mem_reserve") + config.getint("vars", "extra_mem_reserve"))
    caps["guestOverhead"] = config.get("vars", "guest_ram_overhead")

    return caps
예제 #7
0
파일: caps.py 프로젝트: carriercomm/vdsm
def get():
    targetArch = getTargetArch()

    caps = {}

    caps['kvmEnabled'] = \
        str(config.getboolean('vars', 'fake_kvm_support') or
            os.path.exists('/dev/kvm')).lower()

    cpuInfo = CpuInfo()
    cpuTopology = CpuTopology()
    if config.getboolean('vars', 'report_host_threads_as_cores'):
        caps['cpuCores'] = str(cpuTopology.threads())
    else:
        caps['cpuCores'] = str(cpuTopology.cores())

    caps['cpuThreads'] = str(cpuTopology.threads())
    caps['cpuSockets'] = str(cpuTopology.sockets())
    caps['onlineCpus'] = ','.join(cpuTopology.onlineCpus())
    caps['cpuSpeed'] = cpuInfo.mhz()
    if config.getboolean('vars', 'fake_kvm_support'):
        if targetArch == Architecture.X86_64:
            caps['cpuModel'] = 'Intel(Fake) CPU'

            flagList = ['vmx', 'sse2', 'nx']

            if targetArch == platform.machine():
                flagList += cpuInfo.flags()

            flags = set(flagList)

            caps['cpuFlags'] = ','.join(flags) + ',model_486,model_pentium,' \
                'model_pentium2,model_pentium3,model_pentiumpro,' \
                'model_qemu32,model_coreduo,model_core2duo,model_n270,' \
                'model_Conroe,model_Penryn,model_Nehalem,model_Opteron_G1'
        elif targetArch in Architecture.POWER:
            caps['cpuModel'] = 'POWER 8 (fake)'
            caps['cpuFlags'] = 'powernv,model_power8'
        else:
            raise RuntimeError('Unsupported architecture: %s' % targetArch)
    else:
        caps['cpuModel'] = cpuInfo.model()
        caps['cpuFlags'] = ','.join(cpuInfo.flags() +
                                    _getCompatibleCpuModels())

    caps.update(_getVersionInfo())
    caps.update(netinfo.get())
    _report_network_qos(caps)

    try:
        caps['hooks'] = hooks.installed()
    except:
        logging.debug('not reporting hooks', exc_info=True)

    caps['operatingSystem'] = osversion()
    caps['uuid'] = utils.getHostUUID()
    caps['packages2'] = _getKeyPackages()
    caps['emulatedMachines'] = _getEmulatedMachines(targetArch)
    caps['ISCSIInitiatorName'] = _getIscsiIniName()
    caps['HBAInventory'] = storage.hba.HBAInventory()
    caps['vmTypes'] = ['kvm']

    caps['memSize'] = str(utils.readMemInfo()['MemTotal'] / 1024)
    caps['reservedMem'] = str(config.getint('vars', 'host_mem_reserve') +
                              config.getint('vars', 'extra_mem_reserve'))
    caps['guestOverhead'] = config.get('vars', 'guest_ram_overhead')

    # Verify that our libvirt supports virtio RNG (since 10.0.2-31)
    libvirtVer = LooseVersion(
        '-'.join((caps['packages2']['libvirt']['version'],
                  caps['packages2']['libvirt']['release'])))
    requiredVer = LooseVersion('0.10.2-31')

    if libvirtVer >= requiredVer:
        caps['rngSources'] = _getRngSources()
    else:
        logging.debug('VirtioRNG DISABLED: libvirt version %s required >= %s',
                      libvirtVer, requiredVer)

    caps['numaNodes'] = getNumaTopology()
    caps['numaNodeDistance'] = getNumaNodeDistance()
    caps['autoNumaBalancing'] = getAutoNumaBalancingInfo()

    caps['selinux'] = _getSELinux()

    liveSnapSupported = _getLiveSnapshotSupport(targetArch)
    if liveSnapSupported is not None:
        caps['liveSnapshot'] = str(liveSnapSupported).lower()
    caps['liveMerge'] = str(getLiveMergeSupport()).lower()
    caps['kdumpStatus'] = _getKdumpStatus()

    caps['hostdevPassthrough'] = str(_getHostdevPassthorughSupport()).lower()
    caps['additionalFeatures'] = []
    if _glusterEnabled:
        caps['additionalFeatures'].extend(glusterAdditionalFeatures())
    return caps
예제 #8
0
def get():
    targetArch = getTargetArch()

    caps = {}

    caps['kvmEnabled'] = \
        str(config.getboolean('vars', 'fake_kvm_support') or
            os.path.exists('/dev/kvm')).lower()

    cpuInfo = CpuInfo()
    cpuTopology = CpuTopology()
    if config.getboolean('vars', 'report_host_threads_as_cores'):
        caps['cpuCores'] = str(cpuTopology.threads())
    else:
        caps['cpuCores'] = str(cpuTopology.cores())

    caps['cpuThreads'] = str(cpuTopology.threads())
    caps['cpuSockets'] = str(cpuTopology.sockets())
    caps['onlineCpus'] = ','.join(cpuTopology.onlineCpus())
    caps['cpuSpeed'] = cpuInfo.mhz()
    if config.getboolean('vars', 'fake_kvm_support'):
        if targetArch == Architecture.X86_64:
            caps['cpuModel'] = 'Intel(Fake) CPU'

            flagList = ['vmx', 'sse2', 'nx']

            if targetArch == platform.machine():
                flagList += cpuInfo.flags()

            flags = set(flagList)

            caps['cpuFlags'] = ','.join(flags) + ',model_486,model_pentium,' \
                'model_pentium2,model_pentium3,model_pentiumpro,' \
                'model_qemu32,model_coreduo,model_core2duo,model_n270,' \
                'model_Conroe,model_Penryn,model_Nehalem,model_Opteron_G1'
        elif targetArch in Architecture.POWER:
            caps['cpuModel'] = 'POWER 8 (fake)'
            caps['cpuFlags'] = 'powernv,model_power8'
        else:
            raise RuntimeError('Unsupported architecture: %s' % targetArch)
    else:
        caps['cpuModel'] = cpuInfo.model()
        caps['cpuFlags'] = ','.join(cpuInfo.flags() +
                                    _getCompatibleCpuModels())

    caps.update(_getVersionInfo())
    caps.update(netinfo.get())
    _report_legacy_bondings(caps)
    _report_network_qos(caps)

    try:
        caps['hooks'] = hooks.installed()
    except:
        logging.debug('not reporting hooks', exc_info=True)

    caps['operatingSystem'] = osversion()
    caps['uuid'] = utils.getHostUUID()
    caps['packages2'] = _getKeyPackages()
    caps['emulatedMachines'] = _getEmulatedMachines(targetArch)
    caps['ISCSIInitiatorName'] = _getIscsiIniName()
    caps['HBAInventory'] = storage.hba.HBAInventory()
    caps['vmTypes'] = ['kvm']

    caps['memSize'] = str(utils.readMemInfo()['MemTotal'] / 1024)
    caps['reservedMem'] = str(
        config.getint('vars', 'host_mem_reserve') +
        config.getint('vars', 'extra_mem_reserve'))
    caps['guestOverhead'] = config.get('vars', 'guest_ram_overhead')

    # Verify that our libvirt supports virtio RNG (since 10.0.2-31)
    libvirtVer = LooseVersion('-'.join(
        (caps['packages2']['libvirt']['version'],
         caps['packages2']['libvirt']['release'])))
    requiredVer = LooseVersion('0.10.2-31')

    if libvirtVer >= requiredVer:
        caps['rngSources'] = _getRngSources()
    else:
        logging.debug('VirtioRNG DISABLED: libvirt version %s required >= %s',
                      libvirtVer, requiredVer)

    caps['numaNodes'] = getNumaTopology()
    caps['numaNodeDistance'] = getNumaNodeDistance()
    caps['autoNumaBalancing'] = getAutoNumaBalancingInfo()

    caps['selinux'] = _getSELinux()

    liveSnapSupported = _getLiveSnapshotSupport(targetArch)
    if liveSnapSupported is not None:
        caps['liveSnapshot'] = str(liveSnapSupported).lower()
    caps['liveMerge'] = str(getLiveMergeSupport()).lower()
    caps['kdumpStatus'] = _getKdumpStatus()

    caps['hostdevPassthrough'] = str(_getHostdevPassthorughSupport()).lower()

    return caps
예제 #9
0
파일: caps.py 프로젝트: vinzenz/vdsm
def get():
    targetArch = getTargetArch()

    caps = {}

    caps['kvmEnabled'] = \
        str(config.getboolean('vars', 'fake_kvm_support') or
            os.path.exists('/dev/kvm')).lower()

    cpuInfo = CpuInfo()
    cpuTopology = CpuTopology()
    if config.getboolean('vars', 'report_host_threads_as_cores'):
        caps['cpuCores'] = str(cpuTopology.threads())
    else:
        caps['cpuCores'] = str(cpuTopology.cores())

    caps['cpuThreads'] = str(cpuTopology.threads())
    caps['cpuSockets'] = str(cpuTopology.sockets())
    caps['cpuSpeed'] = cpuInfo.mhz()
    if config.getboolean('vars', 'fake_kvm_support'):
        if targetArch == Architecture.X86_64:
            caps['cpuModel'] = 'Intel(Fake) CPU'

            flagList = ['vmx', 'sse2', 'nx']

            if targetArch == platform.machine():
                flagList += cpuInfo.flags()

            flags = set(flagList)

            caps['cpuFlags'] = ','.join(flags) + ',model_486,model_pentium,' \
                'model_pentium2,model_pentium3,model_pentiumpro,' \
                'model_qemu32,model_coreduo,model_core2duo,model_n270,' \
                'model_Conroe,model_Penryn,model_Nehalem,model_Opteron_G1'
        elif targetArch == Architecture.PPC64:
            caps['cpuModel'] = 'POWER 7 (fake)'
            caps['cpuFlags'] = 'powernv,model_POWER7_v2.3'
        else:
            raise RuntimeError('Unsupported architecture: %s' % targetArch)
    else:
        caps['cpuModel'] = cpuInfo.model()
        caps['cpuFlags'] = ','.join(cpuInfo.flags() +
                                    _getCompatibleCpuModels())

    caps.update(_getVersionInfo())
    caps.update(netinfo.get())
    _report_legacy_bondings(caps)

    try:
        caps['hooks'] = hooks.installed()
    except:
        logging.debug('not reporting hooks', exc_info=True)

    caps['operatingSystem'] = osversion()
    caps['uuid'] = utils.getHostUUID()
    caps['packages2'] = _getKeyPackages()
    caps['emulatedMachines'] = _getEmulatedMachines(targetArch)
    caps['ISCSIInitiatorName'] = _getIscsiIniName()
    caps['HBAInventory'] = storage.hba.HBAInventory()
    caps['vmTypes'] = ['kvm']

    caps['memSize'] = str(utils.readMemInfo()['MemTotal'] / 1024)
    caps['reservedMem'] = str(config.getint('vars', 'host_mem_reserve') +
                              config.getint('vars', 'extra_mem_reserve'))
    caps['guestOverhead'] = config.get('vars', 'guest_ram_overhead')
    caps['rngSources'] = _getRngSources()
    caps['numaNodes'] = getNumaTopology()
    caps['numaNodeDistance'] = getNumaNodeDistance()
    caps['autoNumaBalancing'] = getAutoNumaBalancingInfo()

    caps['selinux'] = _getSELinux()

    liveSnapSupported = _getLiveSnapshotSupport(targetArch)
    if liveSnapSupported is not None:
        caps['liveSnapshot'] = str(liveSnapSupported).lower()
    caps['kdumpStatus'] = _getKdumpStatus()

    return caps
예제 #10
0
파일: caps.py 프로젝트: fancyKai/vdsm
def get():
    targetArch = getTargetArch()

    caps = {}

    caps["kvmEnabled"] = str(config.getboolean("vars", "fake_kvm_support") or os.path.exists("/dev/kvm")).lower()

    cpuInfo = CpuInfo()
    cpuTopology = CpuTopology()
    if config.getboolean("vars", "report_host_threads_as_cores"):
        caps["cpuCores"] = str(cpuTopology.threads())
    else:
        caps["cpuCores"] = str(cpuTopology.cores())

    caps["cpuThreads"] = str(cpuTopology.threads())
    caps["cpuSockets"] = str(cpuTopology.sockets())
    caps["onlineCpus"] = ",".join(cpuTopology.onlineCpus())
    caps["cpuSpeed"] = cpuInfo.mhz()
    if config.getboolean("vars", "fake_kvm_support"):
        if targetArch == Architecture.X86_64:
            caps["cpuModel"] = "Intel(Fake) CPU"

            flagList = ["vmx", "sse2", "nx"]

            if targetArch == platform.machine():
                flagList += cpuInfo.flags()

            flags = set(flagList)

            caps["cpuFlags"] = (
                ",".join(flags) + ",model_486,model_pentium,"
                "model_pentium2,model_pentium3,model_pentiumpro,"
                "model_qemu32,model_coreduo,model_core2duo,model_n270,"
                "model_Conroe,model_Penryn,model_Nehalem,model_Opteron_G1"
            )
        elif targetArch in Architecture.POWER:
            caps["cpuModel"] = "POWER 8 (fake)"
            caps["cpuFlags"] = "powernv,model_POWER8"
        else:
            raise RuntimeError("Unsupported architecture: %s" % targetArch)
    else:
        caps["cpuModel"] = cpuInfo.model()
        caps["cpuFlags"] = ",".join(cpuInfo.flags() + _getCompatibleCpuModels())

    caps.update(_getVersionInfo())
    caps.update(netinfo.get())

    try:
        caps["hooks"] = hooks.installed()
    except:
        logging.debug("not reporting hooks", exc_info=True)

    caps["operatingSystem"] = osversion()
    caps["uuid"] = utils.getHostUUID()
    caps["packages2"] = _getKeyPackages()
    caps["emulatedMachines"] = _getEmulatedMachines(targetArch)
    caps["ISCSIInitiatorName"] = _getIscsiIniName()
    caps["HBAInventory"] = storage.hba.HBAInventory()
    caps["vmTypes"] = ["kvm"]

    caps["memSize"] = str(utils.readMemInfo()["MemTotal"] / 1024)
    caps["reservedMem"] = str(config.getint("vars", "host_mem_reserve") + config.getint("vars", "extra_mem_reserve"))
    caps["guestOverhead"] = config.get("vars", "guest_ram_overhead")

    # Verify that our libvirt supports virtio RNG (since 10.0.2-31)
    requiredVer = LooseVersion("0.10.2-31")
    if "libvirt" not in caps["packages2"]:
        libvirtVer = None
    else:
        libvirtVer = LooseVersion(
            "-".join((caps["packages2"]["libvirt"]["version"], caps["packages2"]["libvirt"]["release"]))
        )

    if libvirtVer is None:
        logging.debug("VirtioRNG DISABLED: unknown libvirt version")
    elif libvirtVer < requiredVer:
        logging.debug("VirtioRNG DISABLED: libvirt version %s required >= %s", libvirtVer, requiredVer)
    else:
        caps["rngSources"] = _getRngSources()

    caps["numaNodes"] = getNumaTopology()
    caps["numaNodeDistance"] = getNumaNodeDistance()
    caps["autoNumaBalancing"] = getAutoNumaBalancingInfo()

    caps["selinux"] = _getSELinux()

    liveSnapSupported = _getLiveSnapshotSupport(targetArch)
    if liveSnapSupported is not None:
        caps["liveSnapshot"] = str(liveSnapSupported).lower()
    caps["liveMerge"] = str(getLiveMergeSupport()).lower()
    caps["kdumpStatus"] = _getKdumpStatus()

    caps["hostdevPassthrough"] = str(_getHostdevPassthorughSupport()).lower()
    caps["additionalFeatures"] = []
    if _glusterEnabled:
        caps["additionalFeatures"].extend(glusterAdditionalFeatures())
    return caps
예제 #11
0
def main():
    """
    Register node to engine
    """

    _DEFAULT_NODE_MANAGEMENT_PORT = 54321

    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter,
        description='Tool to register node to oVirt Engine',
        epilog='Example of use:\n%(prog)s '
        '--authorize-engine-ssh-key '
        '--url https://ovirtengine.localdomain:443 '
        '--fingerprint DC:B9:67:35:60:FC:29:E4:C8:03:4E:5:7A:0D '
        '--node-management-address 10.10.1.1 '
        '--node-management-port 54321')

    parser.add_argument(
        '--authorize-engine-ssh-key',
        action='store_true',
        help='Add ovirt engine public ssh key to node authorized keys',
    )

    parser.add_argument(
        '--fingerprint',
        help="Fingerprint to be validate against engine web CA")

    parser.add_argument(
        '--hostname',
        help="Speficy the human-readable name of the node being registered")

    parser.add_argument(
        '--skip-fingerprint',
        action='store_true',
        help='Skip fingerprint check',
    )

    parser.add_argument(
        '--node-management-address',
        help="Node IP address to be registered",
    )

    parser.add_argument(
        '--node-management-port',
        help="Node management port",
    )

    parser.add_argument('--node-uuid', help="Provide an explicit host uuid")

    parser.add_argument('--url', help="Engine URL", required=True)
    parser.add_argument(
        '--verbose',
        action='store_true',
        help="verbose mode, set logging to DEBUG instead of ERROR")
    args = parser.parse_args()

    url = urlparse.urlparse(args.url)
    url_port = url.port

    if url.scheme == "https" and url_port is None:
        url_port = 443
    elif url.scheme == "http" and url_port is None:
        url_port = 80

    if url.scheme == "https" and args.fingerprint:
        engine_cert = ssl.get_server_certificate((url.hostname, int(url_port)))

    if not args.skip_fingerprint and args.fingerprint is None:
        raise RuntimeError('You must use --fingerprint or --skip-fingerprint')

    if args.verbose:
        logging.setLevel(logging.DEBUG)

    if not args.skip_fingerprint and url.scheme == "https":
        cert_fingerprint = _calculate_fingerprint(engine_cert)
        if not args.fingerprint.lower() == cert_fingerprint.lower():
            str_error = "Fingerprint {0} doesn't match " \
                "server's fingerprint!".format(
                    args.fingerprint.lower(),
                )
            _LOG.debug(str_error)
            raise RuntimeError(str_error)

    if args.fingerprint and url.scheme == "http":
        _LOG.debug("Skipping fingerprint check, user provided http url")

    if args.authorize_engine_ssh_key:
        key = _get_remote_public_ssh_key(args.url)
        if key is not None:
            _add_authorized_ssh_key(key)
        else:
            _LOG.error("Cannot download public ssh key from %s" % args.url)

    node_uuid = args.node_uuid
    if node_uuid is None:
        node_uuid = getHostUUID(False)
        if node_uuid is None:
            raise RuntimeError('Cannot retrieve host UUID')

    node_hostname = args.hostname
    if node_hostname is None:
        node_hostname = socket.gethostname()

    management_port = args.node_management_port
    if management_port is None:
        management_port = _DEFAULT_NODE_MANAGEMENT_PORT

    node_management_address = args.node_management_address
    if node_management_address is None:
        route = routeGet([urlparse.urlparse(args.url).hostname])[0]
        node_management_address = Route.fromText(route).src

    if register_node(args.url, node_hostname, node_management_address,
                     int(management_port), node_uuid):
        _LOG.info("Registration is completed: url: %s, hostname: %s "
                  "management address: %s management port: %s" %
                  (args.url, node_hostname, node_management_address,
                   management_port))
    else:
        raise RuntimeError('Cannot complete the registration')
예제 #12
0
def main():
    """
    Register node to engine
    """

    _DEFAULT_NODE_MANAGEMENT_PORT = 54321

    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter,
        description="Tool to register node to oVirt Engine",
        epilog="Example of use:\n%(prog)s "
        "--authorize-engine-ssh-key "
        "--url https://ovirtengine.localdomain:443 "
        "--fingerprint DC:B9:67:35:60:FC:29:E4:C8:03:4E:5:7A:0D "
        "--node-management-address 10.10.1.1 "
        "--node-management-port 54321",
    )

    parser.add_argument(
        "--authorize-engine-ssh-key",
        action="store_true",
        help="Add ovirt engine public ssh key to node authorized keys",
    )

    parser.add_argument("--fingerprint", help="Fingerprint to be validate against engine web CA")

    parser.add_argument("--hostname", help="Speficy the human-readable name of the node being registered")

    parser.add_argument("--skip-fingerprint", action="store_true", help="Skip fingerprint check")

    parser.add_argument("--node-management-address", help="Node IP address to be registered")

    parser.add_argument("--node-management-port", help="Node management port")

    parser.add_argument("--node-uuid", help="Provide an explicit host uuid")

    parser.add_argument("--url", help="Engine URL", required=True)
    parser.add_argument("--verbose", action="store_true", help="verbose mode, set logging to DEBUG instead of ERROR")
    args = parser.parse_args()

    url = urlparse.urlparse(args.url)
    url_port = url.port

    if url.scheme == "https" and url_port is None:
        url_port = 443
    elif url.scheme == "http" and url_port is None:
        url_port = 80

    if url.scheme == "https" and args.fingerprint:
        engine_cert = ssl.get_server_certificate((url.hostname, int(url_port)))

    if not args.skip_fingerprint and args.fingerprint is None:
        raise RuntimeError("You must use --fingerprint or --skip-fingerprint")

    if args.verbose:
        logging.setLevel(logging.DEBUG)

    if not args.skip_fingerprint and url.scheme == "https":
        cert_fingerprint = _calculate_fingerprint(engine_cert)
        if not args.fingerprint.lower() == cert_fingerprint.lower():
            str_error = "Fingerprint {0} doesn't match " "server's fingerprint!".format(args.fingerprint.lower())
            _LOG.debug(str_error)
            raise RuntimeError(str_error)

    if args.fingerprint and url.scheme == "http":
        _LOG.debug("Skipping fingerprint check, user provided http url")

    if args.authorize_engine_ssh_key:
        key = _get_remote_public_ssh_key(args.url)
        if key is not None:
            _add_authorized_ssh_key(key)
        else:
            _LOG.error("Cannot download public ssh key from %s" % args.url)

    node_uuid = args.node_uuid
    if node_uuid is None:
        node_uuid = getHostUUID(False)
        if node_uuid is None:
            raise RuntimeError("Cannot retrieve host UUID")

    node_hostname = args.hostname
    if node_hostname is None:
        node_hostname = socket.gethostname()

    management_port = args.node_management_port
    if management_port is None:
        management_port = _DEFAULT_NODE_MANAGEMENT_PORT

    node_management_address = args.node_management_address
    if node_management_address is None:
        route = routeGet([urlparse.urlparse(args.url).hostname])[0]
        node_management_address = Route.fromText(route).src

    if register_node(args.url, node_hostname, node_management_address, int(management_port), node_uuid):
        _LOG.info(
            "Registration is completed: url: %s, hostname: %s "
            "management address: %s management port: %s"
            % (args.url, node_hostname, node_management_address, management_port)
        )
    else:
        raise RuntimeError("Cannot complete the registration")