Exemple #1
0
def kernel_features():
    return {
        'PTI': supervdsm.getProxy().get_pti(),
        'RETP': supervdsm.getProxy().get_retp(),
        'IBRS': supervdsm.getProxy().get_ibrs(),
        'SSBD': supervdsm.getProxy().get_ssbd(),
    }
Exemple #2
0
def setRpFilterIfNeeded(netIfaceName, hostname, loose_mode):
    """
    Set rp_filter to loose or strict mode if there's no session using the
    netIfaceName device and it's not the device used by the OS to reach the
    'hostname'.
    loose mode is needed to allow multiple iSCSI connections in a multiple NIC
    per subnet configuration. strict mode is needed to avoid the security
    breach where an untrusted VM can DoS the host by sending it packets with
    spoofed random sources.

    Arguments:
        netIfaceName: the device used by the iSCSI session
        target: iSCSI target object cointaining the portal hostname
        loose_mode: boolean
    """
    if netIfaceName is None:
        log.debug("iface.net_ifacename not provided, skipping rp filter setup")
        return

    sessions = _sessionsUsingNetiface(netIfaceName)

    if not any(sessions) and netIfaceName != getRouteDeviceTo(hostname):
        if loose_mode:
            log.info("Setting loose mode rp_filter for device %r." %
                     netIfaceName)
            supervdsm.getProxy().set_rp_filter_loose(netIfaceName)
        else:
            log.info("Setting strict mode rp_filter for device %r." %
                     netIfaceName)
            supervdsm.getProxy().set_rp_filter_strict(netIfaceName)
Exemple #3
0
def _alloc(count, size, path):
    """Helper to actually (de)allocate hugepages, called by public facing
        methods.

    Args:
        count: Number of hugepages to allocate (can be negative)
        size: The target hugepage size (must be supported by the system)
        path: Path to the hugepages directory.

    Returns: The amount of allocated pages (can be negative,
        implicating deallocation).

    Raises:
    """
    if size is None:
        size = DEFAULT_HUGEPAGESIZE[cpuarch.real()]

    path = path.format(size)

    ret = supervdsm.getProxy().hugepages_alloc(count, path)
    if ret != count:
        supervdsm.getProxy().hugepages_alloc(-ret, path)
        raise NonContiguousMemory

    return ret
Exemple #4
0
Fichier : hba.py Projet : nirs/vdsm
def rescan():
    """
    Rescan HBAs discovering new devices.
    """
    log.debug("Starting scan")
    try:
        supervdsm.getProxy().hbaRescan()
    except Error as e:
        log.error("Scan failed: %s", e)
    else:
        log.debug("Scan finished")
Exemple #5
0
def spawn_mdev(mdev_type, mdev_uuid, mdev_placement, log):
    device = _suitable_device_for_mdev_type(mdev_type, mdev_placement, log)
    if device is None:
        message = 'vgpu: No device with type {} is available'.format(mdev_type)
        log.error(message)
        raise exception.ResourceUnavailable(message)
    try:
        supervdsm.getProxy().mdev_create(device, mdev_type, mdev_uuid)
    except IOError:
        message = 'vgpu: Failed to create mdev type {}'.format(mdev_type)
        log.error(message)
        raise exception.ResourceUnavailable(message)
Exemple #6
0
def despawn_mdev(mdev_uuid):
    device = None
    for dev in _each_mdev_device():
        if mdev_uuid in os.listdir(os.path.join(_MDEV_PATH, dev)):
            device = dev
            break
    if device is None or mdev_uuid is None:
        raise exception.ResourceUnavailable('vgpu: No mdev found')
    try:
        supervdsm.getProxy().mdev_delete(device, mdev_uuid)
    except IOError:
        # This is destroy flow, we can't really fail
        pass
Exemple #7
0
Fichier : nbd.py Projet : nirs/vdsm
def start_transient_service(server_id, config):
    if os.geteuid() != 0:
        return supervdsm.getProxy().nbd_start_transient_service(
            server_id, config)

    _verify_path(config.path)

    cmd = [
        QEMU_NBD,
        "--socket", _socket_path(server_id),
        "--format", config.format,
        "--persistent",

        # Use empty export name for nicer url: "nbd:unix:/path" instead of
        # "nbd:unix:/path:exportname=name".
        "--export-name=",

        "--cache=none",
        "--aio=native",
    ]

    if config.readonly:
        cmd.append("--read-only")
    elif config.discard:
        cmd.append("--discard=unmap")

    cmd.append(config.path)

    systemd.run(
        cmd,
        unit=_service_name(server_id),
        uid=fileUtils.resolveUid(constants.VDSM_USER),
        gid=fileUtils.resolveGid(constants.VDSM_GROUP))
