Return useful information from a SmartOS compute node
9157
def _smartos_computenode_data():
    '''
    
    '''
    # Provides:
    #   vms_total
    #   vms_running
    #   vms_stopped
    #   vms_type
    #   sdc_version
    #   vm_capable
    #   vm_hw_virt

    grains = {}

    # collect vm data
    vms = {}
    for vm in __salt__['cmd.run']('vmadm list -p -o uuid,alias,state,type').split("\n"):
        vm = dict(list(zip(['uuid', 'alias', 'state', 'type'], vm.split(':'))))
        vms[vm['uuid']] = vm
        del vms[vm['uuid']]['uuid']

    # set vm grains
    grains['computenode_vms_total'] = len(vms)
    grains['computenode_vms_running'] = 0
    grains['computenode_vms_stopped'] = 0
    grains['computenode_vms_type'] = {'KVM': 0, 'LX': 0, 'OS': 0}
    for vm in vms:
        if vms[vm]['state'].lower() == 'running':
            grains['computenode_vms_running'] += 1
        elif vms[vm]['state'].lower() == 'stopped':
            grains['computenode_vms_stopped'] += 1

        if vms[vm]['type'] not in grains['computenode_vms_type']:
            # NOTE: be prepared for when bhyve gets its own type
            grains['computenode_vms_type'][vms[vm]['type']] = 0
        grains['computenode_vms_type'][vms[vm]['type']] += 1

    # sysinfo derived grains
    sysinfo = salt.utils.json.loads(__salt__['cmd.run']('sysinfo'))
    grains['computenode_sdc_version'] = sysinfo['SDC Version']
    grains['computenode_vm_capable'] = sysinfo['VM Capable']
    if sysinfo['VM Capable']:
        grains['computenode_vm_hw_virt'] = sysinfo['CPU Virtualization']

    # sysinfo derived smbios grains
    grains['manufacturer'] = sysinfo['Manufacturer']
    grains['productname'] = sysinfo['Product']
    grains['uuid'] = sysinfo['UUID']

    return grains
4282
def info(hosts=None, profile=None):
    '''
    
    '''
    es = _get_instance(hosts, profile)

    try:
        return es.info()
    except elasticsearch.TransportError as e:
        raise CommandExecutionError("Cannot retrieve server information, server returned code {0} with message {1}".format(e.status_code, e.error))
918686
def nodes_gcp(c_obj):
    """"""
    gcp_nodes = []
    try:
        gcp_nodes = c_obj.list_nodes(ex_use_disk_cache=True)
    except BaseHTTPError as e:
        abort_err("\r HTTP Error with GCP: {}".format(e))
    gcp_nodes = adj_nodes_gcp(gcp_nodes)
    return gcp_nodes
1044913
def _get_info(self, host, port, unix_socket, auth):
        

        client = self._client(host, port, unix_socket, auth)
        if client is None:
            return None

        info = client.info()
        del client
        return info
964053
def cli(env, sortby, cpu, domain, datacenter, hostname, memory, network, tag, columns, limit):
    """"""

    manager = SoftLayer.HardwareManager(env.client)
    servers = manager.list_hardware(hostname=hostname,
                                    domain=domain,
                                    cpus=cpu,
                                    memory=memory,
                                    datacenter=datacenter,
                                    nic_speed=network,
                                    tags=tag,
                                    mask="mask(SoftLayer_Hardware_Server)[%s]" % columns.mask(),
                                    limit=limit)

    table = formatting.Table(columns.columns)
    table.sortby = sortby

    for server in servers:
        table.add_row([value or formatting.blank()
                       for value in columns.row(server)])

    env.fout(table)
