VMware {code} Community
nalagdrol
Contributor
Contributor

Retrieve information from datastores (perfmanager)

 

#!/usr/bin/env python

from __future__ import print_function
from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim
import atexit
import sys
import ssl
import argparse
import getpass
# from datetime import timedelta, datetime
import datetime
import pprint


def GetVMHosts(content):
    # print("Getting all ESX hosts ...")
    host_view = content.viewManager.CreateContainerView(content.rootFolder,
                                                        [vim.HostSystem],
                                                        True)
    obj = [host for host in host_view.view]
    host_view.Destroy()
    return obj


def GetVMs(content):
    # print("Getting all VMs ...")
    vm_view = content.viewManager.CreateContainerView(content.rootFolder,
                                                      [vim.VirtualMachine],
                                                      True)
    obj = [vm for vm in vm_view.view]
    vm_view.Destroy()
    return obj


def GetDatastores(content):
    # print("Getting all Datastoress ...")
    datastore_view = content.viewManager.CreateContainerView(content.rootFolder,
                                                             [vim.Datastore],
                                                             True)
    obj = [datastore for datastore in datastore_view.view]
    datastore_view.Destroy()
    return obj

def get_args():
    parser = argparse.ArgumentParser(
        description='Arguments for talking to vCenter')

    parser.add_argument('-v', '--vcenter-host',
                        required=True,
                        action='store',
                        dest="vcenter_host",
                        help='vSphere service to connect to')

    parser.add_argument('-o', '--port',
                        type=int,
                        default=443,
                        action='store',
                        help='Port to connect on')

    parser.add_argument('-u', '--user',
                        required=True,
                        dest="user",
                        action='store',
                        help='Username to use')

    parser.add_argument('-p', '--password',
                        required=True,
                        dest="password",
                        action='store',
                        help='Password to use')


    parser.add_argument('--counter',
                        required=True,
                        action='store',
                        dest = "counter",
                        default=None,
                        help='Object that you want to monitor (Example: mem.consumed.average')
    parser.add_argument('--monitor_host',
                        required=True,
                        action='store',
                        dest = "monitor_host",
                        default=None,
                        help='Name of the esx that is going to be monitored. ie: --esx esjc-dsnt-vs69p.om.dsn.inet')
    parser.add_argument('--host_type',
                        required=True,
                        choices=['esx', 'datastore', 'vm'],
                        action='store',
                        dest = "host_type",
                        default=None,
                        help='Object type that we want to monitor (It could be:\n --host_type esx \n --host_type datastore \n --host_type vm')
    parser.add_argument('--counter_name',
                        required=True,
                        action='store',
                        dest = "counter_name",
                        default=None,
                        help='Counter name that could be used in the status message (i.e: Instead of using mem.consumed.average you could use --counter_name mem_used')
    parser.add_argument('--alerting',
                        choices=['yes', 'no'],
                        required=True,
                        action='store',
                        dest = "alerting",
                        default=None,
                        help='Select yes/no to give instructions to the script about if it must show alerts in the case that the warning/critical thresholds are reached')

    args = parser.parse_args()


    if not args.password:
        args.password = getpass.getpass(
            prompt='Enter password')

    return args

def StatCheck(perf_dict, counter_name):
    counter_key = perf_dict[counter_name]
    return counter_key


def BuildQuery(perfManager, counterId, instance, host, interval):
    # Note that vim.PerformanceManager.QuerySpec returns a list - albeit of 1 sample with maxSample=1

    metricId = vim.PerformanceManager.MetricId(counterId=counterId, instance=instance)
    # print(' counterId is %s and host is %s  and metricId is %s \n' % (counterId, host, metricId))

    query = vim.PerformanceManager.QuerySpec(intervalId=interval, entity=host, metricId=[metricId], maxSample=1)
    perfResults = perfManager.QueryPerf(querySpec=[query])
    if perfResults:
        return perfResults
    else:
        print('ERROR: Performance results empty.  TIP: Check time drift on source and vCenter server')
        print('Troubleshooting info:')
        print(query)
        # exit()
        return


def main():
    global statCounter
    global content, hosts, hostPgDict
    statCounter = ""
    args = get_args()
    searching = args.host_type
    context = ssl._create_unverified_context()
    serviceInstance = SmartConnect(host=args.vcenter_host,
                                   user=args.user,
                                   pwd=args.password,
                                   port=443,
                                   sslContext=context)
    atexit.register(Disconnect, serviceInstance)
    content = serviceInstance.RetrieveContent()
    hosts = GetVMHosts(content)
    perfManager = content.perfManager
    perfCounters = perfManager.perfCounter

    # Get all the performance counters
    perf_dict = {}
    perfList = perfManager.perfCounter
    for counter in perfList:
        counter_full = "{}.{}.{}".format(counter.groupInfo.key, counter.nameInfo.key, counter.rollupType)
        perf_dict[counter_full] = counter.key
    status = 0
    state = ""
    current_host = ""
    found = False
    interval = 20
    for host in hosts:

(perfManager.QueryPerfProviderSummary(host)))
        if searching == "esx" and args.monitor_host == host.name:
            statCounter = BuildQuery(perfManager, (StatCheck(perf_dict, args.counter)), "", host, interval)
            if statCounter:
                statCounter = float(sum(statCounter[0].value[0].value))
                print(statCounter)
                current_host = host.name
                state = 'OK: %s for %s is %s'% (args.counter_name, host.name, statCounter)
                print (statCounter)
        elif searching == "vm":
            vms = GetVMs(content)
            for vm in vms:

                if vm.name == args.monitor_host and found == False:
                    statCounter = BuildQuery(perfManager, (StatCheck(perf_dict, args.counter)), "", vm, interval)
                    current_host = vm.name
                    found = True
                    if statCounter:
                        statCounter = float(sum(statCounter[0].value[0].value))
                        state = 'OK: %s for %s is %s'% (args.counter_name, vm.name, statCounter)

        elif searching == "datastore": #and datastore.name == args.monitor_host:
            datastores = GetDatastores(content)

            # print(' ---------Datastores -----------')
            for datastore in datastores:
                statCounter = BuildQuery(perfManager, (StatCheck(perf_dict, datastore.disk.capacity)), "", datastore, interval)


# Main section
if __name__ == "__main__":
    sys.exit(main())

 

Hello,

I am creating a script that retrieves information from the vm, hosts and datastores, but I am having problems with the datastores and I do not know why...

It returns this error:

line 219, in main
statCounter = BuildQuery(perfManager, (StatCheck(perf_dict, datastore.disk.capacity)), "", datastore, interval)
AttributeError: 'vim.Datastore' object has no attribute 'disk'

 

With VMs and Hosts it is working, but it does not retrieve information about datastores...

 

Reply
0 Kudos
2 Replies
scott28tt
VMware Employee
VMware Employee

Your question really belongs in one of the sub-forums here: https://communities.vmware.com/t5/vSphere/ct-p/4572

A moderator should move it there for you.

 


-------------------------------------------------------------------------------------------------------------------------------------------------------------

Although I am a VMware employee I contribute to VMware Communities voluntarily (ie. not in any official capacity)
VMware Training & Certification blog
Reply
0 Kudos
nalagdrol
Contributor
Contributor

Ok! Seems like now it is in the correct category 🙂 

Reply
0 Kudos