Exemple #8
0
def validateDirAccess(dirPath):
    try:
        getProcPool().fileUtils.validateAccess(dirPath)
        supervdsm.getProxy().validateAccess(
            constants.VDSM_USER,
            (constants.VDSM_GROUP,), dirPath,
            (os.R_OK | os.W_OK | os.X_OK))
        supervdsm.getProxy().validateAccess(
            constants.QEMU_PROCESS_USER,
            (constants.DISKIMAGE_GROUP, constants.METADATA_GROUP), dirPath,
            (os.R_OK | os.X_OK))
    except OSError as e:
        if e.errno == errno.EACCES:
            raise se.StorageServerAccessPermissionError(dirPath)
        raise

    return True
Exemple #9
0
def remove_vnc_password(username):
    if os.geteuid() != 0:
        return supervdsm.getProxy().saslpasswd2_remove_vnc_password(username)

    commands.run([SASL_COMMAND,
                  "-a", SASL_APP_NAME,
                  "-f", SASL_PASSWORD_DB,
                  "-d",
                  username])
Exemple #10
0
 def _get_gluster_volinfo(self):
     try:
         superVdsmProxy = supervdsm.getProxy()
         volinfo = superVdsmProxy.glusterVolumeInfo(self._volname,
                                                    self._volfileserver)
         return volinfo[self._volname]
     except ge.GlusterCmdExecFailedException as e:
         self.log.warning("Failed to get volume info: %s", e)
         return {}
Exemple #11
0
def test_ksm_action(dropped_privileges):
    proxy = supervdsm.getProxy()
    ksmParams = {"run": 0,
                 "merge_across_nodes": 1,
                 "sleep_millisecs": 0xffff,
                 "pages_to_scan": 0xffff}
    proxy.ksmTune(ksmParams)

    for k, v in six.iteritems(ksmParams):
        with open("/sys/kernel/mm/ksm/%s" % k, "r") as f:
            assert str(v) == f.read().rstrip()
Exemple #12
0
def _isVncEncrypted():
    """
    If VNC is configured to use encrypted connections, libvirt's qemu.conf
    contains the following flag:
        vnc_tls = 1
    """
    try:
        return supervdsm.getProxy().check_qemu_conf_contains('vnc_tls', '1')
    except:
        logging.error("Supervdsm was not able to read VNC TLS config. "
                      "Check supervdsmd log for details.")
    return False
Exemple #13
0
def set_vnc_password(username, passwd):
    if os.geteuid() != 0:
        return supervdsm.getProxy().saslpasswd2_set_vnc_password(username,
                                                                 passwd)

    # Call to Popen.communicate needs string in Python2 and bytes in Python 3
    # string.encode returns string in Python2 and bytes in Python3
    # How convenient!
    commands.run([SASL_COMMAND,
                  "-a", SASL_APP_NAME,
                  "-f", SASL_PASSWORD_DB,
                  "-p",
                  username],
                 input=passwd.encode())
Exemple #14
0
def run_helper(sub_cmd, cmd_input=None):
    if os.geteuid() != 0:
        return supervdsm.getProxy().managedvolume_run_helper(
            sub_cmd, cmd_input=cmd_input)
    try:
        if cmd_input:
            cmd_input = json.dumps(cmd_input).encode("utf-8")
        result = commands.run([HELPER, sub_cmd], input=cmd_input)
    except cmdutils.Error as e:
        raise se.ManagedVolumeHelperFailed("Error executing helper: %s" % e)
    try:
        return json.loads(result)
    except ValueError as e:
        raise se.ManagedVolumeHelperFailed("Error loading result: %s" % e)