951771
def vm_info(vm_=None):
    '''
    
    '''
    with _get_xapi_session() as xapi:

        def _info(vm_):
            vm_rec = _get_record_by_label(xapi, 'VM', vm_)
            if vm_rec is False:
                return False
            vm_metrics_rec = _get_metrics_record(xapi, 'VM', vm_rec)

            return {'cpu': vm_metrics_rec['VCPUs_number'],
                    'maxCPU': _get_val(vm_rec, ['VCPUs_max']),
                    'cputime': vm_metrics_rec['VCPUs_utilisation'],
                    'disks': get_disks(vm_),
                    'nics': get_nics(vm_),
                    'maxMem': int(_get_val(vm_rec, ['memory_dynamic_max'])),
                    'mem': int(vm_metrics_rec['memory_actual']),
                    'state': _get_val(vm_rec, ['power_state'])
                    }
        info = {}
        if vm_:
            ret = _info(vm_)
            if ret is not None:
                info[vm_] = ret
        else:
            for vm_ in list_domains():
                ret = _info(vm_)
                if ret is not None:
                    info[vm_] = _info(vm_)
        return info
1243003
def _memdata(osdata):
    '''
    
    '''
    # Provides:
    #   mem_total
    #   swap_total, for supported systems.
    grains = {'mem_total': 0}
    if osdata['kernel'] == 'Linux':
        grains.update(_linux_memdata())
    elif osdata['kernel'] in ('FreeBSD', 'OpenBSD', 'NetBSD'):
        grains.update(_bsd_memdata(osdata))
    elif osdata['kernel'] == 'Darwin':
        grains.update(_osx_memdata())
    elif osdata['kernel'] == 'SunOS':
        grains.update(_sunos_memdata())
    elif osdata['kernel'] == 'AIX':
        grains.update(_aix_memdata())
    elif osdata['kernel'] == 'Windows' and HAS_WMI:
        grains.update(_windows_memdata())
    return grains
577718
def node_info():
    '''
    
    '''
    with _get_xapi_session() as xapi:
        # get node uuid
        host_rec = _get_record(xapi, 'host', _get_all(xapi, 'host')[0])
        # get first CPU (likely to be a core) uuid
        host_cpu_rec = _get_record(xapi, 'host_cpu', host_rec['host_CPUs'][0])
        # get related metrics
        host_metrics_rec = _get_metrics_record(xapi, 'host', host_rec)

        # adapted / cleaned up from Xen's xm
        def getCpuMhz():
            cpu_speeds = [int(host_cpu_rec["speed"])
                          for host_cpu_it in host_cpu_rec
                          if "speed" in host_cpu_it]
            if cpu_speeds:
                return sum(cpu_speeds) / len(cpu_speeds)
            else:
                return 0

        def getCpuFeatures():
            if host_cpu_rec:
                return host_cpu_rec['features']

        def getFreeCpuCount():
            cnt = 0
            for host_cpu_it in host_cpu_rec:
                if not host_cpu_rec['cpu_pool']:
                    cnt += 1
            return cnt

        info = {
                'cpucores': _get_val(host_rec,
                                    ["cpu_configuration", "nr_cpus"]),
                'cpufeatures': getCpuFeatures(),
                'cpumhz': getCpuMhz(),
                'cpuarch': _get_val(host_rec,
                                    ["software_version", "machine"]),
                'cputhreads': _get_val(host_rec,
                                    ["cpu_configuration", "threads_per_core"]),
                'phymemory': int(host_metrics_rec["memory_total"]) / 1024 / 1024,
                'cores_per_sockets': _get_val(host_rec,
                                    ["cpu_configuration", "cores_per_socket"]),
                'free_cpus': getFreeCpuCount(),
                'free_memory': int(host_metrics_rec["memory_free"]) / 1024 / 1024,
                'xen_major': _get_val(host_rec,
                                    ["software_version", "xen_major"]),
                'xen_minor': _get_val(host_rec,
                                    ["software_version", "xen_minor"]),
                'xen_extra': _get_val(host_rec,
                                    ["software_version", "xen_extra"]),
                'xen_caps': " ".join(_get_val(host_rec, ["capabilities"])),
                'xen_scheduler': _get_val(host_rec,
                                    ["sched_policy"]),
                'xen_pagesize': _get_val(host_rec,
                                    ["other_config", "xen_pagesize"]),
                'platform_params': _get_val(host_rec,
                                    ["other_config", "platform_params"]),
                'xen_commandline': _get_val(host_rec,
                                    ["other_config", "xen_commandline"]),
                'xen_changeset': _get_val(host_rec,
                                    ["software_version", "xen_changeset"]),
                'cc_compiler': _get_val(host_rec,
                                    ["software_version", "cc_compiler"]),
                'cc_compile_by': _get_val(host_rec,
                                    ["software_version", "cc_compile_by"]),
                'cc_compile_domain': _get_val(host_rec,
                                    ["software_version", "cc_compile_domain"]),
                'cc_compile_date': _get_val(host_rec,
                                    ["software_version", "cc_compile_date"]),
                'xend_config_format': _get_val(host_rec,
                                    ["software_version", "xend_config_format"])
                }

        return info
