Example #1
0
 def testGetEmpty(self):
     result = {}
     result.update(netinfo.get())
     self.assertEqual(result['networks'], {})
     self.assertEqual(result['bridges'], {})
     self.assertEqual(result['nics'], {})
     self.assertEqual(result['bondings'], {})
     self.assertEqual(result['vlans'], {})
Example #2
0
 def testGetEmpty(self):
     result = {}
     result.update(get())
     self.assertEqual(result['networks'], {})
     self.assertEqual(result['bridges'], {})
     self.assertEqual(result['nics'], {})
     self.assertEqual(result['bondings'], {})
     self.assertEqual(result['vlans'], {})
Example #3
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
Example #4
0
File: caps.py Project: 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
Example #5
0
 def testGetNonExistantBridgeInfo(self):
     # Getting info of non existing bridge should not raise an exception,
     # just log a traceback. If it raises an exception the test will fail as
     # it should.
     netinfo.get()
Example #6
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_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
Example #7
0
 def testGetNonExistantBridgeInfo(self):
     # Getting info of non existing bridge should not raise an exception,
     # just log a traceback. If it raises an exception the test will fail as
     # it should.
     get()
Example #8
0
def setupNetworks(networks, bondings, **options):
    """Add/Edit/Remove configuration for networks and bondings.

    Params:
        networks - dict of key=network, value=attributes
            where 'attributes' is a dict with the following optional items:
                        vlan=<id>
                        bonding="<name>" | nic="<name>"
                        (bonding and nics are mutually exclusive)
                        ipaddr="<ipv4>"
                        netmask="<ipv4>"
                        gateway="<ipv4>"
                        bootproto="..."
                        ipv6addr="<ipv6>[/<prefixlen>]"
                        ipv6gateway="<ipv6>"
                        ipv6autoconf="0|1"
                        dhcpv6="0|1"
                        defaultRoute=True|False
                        (other options will be passed to the config file AS-IS)
                        -- OR --
                        remove=True (other attributes can't be specified)

        bondings - dict of key=bonding, value=attributes
            where 'attributes' is a dict with the following optional items:
                        nics=["<nic1>" , "<nic2>", ...]
                        options="<bonding-options>"
                        -- OR --
                        remove=True (other attributes can't be specified)

        options - dict of options, such as:
                        force=0|1
                        connectivityCheck=0|1
                        connectivityTimeout=<int>
                        _inRollback=True|False

    Notes:
        When you edit a network that is attached to a bonding, it's not
        necessary to re-specify the bonding (you need only to note
        the attachment in the network's attributes). Similarly, if you edit
        a bonding, it's not necessary to specify its networks.
    """
    logger = logging.getLogger("setupNetworks")

    libvirt_nets = netinfo.networks()
    _netinfo = netinfo.NetInfo(_netinfo=netinfo.get(
        netinfo._libvirtNets2vdsm(libvirt_nets)))
    networksAdded = set()

    logger.debug("Setting up network according to configuration: "
                 "networks:%r, bondings:%r, options:%r" % (networks,
                                                           bondings, options))

    force = options.get('force', False)
    if not utils.tobool(force):
        logging.debug("Validating configuration")
        _validateNetworkSetup(dict(networks), dict(bondings))

    results = hooks.before_network_setup(_buildSetupHookDict(networks,
                                                             bondings,
                                                             options))

    # gather any changes that could have been done by the hook scripts
    networks = results['request']['networks']
    bondings = results['request']['bondings']
    options = results['request']['options']

    logger.debug("Applying...")
    with ConfiguratorClass(options.get('_inRollback', False)) as configurator:
        # Remove edited networks and networks with 'remove' attribute
        for network, networkAttrs in networks.items():
            if network in _netinfo.networks:
                logger.debug("Removing network %r", network)
                delNetwork(network, configurator=configurator, force=force,
                           implicitBonding=False, _netinfo=_netinfo)
                if 'remove' in networkAttrs:
                    del networks[network]
                    del libvirt_nets[network]
                _netinfo.updateDevices()
                del _netinfo.networks[network]
            elif network in libvirt_nets:
                # If the network was not in _netinfo but is in the networks
                # returned by libvirt, it means that we are dealing with
                # a broken network.
                logger.debug('Removing broken network %r', network)
                _delBrokenNetwork(network, libvirt_nets[network],
                                  configurator=configurator)
                if 'remove' in networkAttrs:
                    del networks[network]
                    del libvirt_nets[network]
                _netinfo.updateDevices()
            elif 'remove' in networkAttrs:
                raise ConfigNetworkError(ne.ERR_BAD_BRIDGE, "Cannot delete "
                                         "network %r: It doesn't exist in the "
                                         "system" % network)
            else:
                networksAdded.add(network)

        _handleBondings(bondings, configurator)

        # We need to use the newest host info
        _netinfo.updateDevices()
        for network, networkAttrs in networks.iteritems():
            d = dict(networkAttrs)
            if 'bonding' in d:
                d.update(_buildBondOptions(d['bonding'], bondings, _netinfo))
            else:
                d['nics'] = [d.pop('nic')] if 'nic' in d else []
            d['force'] = force

            logger.debug("Adding network %r", network)
            try:
                addNetwork(network, configurator=configurator,
                           implicitBonding=True, _netinfo=_netinfo, **d)
            except ConfigNetworkError as cne:
                if cne.errCode == ne.ERR_FAILED_IFUP:
                    logger.debug("Adding network %r failed. Running "
                                 "orphan-devices cleanup", network)
                    _emergencyNetworkCleanup(network, networkAttrs,
                                             configurator)
                raise

            _netinfo.updateDevices()  # Things like a bond mtu can change

        if utils.tobool(options.get('connectivityCheck', True)):
            logger.debug('Checking connectivity...')
            if not clientSeen(int(options.get('connectivityTimeout',
                                  CONNECTIVITY_TIMEOUT_DEFAULT))):
                logger.info('Connectivity check failed, rolling back')
                for network in networksAdded:
                    # If the new added network was created on top of
                    # existing bond, we need to keep the bond on rollback
                    # flow, else we will break the new created bond.
                    delNetwork(network, force=True,
                               implicitBonding=networks[network].
                               get('bonding') in bondings)
                raise ConfigNetworkError(ne.ERR_LOST_CONNECTION,
                                         'connectivity check failed')

    hooks.after_network_setup(_buildSetupHookDict(networks, bondings, options))