Exemple #15
0
 def _prepareVolumePathFromPayload(self, vmId, device, payload):
     """
     param vmId:
         VM UUID or None
     param device:
         either 'floppy' or 'cdrom'
     param payload:
         a dict formed like this:
         {'volId': 'volume id',   # volId is optional
          'file': {'filename': 'content', ...}}
     """
     funcs = {'cdrom': 'mkIsoFs', 'floppy': 'mkFloppyFs'}
     if device not in funcs:
         raise vm.VolumeError("Unsupported 'device': %s" % device)
     func = getattr(supervdsm.getProxy(), funcs[device])
     return func(vmId, payload['file'], payload.get('volId'))
Exemple #16
0
 def restoreNetConfig(self):
     supervdsm.getProxy().restoreNetworks()
Exemple #17
0
def getSessionInfo(sessionID):
    return supervdsm.getProxy().readSessionInfo(sessionID)
Exemple #18
0
def docker_net_create(subnet, gw, nic, network):
    return _result(supervdsm.getProxy().docker_net_create(
        subnet, gw, nic, network))
Exemple #19
0
def get():
    caps = {}
    cpu_topology = numa.cpu_topology()

    caps['kvmEnabled'] = str(os.path.exists('/dev/kvm')).lower()

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

    caps['cpuThreads'] = str(cpu_topology.threads)
    caps['cpuSockets'] = str(cpu_topology.sockets)
    caps['onlineCpus'] = ','.join(cpu_topology.online_cpus)
    caps['cpuSpeed'] = cpuinfo.frequency()
    caps['cpuModel'] = cpuinfo.model()
    caps['cpuFlags'] = ','.join(cpuinfo.flags() +
                                machinetype.compatible_cpu_models())

    caps.update(_getVersionInfo())

    net_caps = supervdsm.getProxy().network_caps()
    caps.update(net_caps)

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

    caps['operatingSystem'] = osinfo.version()
    caps['uuid'] = host.uuid()
    caps['packages2'] = osinfo.package_versions()
    caps['realtimeKernel'] = osinfo.runtime_kernel_flags().realtime
    caps['kernelArgs'] = osinfo.kernel_args()
    caps['nestedVirtualization'] = osinfo.nested_virtualization().enabled
    caps['emulatedMachines'] = machinetype.emulated_machines(
        cpuarch.effective())
    caps['ISCSIInitiatorName'] = _getIscsiIniName()
    caps['HBAInventory'] = 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'] = rngsources.list_available()

    caps['numaNodes'] = dict(numa.topology())
    caps['numaNodeDistance'] = dict(numa.distances())
    caps['autoNumaBalancing'] = numa.autonuma_status()

    caps['selinux'] = osinfo.selinux_status()

    caps['liveSnapshot'] = 'true'
    caps['liveMerge'] = 'true'
    caps['kdumpStatus'] = osinfo.kdump_status()

    caps['hostdevPassthrough'] = str(hostdev.is_supported()).lower()
    # TODO This needs to be removed after adding engine side support
    # and adding gdeploy support to enable libgfapi on RHHI by default
    caps['additionalFeatures'] = ['libgfapi_supported']
    if osinfo.glusterEnabled:
        from vdsm.gluster.api import glusterAdditionalFeatures
        caps['additionalFeatures'].extend(glusterAdditionalFeatures())
    caps['hostedEngineDeployed'] = _isHostedEngineDeployed()
    caps['hugepages'] = hugepages.supported()
    caps['kernelFeatures'] = osinfo.kernel_features()
    caps['vncEncrypted'] = _isVncEncrypted()
    caps['backupEnabled'] = False

    try:
        caps["connector_info"] = managedvolume.connector_info()
    except se.ManagedVolumeNotSupported as e:
        logging.info("managedvolume not supported: %s", e)
    except se.ManagedVolumeHelperFailed as e:
        logging.exception("Error getting managedvolume connector info: %s", e)

    return caps
Exemple #20
0
def _remove_udev_rule(vol_id):
    try:
        proxy = supervdsm.getProxy()
        proxy.remove_managed_udev_rule(vol_id)
    except Exception:
        log.exception("Failed to remove udev rule for volume %s", vol_id)
Exemple #21
0
def multipath_status():
    return getProxy().multipath_status()