741107
def list_nodes(call=None):
    ''' 
    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The list_nodes function must be called with -f or --function.'
        )

    items = query(method='servers')

    ret = {}
    for node in items['servers']:
        public_ips = []
        private_ips = []
        image_id = ''

        if node.get('public_ip'):
            public_ips = [node['public_ip']['address']]

        if node.get('private_ip'):
            private_ips = [node['private_ip']]

        if node.get('image'):
            image_id = node['image']['id']

        ret[node['name']] = {
            'id': node['id'],
            'image_id': image_id,
            'public_ips': public_ips,
            'private_ips': private_ips,
            'size': node['volumes']['0']['size'],
            'state': node['state'],
        }
    return ret
699121
def _system(self, *args, **kwargs):
        '''
        
        '''
        sysinfo = SysInfo(__grains__.get("kernel"))

        data = dict()
        data['cpu'] = sysinfo._get_cpu()
        data['disks'] = sysinfo._get_fs()
        data['mounts'] = sysinfo._get_mounts()
        data['memory'] = sysinfo._get_mem()
        data['network'] = sysinfo._get_network()
        data['os'] = sysinfo._get_os()

        return data
762209
def _node_info(conn):
    '''
    
    '''
    raw = conn.getInfo()
    info = {'cpucores': raw[6],
            'cpumhz': raw[3],
            'cpumodel': six.text_type(raw[0]),
            'cpus': raw[2],
            'cputhreads': raw[7],
            'numanodes': raw[4],
            'phymemory': raw[1],
            'sockets': raw[5]}
    return info
531979
def get_device(self):
        
        addr = self.address
        servers = [server for server in pyrax.cloudservers.list()
                if addr in server.networks.get("private", "")]
        try:
            return servers[0]
        except IndexError:
            return None
164199
def cli(env, identifier, wait):
    """"""

    compute = SoftLayer.HardwareManager(env.client)
    compute_id = helpers.resolve_id(compute.resolve_ids, identifier,
                                    'hardware')
    ready = compute.wait_for_ready(compute_id, wait)
    if ready:
        env.fout("READY")
    else:
        raise exceptions.CLIAbort("Server %s not ready" % compute_id)
964851
def get_node(conn, name):
    '''
    
    '''
    nodes = conn.list_nodes()
    for node in nodes:
        if node.name == name:
            __utils__['cloud.cache_node'](salt.utils.data.simple_types_filter(node.__dict__), __active_provider_name__, __opts__)
            return node
1346654
def get_compute(self, compute_id):
        
        try:
            return self._computes[compute_id]
        except KeyError:
            if compute_id == "vm":
                raise aiohttp.web.HTTPNotFound(text="You try to use a node on the GNS3 VM server but the GNS3 VM is not configured")
            raise aiohttp.web.HTTPNotFound(text="Compute ID {} doesn't exist".format(compute_id))
445588
def gather_details():
    """"""
    try:
        data = {
            'kernel': platform.uname(),
            'distribution': platform.linux_distribution(),
            'libc': platform.libc_ver(),
            'arch': platform.machine(),
            'python_version': platform.python_version(),
            'os_name': platform.system(),
            'static_hostname': platform.node(),
            'cpu': platform.processor(),
            'fqdn': socket.getfqdn(),
        }
    except AttributeError:
        return {}

    return data
1279224
def get_function_data(minion, jid):
    """"""
    redis = Redis(connection_pool=redis_pool)
    data = redis.get('{0}:{1}'.format(minion, jid))
    return Response(response=data, status=200, mimetype="application/json")