Example #9
0
def setupNetworks(networks, bondings, **options):
    """Add/Edit/Remove configuration for networks and bondings.

    Params:
        networks - dict of key=network, value=attributes
            where 'attributes' is a dict with the following optional items:
                        vlan=<id>
                        bonding="<name>" | nic="<name>"
                        (bonding and nics are mutually exclusive)
                        ipaddr="<ipv4>"
                        netmask="<ipv4>"
                        gateway="<ipv4>"
                        bootproto="..."
                        ipv6addr="<ipv6>[/<prefixlen>]"
                        ipv6gateway="<ipv6>"
                        ipv6autoconf="0|1"
                        dhcpv6="0|1"
                        defaultRoute=True|False
                        (other options will be passed to the config file AS-IS)
                        -- OR --
                        remove=True (other attributes can't be specified)

        bondings - dict of key=bonding, value=attributes
            where 'attributes' is a dict with the following optional items:
                        nics=["<nic1>" , "<nic2>", ...]
                        options="<bonding-options>"
                        -- OR --
                        remove=True (other attributes can't be specified)

        options - dict of options, such as:
                        force=0|1
                        connectivityCheck=0|1
                        connectivityTimeout=<int>
                        _inRollback=True|False

    Notes:
        When you edit a network that is attached to a bonding, it's not
        necessary to re-specify the bonding (you need only to note
        the attachment in the network's attributes). Similarly, if you edit
        a bonding, it's not necessary to specify its networks.
    """
    logger = logging.getLogger("setupNetworks")

    libvirt_nets = netinfo.networks()
    _netinfo = netinfo.NetInfo(_netinfo=netinfo.get(
        netinfo._libvirtNets2vdsm(libvirt_nets)))
    networksAdded = set()

    logger.debug("Setting up network according to configuration: "
                 "networks:%r, bondings:%r, options:%r" % (networks,
                                                           bondings, options))

    force = options.get('force', False)
    if not utils.tobool(force):
        logging.debug("Validating configuration")
        _validateNetworkSetup(dict(networks), dict(bondings))

    results = hooks.before_network_setup(_buildSetupHookDict(networks,
                                                             bondings,
                                                             options))

    # gather any changes that could have been done by the hook scripts
    networks = results['request']['networks']
    bondings = results['request']['bondings']
    options = results['request']['options']

    logger.debug("Applying...")
    with ConfiguratorClass(options.get('_inRollback', False)) as configurator:
        # Remove edited networks and networks with 'remove' attribute
        for network, networkAttrs in networks.items():
            if network in _netinfo.networks:
                logger.debug("Removing network %r" % network)
                delNetwork(network, configurator=configurator, force=force,
                           implicitBonding=False, _netinfo=_netinfo)
                if 'remove' in networkAttrs:
                    del networks[network]
                    del libvirt_nets[network]
                _netinfo.updateDevices()
                del _netinfo.networks[network]
            elif network in libvirt_nets:
                # If the network was not in _netinfo but is in the networks
                # returned by libvirt, it means that we are dealing with
                # a broken network.
                logger.debug('Removing broken network %r' % network)
                _delBrokenNetwork(network, libvirt_nets[network],
                                  configurator=configurator)
                if 'remove' in networkAttrs:
                    del networks[network]
                    del libvirt_nets[network]
                _netinfo.updateDevices()
            elif 'remove' in networkAttrs:
                raise ConfigNetworkError(ne.ERR_BAD_BRIDGE, "Cannot delete "
                                         "network %r: It doesn't exist in the "
                                         "system" % network)
            else:
                networksAdded.add(network)

        _handleBondings(bondings, configurator)

        # We need to use the newest host info
        _netinfo.updateDevices()
        for network, networkAttrs in networks.iteritems():
            d = dict(networkAttrs)
            if 'bonding' in d:
                d.update(_buildBondOptions(d['bonding'], bondings, _netinfo))
            else:
                d['nics'] = [d.pop('nic')] if 'nic' in d else []
            d['force'] = force

            logger.debug("Adding network %r" % network)
            addNetwork(network, configurator=configurator,
                       implicitBonding=True, _netinfo=_netinfo, **d)
            _netinfo.updateDevices()  # Things like a bond mtu can change

        if utils.tobool(options.get('connectivityCheck', True)):
            logger.debug('Checking connectivity...')
            if not clientSeen(int(options.get('connectivityTimeout',
                                  CONNECTIVITY_TIMEOUT_DEFAULT))):
                logger.info('Connectivity check failed, rolling back')
                for network in networksAdded:
                    # If the new added network was created on top of
                    # existing bond, we need to keep the bond on rollback
                    # flow, else we will break the new created bond.
                    delNetwork(network, force=True,
                               implicitBonding=networks[network].
                               get('bonding') in bondings)
                raise ConfigNetworkError(ne.ERR_LOST_CONNECTION,
                                         'connectivity check failed')

    hooks.after_network_setup(_buildSetupHookDict(networks, bondings, options))