Exemple #22
0
def serve_clients(log):
    cif = None
    irs = None
    scheduler = None
    running = [True]

    def sigtermHandler(signum, frame):
        log.info("Received signal %s, shutting down" % signum)
        running[0] = False

    def sigusr1Handler(signum, frame):
        if irs:
            log.info("Received signal %s, stopping SPM" % signum)
            # pylint: disable=no-member
            # TODO remove when side effect removed from HSM.__init__ and
            # initialize it in line #63
            irs.spmStop(
                irs.getConnectedStoragePoolsList()['poollist'][0])

    def sigalrmHandler(signum, frame):
        # Used in panic.panic() when shuting down logging, must not log.
        raise RuntimeError("Alarm timeout")

    sigutils.register()
    signal.signal(signal.SIGTERM, sigtermHandler)
    signal.signal(signal.SIGUSR1, sigusr1Handler)
    signal.signal(signal.SIGALRM, sigalrmHandler)
    zombiereaper.registerSignalHandler()

    profile.start()
    metrics.start()

    libvirtconnection.start_event_loop()

    try:
        if config.getboolean('irs', 'irs_enable'):
            try:
                irs = Dispatcher(HSM())
            except:
                panic("Error initializing IRS")

        scheduler = schedule.Scheduler(name="vdsm.Scheduler",
                                       clock=time.monotonic_time)
        scheduler.start()

        from vdsm.clientIF import clientIF  # must import after config is read
        cif = clientIF.getInstance(irs, log, scheduler)

        jobs.start(scheduler, cif)

        install_manhole({'irs': irs, 'cif': cif})

        cif.start()

        init_unprivileged_network_components(cif, supervdsm.getProxy())

        periodic.start(cif, scheduler)
        health.start()
        try:
            while running[0]:
                sigutils.wait_for_signal()

            profile.stop()
            if config.getboolean('devel', 'coverage_enable'):
                atexit._run_exitfuncs()
        finally:
            stop_unprivileged_network_components()
            metrics.stop()
            health.stop()
            periodic.stop()
            cif.prepareForShutdown()
            jobs.stop()
            scheduler.stop()
            run_stop_hook()
    finally:
        libvirtconnection.stop_event_loop(wait=False)
Exemple #23
0
def pathListIter(filterGuids=()):
    filterLen = len(filterGuids) if filterGuids else -1
    devsFound = 0

    knownSessions = {}

    svdsm = supervdsm.getProxy()
    pathStatuses = devicemapper.getPathsStatus()

    for dmId, guid in getMPDevsIter():
        if devsFound == filterLen:
            break

        if filterGuids and guid not in filterGuids:
            continue

        devsFound += 1

        devInfo = {
            "guid": guid,
            "dm": dmId,
            "capacity": str(getDeviceSize(dmId)),
            "serial": svdsm.getScsiSerial(dmId),
            "paths": [],
            "connections": [],
            "devtypes": [],
            "devtype": "",
            "vendor": "",
            "product": "",
            "fwrev": "",
            "logicalblocksize": "",
            "physicalblocksize": "",
            "discard_max_bytes": getDeviceDiscardMaxBytes(dmId),
        }

        for slave in devicemapper.getSlaves(dmId):
            if not devicemapper.isBlockDevice(slave):
                log.warning("No such physdev '%s' is ignored" % slave)
                continue

            if not devInfo["vendor"]:
                try:
                    devInfo["vendor"] = getVendor(slave)
                except Exception:
                    log.warn("Problem getting vendor from device `%s`",
                             slave,
                             exc_info=True)

            if not devInfo["product"]:
                try:
                    devInfo["product"] = getModel(slave)
                except Exception:
                    log.warn("Problem getting model name from device `%s`",
                             slave,
                             exc_info=True)

            if not devInfo["fwrev"]:
                try:
                    devInfo["fwrev"] = getFwRev(slave)
                except Exception:
                    log.warn("Problem getting fwrev from device `%s`",
                             slave,
                             exc_info=True)

            if (not devInfo["logicalblocksize"]
                    or not devInfo["physicalblocksize"]):
                try:
                    logBlkSize, phyBlkSize = getDeviceBlockSizes(slave)
                    devInfo["logicalblocksize"] = str(logBlkSize)
                    devInfo["physicalblocksize"] = str(phyBlkSize)
                except Exception:
                    log.warn("Problem getting blocksize from device `%s`",
                             slave,
                             exc_info=True)

            pathInfo = {}
            pathInfo["physdev"] = slave
            pathInfo["state"] = pathStatuses.get(slave, "failed")
            pathInfo["capacity"] = str(getDeviceSize(slave))
            try:
                hbtl = getHBTL(slave)
            except OSError as e:
                if e.errno == errno.ENOENT:
                    log.warn("Device has no hbtl: %s", slave)
                    pathInfo["lun"] = 0
                else:
                    log.error(
                        "Error: %s while trying to get hbtl of device: "
                        "%s", e, slave)
                    raise
            else:
                pathInfo["lun"] = hbtl.lun

            if iscsi.devIsiSCSI(slave):
                devInfo["devtypes"].append(DEV_ISCSI)
                pathInfo["type"] = DEV_ISCSI
                sessionID = iscsi.getiScsiSession(slave)
                if sessionID not in knownSessions:
                    # FIXME: This entire part is for BC. It should be moved to
                    # hsm and not preserved for new APIs. New APIs should keep
                    # numeric types and sane field names.
                    sess = iscsi.getSessionInfo(sessionID)
                    sessionInfo = {
                        "connection": sess.target.portal.hostname,
                        "port": str(sess.target.portal.port),
                        "iqn": sess.target.iqn,
                        "portal": str(sess.target.tpgt),
                        "initiatorname": sess.iface.name
                    }

                    # Note that credentials must be sent back in order for
                    # the engine to tell vdsm how to reconnect later
                    if sess.credentials:
                        cred = sess.credentials
                        sessionInfo['user'] = cred.username
                        sessionInfo['password'] = cred.password

                    knownSessions[sessionID] = sessionInfo
                devInfo["connections"].append(knownSessions[sessionID])
            else:
                devInfo["devtypes"].append(DEV_FCP)
                pathInfo["type"] = DEV_FCP

            if devInfo["devtype"] == "":
                devInfo["devtype"] = pathInfo["type"]
            elif (devInfo["devtype"] != DEV_MIXED
                  and devInfo["devtype"] != pathInfo["type"]):
                devInfo["devtype"] == DEV_MIXED

            devInfo["paths"].append(pathInfo)

        yield devInfo