Example #10
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
Example #11
0
File: caps.py Project: 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
Example #12
0
File: api.py Project: Caez83/vdsm
def setupNetworks(networks, bondings, **options):
    """Add/Edit/Remove configuration for networks and bondings.

    Params:
        networks - dict of key=network, value=attributes
            where 'attributes' is a dict with the following optional items:
                        vlan=<id>
                        bonding="<name>" | nic="<name>"
                        (bonding and nics are mutually exclusive)
                        ipaddr="<ipv4>"
                        netmask="<ipv4>"
                        gateway="<ipv4>"
                        bootproto="..."
                        ipv6addr="<ipv6>[/<prefixlen>]"
                        ipv6gateway="<ipv6>"
                        ipv6autoconf="0|1"
                        dhcpv6="0|1"
                        defaultRoute=True|False
                        (other options will be passed to the config file AS-IS)
                        -- OR --
                        remove=True (other attributes can't be specified)

        bondings - dict of key=bonding, value=attributes
            where 'attributes' is a dict with the following optional items:
                        nics=["<nic1>" , "<nic2>", ...]
                        options="<bonding-options>"
                        -- OR --
                        remove=True (other attributes can't be specified)

        options - dict of options, such as:
                        force=0|1
                        connectivityCheck=0|1
                        connectivityTimeout=<int>
                        _inRollback=True|False

    Notes:
        When you edit a network that is attached to a bonding, it's not
        necessary to re-specify the bonding (you need only to note
        the attachment in the network's attributes). Similarly, if you edit
        a bonding, it's not necessary to specify its networks.
    """
    logger = logging.getLogger("setupNetworks")

    logger.debug("Setting up network according to configuration: "
                 "networks:%r, bondings:%r, options:%r" % (networks,
                                                           bondings, options))

    force = options.get('force', False)
    if not utils.tobool(force):
        logging.debug("Validating configuration")
        _validateNetworkSetup(networks, bondings)

    bondings, networks, options = _apply_hook(bondings, networks, options)

    libvirt_nets = netinfo.networks()
    _netinfo = netinfo.NetInfo(_netinfo=netinfo.get(
        netinfo.libvirtNets2vdsm(libvirt_nets)))
    connectivity_check_networks = set()

    logger.debug("Applying...")
    in_rollback = options.get('_inRollback', False)
    with ConfiguratorClass(in_rollback) as configurator:
        # Remove edited networks and networks with 'remove' attribute
        for network, attrs in networks.items():
            if network in _netinfo.networks:
                logger.debug("Removing network %r", network)
                running_conf = configurator.runningConfig.networks.get(network)
                keep_bridge = _should_keep_bridge(
                    network_attrs=attrs,
                    currently_bridged=_netinfo.networks[network]['bridged'],
                    network_running_config=running_conf
                )

                _delNetwork(network, configurator=configurator, force=force,
                            implicitBonding=False, _netinfo=_netinfo,
                            keep_bridge=keep_bridge)
                _netinfo.updateDevices()
                del _netinfo.networks[network]
            elif network in libvirt_nets:
                # If the network was not in _netinfo but is in the networks
                # returned by libvirt, it means that we are dealing with
                # a broken network.
                logger.debug('Removing broken network %r', network)
                _delBrokenNetwork(network, libvirt_nets[network],
                                  configurator=configurator)
                _netinfo.updateDevices()
            elif 'remove' in attrs:
                raise ConfigNetworkError(ne.ERR_BAD_BRIDGE, "Cannot delete "
                                         "network %r: It doesn't exist in the "
                                         "system" % network)
            else:
                connectivity_check_networks.add(network)

        _handleBondings(bondings, configurator, in_rollback)

        _add_missing_networks(configurator, networks, bondings, force,
                              logger, _netinfo)

        _check_connectivity(connectivity_check_networks, networks, bondings,
                            options, logger)

    hooks.after_network_setup(_buildSetupHookDict(networks, bondings, options))
Example #13
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())

    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
Example #14
0
def setupNetworks(networks, bondings, **options):
    """Add/Edit/Remove configuration for networks and bondings.

    Params:
        networks - dict of key=network, value=attributes
            where 'attributes' is a dict with the following optional items:
                        vlan=<id>
                        bonding="<name>" | nic="<name>"
                        (bonding and nics are mutually exclusive)
                        ipaddr="<ipv4>"
                        netmask="<ipv4>"
                        gateway="<ipv4>"
                        bootproto="..."
                        ipv6addr="<ipv6>[/<prefixlen>]"
                        ipv6gateway="<ipv6>"
                        ipv6autoconf="0|1"
                        dhcpv6="0|1"
                        defaultRoute=True|False
                        (other options will be passed to the config file AS-IS)
                        -- OR --
                        remove=True (other attributes can't be specified)

        bondings - dict of key=bonding, value=attributes
            where 'attributes' is a dict with the following optional items:
                        nics=["<nic1>" , "<nic2>", ...]
                        options="<bonding-options>"
                        -- OR --
                        remove=True (other attributes can't be specified)

        options - dict of options, such as:
                        force=0|1
                        connectivityCheck=0|1
                        connectivityTimeout=<int>
                        _inRollback=True|False

    Notes:
        When you edit a network that is attached to a bonding, it's not
        necessary to re-specify the bonding (you need only to note
        the attachment in the network's attributes). Similarly, if you edit
        a bonding, it's not necessary to specify its networks.
    """
    logger = logging.getLogger("setupNetworks")

    logger.debug("Setting up network according to configuration: "
                 "networks:%r, bondings:%r, options:%r" %
                 (networks, bondings, options))

    force = options.get('force', False)
    if not utils.tobool(force):
        logging.debug("Validating configuration")
        _validateNetworkSetup(networks, bondings)

    bondings, networks, options = _apply_hook(bondings, networks, options)

    libvirt_nets = netinfo.networks()
    _netinfo = netinfo.NetInfo(
        _netinfo=netinfo.get(netinfo.libvirtNets2vdsm(libvirt_nets)))
    connectivity_check_networks = set()

    logger.debug("Applying...")
    in_rollback = options.get('_inRollback', False)
    kernel_config = netconfpersistence.KernelConfig(_netinfo)
    normalized_config = kernel_config.normalize(
        netconfpersistence.BaseConfig(networks, bondings))
    with ConfiguratorClass(in_rollback) as configurator:
        # Remove edited networks and networks with 'remove' attribute
        for network, attrs in networks.items():
            if network in _netinfo.networks:
                logger.debug("Removing network %r", network)
                keep_bridge = _should_keep_bridge(
                    network_attrs=normalized_config.networks[network],
                    currently_bridged=_netinfo.networks[network]['bridged'],
                    net_kernel_config=kernel_config.networks[network])

                _delNetwork(network,
                            configurator=configurator,
                            force=force,
                            implicitBonding=False,
                            _netinfo=_netinfo,
                            keep_bridge=keep_bridge)
                del _netinfo.networks[network]
                _netinfo.updateDevices()
            elif network in libvirt_nets:
                # If the network was not in _netinfo but is in the networks
                # returned by libvirt, it means that we are dealing with
                # a broken network.
                logger.debug('Removing broken network %r', network)
                _delBrokenNetwork(network,
                                  libvirt_nets[network],
                                  configurator=configurator)
                _netinfo.updateDevices()
            elif 'remove' in attrs:
                raise ConfigNetworkError(
                    ne.ERR_BAD_BRIDGE, "Cannot delete "
                    "network %r: It doesn't exist in the "
                    "system" % network)
            else:
                connectivity_check_networks.add(network)

        _handleBondings(bondings, configurator, in_rollback)

        _add_missing_networks(configurator, networks, bondings, force, logger,
                              _netinfo)

        _check_connectivity(connectivity_check_networks, networks, bondings,
                            options, logger)

    hooks.after_network_setup(_buildSetupHookDict(networks, bondings, options))