Exemple #24
0
def change_numvfs(device_name, numvfs):
    net_name = physical_function_net_name(device_name)
    supervdsm.getProxy().change_numvfs(name_to_pci_path(device_name), numvfs,
                                       net_name)
Exemple #25
0
 def restoreNetConfig(self):
     supervdsm.getProxy().restoreNetworks()
Exemple #26
0
def get():
    caps = {}
    cpu_topology = numa.cpu_topology()

    caps['kvmEnabled'] = str(os.path.exists('/dev/kvm')).lower()

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

    caps['cpuThreads'] = str(cpu_topology.threads)
    caps['cpuSockets'] = str(cpu_topology.sockets)
    caps['onlineCpus'] = ','.join(cpu_topology.online_cpus)
    caps['cpuSpeed'] = cpuinfo.frequency()
    caps['cpuModel'] = cpuinfo.model()
    caps['cpuFlags'] = ','.join(cpuinfo.flags() +
                                machinetype.compatible_cpu_models())

    caps.update(_getVersionInfo())

    net_caps = supervdsm.getProxy().network_caps()
    caps.update(net_caps)

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

    caps['operatingSystem'] = osinfo.version()
    caps['uuid'] = host.uuid()
    caps['packages2'] = osinfo.package_versions()
    caps['realtimeKernel'] = osinfo.runtime_kernel_flags().realtime
    caps['kernelArgs'] = osinfo.kernel_args()
    caps['nestedVirtualization'] = osinfo.nested_virtualization().enabled
    caps['emulatedMachines'] = machinetype.emulated_machines(
        cpuarch.effective())
    caps['ISCSIInitiatorName'] = _getIscsiIniName()
    caps['HBAInventory'] = 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'] = rngsources.list_available()

    caps['numaNodes'] = dict(numa.topology())
    caps['numaNodeDistance'] = dict(numa.distances())
    caps['autoNumaBalancing'] = numa.autonuma_status()

    caps['selinux'] = osinfo.selinux_status()

    liveSnapSupported = _getLiveSnapshotSupport(cpuarch.effective())
    if liveSnapSupported is not None:
        caps['liveSnapshot'] = str(liveSnapSupported).lower()
    caps['liveMerge'] = str(getLiveMergeSupport()).lower()
    caps['kdumpStatus'] = osinfo.kdump_status()

    caps['hostdevPassthrough'] = str(hostdev.is_supported()).lower()
    # TODO This needs to be removed after adding engine side support
    # and adding gdeploy support to enable libgfapi on RHHI by default
    caps['additionalFeatures'] = ['libgfapi_supported']
    if osinfo.glusterEnabled:
        from vdsm.gluster.api import glusterAdditionalFeatures
        caps['additionalFeatures'].extend(glusterAdditionalFeatures())
    caps['containers'] = containersconnection.is_supported()
    caps['hostedEngineDeployed'] = _isHostedEngineDeployed()
    caps['hugepages'] = hugepages.supported()
    return caps
Exemple #27
0
def removeMapping(deviceName):
    return getProxy().removeDeviceMapping(deviceName)
Exemple #28
0
 def _prepare_socket(self):
     supervdsm.getProxy().prepareVmChannel(self._socketName)
Exemple #29
0
def getPathsStatus():
    return getProxy().getPathsStatus()
Exemple #30
0
def kernel_features():
    return supervdsm.getProxy().get_cpu_vulnerabilities()
Exemple #31
0
def docker_net_remove(network):
    return _result(supervdsm.getProxy().docker_net_remove(network))
Exemple #32
0
 def prepare(self):
     if self._path:
         supervdsm.getProxy().prepareVmChannel(
             self._path,
             constants.OVIRT_VMCONSOLE_GROUP)
Exemple #33
0
 def __init__(self):
     self.svdsmProxy = svdsm.getProxy()
Exemple #34
0
def getSessionInfo(sessionID):
    return supervdsm.getProxy().readSessionInfo(sessionID)
Exemple #35
0
def serve_clients(log):
    cif = None
    irs = None
    scheduler = None
    running = [True]

    def sigtermHandler(signum, frame):
        log.info("Received signal %s, shutting down" % signum)
        running[0] = False

    def sigusr1Handler(signum, frame):
        if irs:
            log.info("Received signal %s, stopping SPM" % signum)
            # pylint: disable=no-member
            # TODO remove when side effect removed from HSM.__init__ and
            # initialize it in line #63
            irs.spmStop(
                irs.getConnectedStoragePoolsList()['poollist'][0])

    sigutils.register()
    signal.signal(signal.SIGTERM, sigtermHandler)
    signal.signal(signal.SIGUSR1, sigusr1Handler)
    zombiereaper.registerSignalHandler()

    profile.start()
    metrics.start()

    libvirtconnection.start_event_loop()

    try:
        if config.getboolean('irs', 'irs_enable'):
            try:
                irs = Dispatcher(HSM())
            except:
                panic("Error initializing IRS")

        scheduler = schedule.Scheduler(name="vdsm.Scheduler",
                                       clock=time.monotonic_time)
        scheduler.start()

        from vdsm.clientIF import clientIF  # must import after config is read
        cif = clientIF.getInstance(irs, log, scheduler)

        jobs.start(scheduler, cif)

        install_manhole({'irs': irs, 'cif': cif})

        cif.start()

        init_unprivileged_network_components(cif, supervdsm.getProxy())

        periodic.start(cif, scheduler)
        health.start()
        try:
            while running[0]:
                sigutils.wait_for_signal()

            profile.stop()
        finally:
            metrics.stop()
            health.stop()
            periodic.stop()
            cif.prepareForShutdown()
            jobs.stop()
            scheduler.stop()
    finally:
        libvirtconnection.stop_event_loop(wait=False)
Exemple #36
0
 def setup(self):
     if self.uses_source('/dev/hwrng'):
         supervdsm.getProxy().appropriateHwrngDevice(self.vmid)
Exemple #37
0
def test_ping_call(dropped_privileges):
    proxy = supervdsm.getProxy()
    assert bool(proxy.ping())
Exemple #38
0
def docker_net_inspect(network):
    return _result(supervdsm.getProxy().docker_net_inspect(network))
Exemple #39
0
 def _prepare_socket(self):
     supervdsm.getProxy().prepareVmChannel(self._socketName)
Exemple #40
0
def change_numvfs(device_name, numvfs):
    net_name = physical_function_net_name(device_name)
    supervdsm.getProxy().change_numvfs(name_to_pci_path(device_name), numvfs,
                                       net_name)
Exemple #41
0
 def teardown(self):
     if self.uses_source('/dev/hwrng'):
         supervdsm.getProxy().rmAppropriateHwrngDevice(self.vmid)
Exemple #42
0
def systemd_run(unit_name, cgroup_slice, *args):
    return _result(supervdsm.getProxy().systemd_run(unit_name, cgroup_slice,
                                                    *args))
Exemple #43
0
 def umount(self, force=False, lazy=False, freeloop=False):
     umount = supervdsm.getProxy().umount if os.geteuid() != 0 else _umount
     self.log.info("unmounting %s", self.fs_file)
     with utils.stopwatch("%s unmounted" % self.fs_file, log=self.log):
         umount(self.fs_file, force=force, lazy=lazy, freeloop=freeloop)
     self._wait_for_events()
Exemple #44
0
def systemctl_stop(name):
    return _result(supervdsm.getProxy().systemctl_stop(name))
Exemple #45
0
def get():
    caps = {}
    cpu_topology = numa.cpu_topology()

    caps['kvmEnabled'] = str(os.path.exists('/dev/kvm')).lower()

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

    caps['cpuThreads'] = str(cpu_topology.threads)
    caps['cpuSockets'] = str(cpu_topology.sockets)
    caps['onlineCpus'] = ','.join(cpu_topology.online_cpus)
    caps['cpuSpeed'] = cpuinfo.frequency()
    caps['cpuModel'] = cpuinfo.model()
    caps['cpuFlags'] = ','.join(cpuinfo.flags() +
                                machinetype.compatible_cpu_models())

    caps.update(dsaversion.version_info)

    net_caps = supervdsm.getProxy().network_caps()
    caps.update(net_caps)

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

    caps['operatingSystem'] = osinfo.version()
    caps['uuid'] = host.uuid()
    caps['packages2'] = osinfo.package_versions()
    caps['realtimeKernel'] = osinfo.runtime_kernel_flags().realtime
    caps['kernelArgs'] = osinfo.kernel_args()
    caps['nestedVirtualization'] = osinfo.nested_virtualization().enabled
    caps['emulatedMachines'] = machinetype.emulated_machines(
        cpuarch.effective())
    caps['ISCSIInitiatorName'] = _getIscsiIniName()
    caps['HBAInventory'] = 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'] = rngsources.list_available()

    caps['numaNodes'] = dict(numa.topology())
    caps['numaNodeDistance'] = dict(numa.distances())
    caps['autoNumaBalancing'] = numa.autonuma_status()

    caps['selinux'] = osinfo.selinux_status()

    caps['liveSnapshot'] = 'true'
    caps['liveMerge'] = 'true'
    caps['kdumpStatus'] = osinfo.kdump_status()
    caps["deferred_preallocation"] = True

    caps['hostdevPassthrough'] = str(hostdev.is_supported()).lower()
    # TODO This needs to be removed after adding engine side support
    # and adding gdeploy support to enable libgfapi on RHHI by default
    caps['additionalFeatures'] = ['libgfapi_supported']
    if osinfo.glusterEnabled:
        from vdsm.gluster.api import glusterAdditionalFeatures
        caps['additionalFeatures'].extend(glusterAdditionalFeatures())
    caps['hostedEngineDeployed'] = _isHostedEngineDeployed()
    caps['hugepages'] = hugepages.supported()
    caps['kernelFeatures'] = osinfo.kernel_features()
    caps['vncEncrypted'] = _isVncEncrypted()
    caps['backupEnabled'] = False
    caps['fipsEnabled'] = _getFipsEnabled()
    caps['tscFrequency'] = _getTscFrequency()
    caps['tscScaling'] = _getTscScaling()

    try:
        caps["connector_info"] = managedvolume.connector_info()
    except se.ManagedVolumeNotSupported as e:
        logging.info("managedvolume not supported: %s", e)
    except se.ManagedVolumeHelperFailed as e:
        logging.exception("Error getting managedvolume connector info: %s", e)

    # Which domain versions are supported by this host.
    caps["domain_versions"] = sc.DOMAIN_VERSIONS

    caps["supported_block_size"] = backends.supported_block_size()

    return caps
Exemple #46
0
 def __init__(self):
     self.svdsmProxy = svdsm.getProxy()