'cs_capacity') client.create_database('cs_capacity') break except Exception as err: print("{} - Can't connect to InfluxDB, sleeping.".format( datetime.datetime.now())) print(err) time.sleep(5) while True: for zone, params in config.items(): try: cs = CloudStack(endpoint=params['api_url'], key=params['api_key'], secret=params['secret_key']) mem = cs.listCapacity(type=0)['capacity'][0]['percentused'] cpu = cs.listCapacity(type=1)['capacity'][0]['percentused'] vms = cs.listVirtualMachines(state='running', listall='true')['count'] client.write_points([{ "measurement": zone + " - CPU", "fields": { "value": float(cpu) } }]) client.write_points([{ "measurement": zone + " - RAM", "fields": { "value": float(mem) } }])
class csresources: def __init__(self): tempdict = {} path = os.path.dirname(os.path.abspath(__file__)) # Read config try: f = open(path + "/../cloudstack.config", "r") config = f.readlines() except: print("Somethings wrong with your config file") sys.exit(2) for entry in config: entry = entry.replace("\n", "") temarray = entry.split("=") tempdict[temarray[0]] = temarray[1] if tempdict['verify'] is None: tempdict['verify'] = False self.cs = CloudStack(endpoint=tempdict['endpoint'], key=tempdict['key'], secret=tempdict['secret'], verify=False) def list_virtual_routers(self): routerList = [] domains = self.cs.listDomains() for domain in domains['domain']: projects = self.cs.listProjects(domainid=domain["id"]) if "project" in projects: for project in projects["project"]: routers = self.cs.listRouters(projectid=project["id"]) if "router" in routers: for router in routers["router"]: routerList.append(router) routers = self.cs.listRouters(domainid=domain["id"]) if "router" in routers: for router in routers["router"]: routerList.append(router) return routerList def list_system_vms(self): return self.cs.listSystemVms()['systemvm'] def list_capacity(self): return self.cs.listCapacity()['capacity'] def list_projects(self, domainfilter=None, projectfilter=None): projects = [] domains = self.cs.listDomains(id=domainfilter)['domain'] if projectfilter is not None and domainfilter is not None: temp = self.cs.listProjects(domainid=domainfilter, id=projectfilter) if 'project' in temp: projects += temp['project'] else: for domain in domains: temp = self.cs.listProjects(domainid=domain['id']) if 'project' in temp: for project in temp['project']: projects.append(project) return projects def list_domains(self, domainfilter=None): return self.cs.listDomains(id=domainfilter)['domain'] def list_clusters(self): return self.cs.listClusters()['cluster'] def list_offerings(self): return self.cs.listServiceOfferings()['serviceoffering'] def list_hvs(self): return self.cs.listHosts(type="Routing")['host'] def get_hvstructure(self, cluster, withvm=1): hvstatus = [] domains = self.cs.listDomains() vmdict = [] if 'cluster.memory.allocated.capacity.disablethreshold' in cluster[ 'resourcedetails']: memthreshold = cluster['resourcedetails'][ 'cluster.memory.allocated.capacity.disablethreshold'] else: memthreshold = 1 if 'cluster.cpu.allocated.capacity.disablethreshold' in cluster[ 'resourcedetails']: cputhreshold = cluster['resourcedetails'][ 'cluster.cpu.allocated.capacity.disablethreshold'] else: cputhreshold = 1 memovercommit = cluster['resourcedetails']['memoryOvercommitRatio'] cpuovercommit = cluster['resourcedetails']['cpuOvercommitRatio'] clusterid = cluster['id'] hosts = self.cs.listHosts(clusterid=clusterid) #Get Host list for host in hosts['host']: if host['type'] == "Routing": hvstatus.append({ 'name': host['name'], 'cpu': (float(host['cpunumber'] * host['cpuspeed']) * float(cpuovercommit)) * float(cputhreshold), 'mem': ((host['memorytotal'] * float(memovercommit)) * float(memthreshold)) / 1024, 'memfree': ((host['memorytotal'] * float(memthreshold)) - host['memoryused']) / 1024, 'cpufree': ((float(host['cpunumber'] * host['cpuspeed']) * float(cpuovercommit)) * float(cputhreshold)) - (float(host['cpuallocated'].replace("%", "")) * ((host['cpunumber'] * host['cpuspeed']) / 100)), 'ratio': None, 'vms': [], }) ##Split this as an extra function!!!!!! if withvm == 1: # Get VM list for domain in domains['domain']: projects = self.cs.listProjects(domainid=domain['id']) if "project" in projects.keys(): for project in projects['project']: vms = self.cs.listVirtualMachines( projectid=project['id']) if "virtualmachine" in vms: for vm in vms['virtualmachine']: vmdict.append(vm) #Add VMs to their Hypervisors for vm in vmdict: for hv in hvstatus: if "hostname" in vm: if vm['hostname'] == hv['name']: hv['vms'].append({ 'name': vm['name'], 'cpu': vm['cpunumber'] * vm['cpuspeed'], 'mem': vm['memory'] * 1024, 'instance': vm['instancename'], }) return hvstatus
def get_stats(): timeout = 300 stats = dict() hvmrunning = defaultdict(int) hvmstopped = defaultdict(int) hvmstopping = defaultdict(int) hvmstarting = defaultdict(int) cs = CloudStack(endpoint=API_MONITORS, key=APIKEY_MONITORS, secret=SECRET_MONITORS, timeout=timeout) logger('verb', "get_stats calls API %s KEY %s SECRET %s" % (API_MONITORS, APIKEY_MONITORS, SECRET_MONITORS)) try: logger('verb', "Performing listhosts API call") hypervisors = cs_list(cs, 'listHosts', 'host', type='Routing', resourcestate='Enabled', state='Up') logger('verb', "Completed listhosts API call") except Exception: logger('warn', "status err Unable to connect to CloudStack URL at %s for Hosts" % API_MONITORS) for h in hypervisors: metricnameMemUsed = METRIC_DELIM.join([h['name'].lower(), h['podname'].lower(), re.sub(r"\s+", '-', h['zonename'].lower()), 'memoryused']) metricnameMemTotal = METRIC_DELIM.join([h['name'].lower(), h['podname'].lower(), re.sub(r"\s+", '-', h['zonename'].lower()), 'memorytotal']) metricnameMemAlloc = METRIC_DELIM.join([h['name'].lower(), h['podname'].lower(), re.sub(r"\s+", '-', h['zonename'].lower()), 'memoryallocated']) metricnameMemAllocPercent = METRIC_DELIM.join([h['name'].lower(), h['podname'].lower(), re.sub(r"\s+", '-', h['zonename'].lower()), 'memoryallocatedpercent']) metricnameCpuAlloc = METRIC_DELIM.join([h['name'].lower(), h['podname'].lower(), re.sub(r"\s+", '-', h['zonename'].lower()), 'cpuallocated']) try: memorytotal = int(h['memorytotal']) memoryallocated = int(h['memoryallocated']) stats[metricnameMemUsed] = h['memoryused'] stats[metricnameMemTotal] = memorytotal stats[metricnameMemAlloc] = memoryallocated stats[metricnameMemAllocPercent] = round(memoryallocated / memorytotal, 4) if memorytotal > 0 else 0 cpuallocated = h['cpuallocated'].replace("%", "") stats[metricnameCpuAlloc] = cpuallocated logger('verb', "readings : %s memory used %s " % (h['name'], h['memoryused'])) except (TypeError, ValueError, KeyError): pass # collect disk metrics try: logger('verb', "Performing liststoragepools API call") pools = cs_list(cs, 'listStoragePools', 'storagepool') logger('verb', "Completed liststoragepools API call") except Exception: logger('warn', "status err Unable to connect to CloudStack URL at %s for storage pools" % API_MONITORS) for h in pools: name = h['name'].split()[0] # to avoid "Local Storage" in the pool name metricnameDiskAlloc = METRIC_DELIM.join([name.lower(), h['podname'].lower(), re.sub(r"\s+", '-', h['zonename'].lower()), 'disksizeallocated']) metricnameDiskAllocPercent = METRIC_DELIM.join([name.lower(), h['podname'].lower(), re.sub(r"\s+", '-', h['zonename'].lower()), 'disksizeallocatedpercent']) metricnameDiskUsed = METRIC_DELIM.join([name.lower(), h['podname'].lower(), re.sub(r"\s+", '-', h['zonename'].lower()), 'disksizeused']) metricnameDiskTotal = METRIC_DELIM.join([name.lower(), h['podname'].lower(), re.sub(r"\s+", '-', h['zonename'].lower()), 'disksizetotal']) try: disksizeallocated = int(h['disksizeallocated']) disksizetotal = int(h['disksizetotal']) stats[metricnameDiskAlloc] = disksizeallocated stats[metricnameDiskUsed] = h['disksizeused'] stats[metricnameDiskTotal] = h['disksizetotal'] stats[metricnameDiskAllocPercent] = round(disksizeallocated / disksizetotal, 4) if disksizetotal > 0 else 0 except (TypeError, ValueError, KeyError): pass # collect number of active console sessions try: logger('verb', "Performing listSystemVms API call") systemvms = cs_list(cs, 'listSystemVms', 'systemvm', systemvmtype='consoleproxy') logger('verb', "Completed listSystemVms API call") except Exception: logger('warn', "status err Unable to connect to CloudStack URL at %s for SystemVms" % API_MONITORS) for systemvm in systemvms: metricnameSessions = METRIC_DELIM.join(['activeviewersessions', systemvm['zonename'].lower(), systemvm['name'].lower(), 'activeviewersessions']) if 'activeviewersessions' in systemvm: stats[metricnameSessions] = systemvm['activeviewersessions'] # collect number of zones, available public ips and VMs try: logger('verb', "Performing listZones API call") zones = cs_list(cs, 'listZones', 'zone', showcapacities='true') logger('verb', "Completed listZones API call") except Exception: logger('warn', "status err Unable to connect to CloudStack URL at %s for ListZone" % API_MONITORS) for zone in zones: metricnameIpAllocated = METRIC_DELIM.join(['zonepublicipallocated', zone['name'].lower(), 'zonepublicipallocated']) metricnameIpTotal = METRIC_DELIM.join(['zonepubliciptotal', zone['name'].lower(), 'zonepubliciptotal']) metricnameIpAllocatedPercent = METRIC_DELIM.join(['zonepublicippercent', zone['name'].lower(), 'zonepublicippercent']) metricnameVmZoneTotalRunning = METRIC_DELIM.join(['zonevmtotalrunning', zone['name'].lower(), 'zonevmtotalrunning']) metricnameVmZoneTotalRunningMicro = METRIC_DELIM.join(['zonevmtotalrunningmicro', zone['name'].lower(), 'zonevmtotalrunningmicro']) metricnameVmZoneTotalRunningTiny = METRIC_DELIM.join(['zonevmtotalrunningtiny', zone['name'].lower(), 'zonevmtotalrunningtiny']) metricnameVmZoneTotalRunningSmall = METRIC_DELIM.join(['zonevmtotalrunningsmall', zone['name'].lower(), 'zonevmtotalrunningsmall']) metricnameVmZoneTotalRunningMedium = METRIC_DELIM.join(['zonevmtotalrunningmedium', zone['name'].lower(), 'zonevmtotalrunningmedium']) metricnameVmZoneTotalRunningLarge = METRIC_DELIM.join(['zonevmtotalrunninglarge', zone['name'].lower(), 'zonevmtotalrunninglarge']) metricnameVmZoneTotalRunningXLarge = METRIC_DELIM.join(['zonevmtotalrunningxlarge', zone['name'].lower(), 'zonevmtotalrunningxlarge']) metricnameVmZoneTotalRunningHuge = METRIC_DELIM.join(['zonevmtotalrunninghuge', zone['name'].lower(), 'zonevmtotalrunninghuge']) metricnameVmZoneTotalRunningMega = METRIC_DELIM.join(['zonevmtotalrunningmega', zone['name'].lower(), 'zonevmtotalrunningmega']) metricnameVmZoneTotalRunningTitan = METRIC_DELIM.join(['zonevmtotalrunningtitan', zone['name'].lower(), 'zonevmtotalrunningtitan']) metricnameVmZoneTotalStopped = METRIC_DELIM.join(['zonevmtotalstopped', zone['name'].lower(), 'zonevmtotalstopped']) metricnameVmZoneTotalStoppedMicro = METRIC_DELIM.join(['zonevmtotalstoppedmicro', zone['name'].lower(), 'zonevmtotalstoppedmicro']) metricnameVmZoneTotalStoppedTiny = METRIC_DELIM.join(['zonevmtotalstoppedtiny', zone['name'].lower(), 'zonevmtotalstoppedtiny']) metricnameVmZoneTotalStoppedSmall = METRIC_DELIM.join(['zonevmtotalstoppedsmall', zone['name'].lower(), 'zonevmtotalstoppedsmall']) metricnameVmZoneTotalStoppedMedium = METRIC_DELIM.join(['zonevmtotalstoppedmedium', zone['name'].lower(), 'zonevmtotalstoppedmedium']) metricnameVmZoneTotalStoppedLarge = METRIC_DELIM.join(['zonevmtotalstoppedlarge', zone['name'].lower(), 'zonevmtotalstoppedlarge']) metricnameVmZoneTotalStoppedXLarge = METRIC_DELIM.join(['zonevmtotalstoppedxlarge', zone['name'].lower(), 'zonevmtotalstoppedxlarge']) metricnameVmZoneTotalStoppedHuge = METRIC_DELIM.join(['zonevmtotalstoppedhuge', zone['name'].lower(), 'zonevmtotalstoppedhuge']) metricnameVmZoneTotalStoppedMega = METRIC_DELIM.join(['zonevmtotalstoppedmega', zone['name'].lower(), 'zonevmtotalstoppedmega']) metricnameVmZoneTotalStoppedTitan = METRIC_DELIM.join(['zonevmtotalstoppedtitan', zone['name'].lower(), 'zonevmtotalstoppedtitan']) metricnameVmZoneTotalStopping = METRIC_DELIM.join(['zonevmtotalstopping', zone['name'].lower(), 'zonevmtotalstopping']) metricnameVmZoneTotalStarting = METRIC_DELIM.join(['zonevmtotalstarting', zone['name'].lower(), 'zonevmtotalstarting']) metricnameVmZoneTotalMicro = METRIC_DELIM.join(['zonevmtotalmicro', zone['name'].lower(), 'zonevmtotalmicro']) metricnameVmZoneTotalTiny = METRIC_DELIM.join(['zonevmtotaltiny', zone['name'].lower(), 'zonevmtotaltiny']) metricnameVmZoneTotalSmall = METRIC_DELIM.join(['zonevmtotalsmall', zone['name'].lower(), 'zonevmtotalsmall']) metricnameVmZoneTotalMedium = METRIC_DELIM.join(['zonevmtotalmedium', zone['name'].lower(), 'zonevmtotalmedium']) metricnameVmZoneTotalLarge = METRIC_DELIM.join(['zonevmtotallarge', zone['name'].lower(), 'zonevmtotallarge']) metricnameVmZoneTotalXLarge = METRIC_DELIM.join(['zonevmtotalxlarge', zone['name'].lower(), 'zonevmtotalxlarge']) metricnameVmZoneTotalHuge = METRIC_DELIM.join(['zonevmtotalhuge', zone['name'].lower(), 'zonevmtotalhuge']) metricnameVmZoneTotalMega = METRIC_DELIM.join(['zonevmtotalmega', zone['name'].lower(), 'zonevmtotalmega']) metricnameVmZoneTotalTitan = METRIC_DELIM.join(['zonevmtotaltitan', zone['name'].lower(), 'zonevmtotaltitan']) metricnameVmZoneTotal = METRIC_DELIM.join(['zonevmtotal', zone['name'].lower(), 'zonevmtotal']) metricnameZonesCount = METRIC_DELIM.join(['zonescount', 'zonescount']) metricnameHostZoneTotal = METRIC_DELIM.join(['zonehosttotal', zone['name'].lower(), 'zonehosttotal']) metricnameVMZoneRAMavgSize = METRIC_DELIM.join(['zonevmramavgsize', zone['name'].lower(), 'zonevmramavgsize']) metricnameVMZoneCPUavgSize = METRIC_DELIM.join(['zonevmcpuavgsize', zone['name'].lower(), 'zonevmcpuavgsize']) # collect number of virtual machines zoneid = zone['id'] try: logger('verb', "Performing listVirtualMachines API call") virtualmachines = cs_list(cs, 'listVirtualMachines', 'virtualmachine', details='all', zoneid=zoneid) logger('verb', "Completed listVirtualMachines API call") except Exception: logger('warn', "status err Unable to connect to CloudStack URL at %s for ListVms" % API_MONITORS) virtualMachineZoneRunningCount = 0 virtualMachineZoneRunningMicroCount = 0 virtualMachineZoneRunningTinyCount = 0 virtualMachineZoneRunningSmallCount = 0 virtualMachineZoneRunningMediumCount = 0 virtualMachineZoneRunningLargeCount = 0 virtualMachineZoneRunningXLargeCount = 0 virtualMachineZoneRunningHugeCount = 0 virtualMachineZoneRunningMegaCount = 0 virtualMachineZoneRunningTitanCount = 0 virtualMachineZoneStoppedCount = 0 virtualMachineZoneStoppedMicroCount = 0 virtualMachineZoneStoppedTinyCount = 0 virtualMachineZoneStoppedSmallCount = 0 virtualMachineZoneStoppedMediumCount = 0 virtualMachineZoneStoppedLargeCount = 0 virtualMachineZoneStoppedXLargeCount = 0 virtualMachineZoneStoppedHugeCount = 0 virtualMachineZoneStoppedMegaCount = 0 virtualMachineZoneStoppedTitanCount = 0 virtualMachineZoneStartingCount = 0 virtualMachineZoneStoppingCount = 0 virtualMachineZoneMicro = 0 virtualMachineZoneTiny = 0 virtualMachineZoneSmall = 0 virtualMachineZoneMedium = 0 virtualMachineZoneLarge = 0 virtualMachineZoneXLarge = 0 virtualMachineZoneHuge = 0 virtualMachineZoneMega = 0 virtualMachineZoneTitan = 0 cpu = 0 ram = 0 for virtualmachine in virtualmachines: cpu += virtualmachine['cpunumber'] ram += virtualmachine['memory'] if virtualmachine['state'] == 'Running': virtualMachineZoneRunningCount += 1 elif virtualmachine['state'] == 'Stopped': virtualMachineZoneStoppedCount += 1 elif virtualmachine['state'] == 'Stopping': virtualMachineZoneStartingCount += 1 elif virtualmachine['state'] == 'Starting': virtualMachineZoneStoppingCount += 1 if virtualmachine['serviceofferingname'] == 'Micro': virtualMachineZoneMicro += 1 if virtualmachine['state'] == 'Running': virtualMachineZoneRunningMicroCount += 1 else: virtualMachineZoneStoppedMicroCount += 1 elif virtualmachine['serviceofferingname'] == 'Tiny': virtualMachineZoneTiny += 1 if virtualmachine['state'] == 'Running': virtualMachineZoneRunningTinyCount += 1 else: virtualMachineZoneStoppedTinyCount += 1 elif virtualmachine['serviceofferingname'] == 'Small': virtualMachineZoneSmall += 1 if virtualmachine['state'] == 'Running': virtualMachineZoneRunningSmallCount += 1 else: virtualMachineZoneStoppedSmallCount += 1 elif virtualmachine['serviceofferingname'] == 'Medium': virtualMachineZoneMedium += 1 if virtualmachine['state'] == 'Running': virtualMachineZoneRunningMediumCount += 1 else: virtualMachineZoneStoppedMediumCount += 1 elif virtualmachine['serviceofferingname'] == 'Large': virtualMachineZoneLarge += 1 if virtualmachine['state'] == 'Running': virtualMachineZoneRunningLargeCount += 1 else: virtualMachineZoneStoppedLargeCount += 1 elif virtualmachine['serviceofferingname'] == 'Extra-large': virtualMachineZoneXLarge += 1 if virtualmachine['state'] == 'Running': virtualMachineZoneRunningXLargeCount += 1 else: virtualMachineZoneStoppedXLargeCount += 1 elif virtualmachine['serviceofferingname'] == 'Huge': virtualMachineZoneHuge += 1 if virtualmachine['state'] == 'Running': virtualMachineZoneRunningHugeCount += 1 else: virtualMachineZoneStoppedHugeCount += 1 elif virtualmachine['serviceofferingname'] == 'Mega': virtualMachineZoneMega += 1 if virtualmachine['state'] == 'Running': virtualMachineZoneRunningMegaCount += 1 else: virtualMachineZoneStoppedMegaCount += 1 elif virtualmachine['serviceofferingname'] == 'Titan': virtualMachineZoneTitan += 1 if virtualmachine['state'] == 'Running': virtualMachineZoneRunningTitanCount += 1 else: virtualMachineZoneStoppedTitanCount += 1 if len(virtualmachines) == 0: ramavg = 0 cpuavg = 0 else: ram = (ram / 1024) ramavg = (ram / len(virtualmachines)) cpuavg = (cpu / len(virtualmachines)) stats[metricnameVMZoneRAMavgSize] = ramavg stats[metricnameVMZoneCPUavgSize] = cpuavg stats[metricnameVmZoneTotal] = len(virtualmachines) stats[metricnameVmZoneTotalRunning] = virtualMachineZoneRunningCount stats[metricnameVmZoneTotalRunningMicro] = virtualMachineZoneRunningMicroCount stats[metricnameVmZoneTotalRunningTiny] = virtualMachineZoneRunningTinyCount stats[metricnameVmZoneTotalRunningSmall] = virtualMachineZoneRunningSmallCount stats[metricnameVmZoneTotalRunningMedium] = virtualMachineZoneRunningMediumCount stats[metricnameVmZoneTotalRunningLarge] = virtualMachineZoneRunningLargeCount stats[metricnameVmZoneTotalRunningXLarge] = virtualMachineZoneRunningXLargeCount stats[metricnameVmZoneTotalRunningHuge] = virtualMachineZoneRunningHugeCount stats[metricnameVmZoneTotalRunningMega] = virtualMachineZoneRunningMegaCount stats[metricnameVmZoneTotalRunningTitan] = virtualMachineZoneRunningTitanCount stats[metricnameVmZoneTotalStopped] = virtualMachineZoneStoppedCount stats[metricnameVmZoneTotalStoppedMicro] = virtualMachineZoneStoppedMicroCount stats[metricnameVmZoneTotalStoppedTiny] = virtualMachineZoneStoppedTinyCount stats[metricnameVmZoneTotalStoppedSmall] = virtualMachineZoneStoppedSmallCount stats[metricnameVmZoneTotalStoppedMedium] = virtualMachineZoneStoppedMediumCount stats[metricnameVmZoneTotalStoppedLarge] = virtualMachineZoneStoppedLargeCount stats[metricnameVmZoneTotalStoppedXLarge] = virtualMachineZoneStoppedXLargeCount stats[metricnameVmZoneTotalStoppedHuge] = virtualMachineZoneStoppedHugeCount stats[metricnameVmZoneTotalStoppedMega] = virtualMachineZoneStoppedMegaCount stats[metricnameVmZoneTotalStoppedTitan] = virtualMachineZoneStoppedTitanCount stats[metricnameVmZoneTotalStopping] = virtualMachineZoneStoppingCount stats[metricnameVmZoneTotalStarting] = virtualMachineZoneStartingCount stats[metricnameVmZoneTotalMicro] = virtualMachineZoneMicro stats[metricnameVmZoneTotalTiny] = virtualMachineZoneTiny stats[metricnameVmZoneTotalSmall] = virtualMachineZoneSmall stats[metricnameVmZoneTotalMedium] = virtualMachineZoneMedium stats[metricnameVmZoneTotalLarge] = virtualMachineZoneLarge stats[metricnameVmZoneTotalXLarge] = virtualMachineZoneXLarge stats[metricnameVmZoneTotalHuge] = virtualMachineZoneHuge stats[metricnameVmZoneTotalMega] = virtualMachineZoneMega stats[metricnameVmZoneTotalTitan] = virtualMachineZoneTitan # collect number of root volumes try: logger('verb', "Performing listVolumes API call") rootvolumes = cs_list(cs, 'listVolumes', 'volume', type='ROOT', zoneid=zoneid) logger('verb', "Completed listVolumes API call") except Exception: logger('warn', "status err Unable to connect to CloudStack URL at %s for ListVolumes" % API_MONITORS) rootvolsize = 0 for rootvolume in rootvolumes: rootvolsize += rootvolume['size'] if rootvolume['vmstate'] == 'Running': # add to a dict to get the Running VMs per hypervisor host = rootvolume['storage'] hvmrunning[host] += 1 elif rootvolume['vmstate'] == 'Stopped' and not rootvolume['state'] == 'Allocated': # add to a dict to get the Stopped VMs per hypervisor host = rootvolume['storage'] hvmstopped[host] += 1 elif rootvolume['vmstate'] == 'Stopping': # add to a dict to get the Stopping VMs per hypervisor host = rootvolume['storage'] hvmstopping[host] += 1 elif rootvolume['vmstate'] == 'Starting': # add to a dict to get the Starting VMs per hypervisor host = rootvolume['storage'] hvmstarting[host] += 1 if len(rootvolumes) != 0: rootvolsize = (rootvolsize / 1073741824) rootavgsize = rootvolsize / len(rootvolumes) else: rootvolsize = 0 rootavgsize = 0 metricnameRootAvgSizeZone = METRIC_DELIM.join(['zonerootdiskavgsize', zone['name'].lower(), 'zonerootdiskavgsize']) stats[metricnameRootAvgSizeZone] = rootavgsize # add metric VMs per hypervisor for h in hypervisors: virtualMachineHTotalCount = 0 metricnameVmHTotal = METRIC_DELIM.join([h['name'].lower(), h['podname'].lower(), re.sub(r"\s+", '-', h['zonename'].lower()), 'hvmtotal']) metricnameVmHTotalRunning = METRIC_DELIM.join([h['name'].lower(), h['podname'].lower(), re.sub(r"\s+", '-', h['zonename'].lower()), 'hvmtotalrunning']) metricnameVmHTotalStarting = METRIC_DELIM.join([h['name'].lower(), h['podname'].lower(), re.sub(r"\s+", '-', h['zonename'].lower()), 'hvmtotalstarting']) metricnameVmHTotalStopping = METRIC_DELIM.join([h['name'].lower(), h['podname'].lower(), re.sub(r"\s+", '-', h['zonename'].lower()), 'hvmtotalstopping']) metricnameVmHTotalStopped = METRIC_DELIM.join([h['name'].lower(), h['podname'].lower(), re.sub(r"\s+", '-', h['zonename'].lower()), 'hvmtotalstopped']) hname = h['name'].lower() if hname in hvmrunning: virtualMachineHTotalCount = virtualMachineHTotalCount + hvmrunning[hname] stats[metricnameVmHTotalRunning] = hvmrunning[hname] else: stats[metricnameVmHTotalRunning] = 0 if hname in hvmstarting: virtualMachineHTotalCount = virtualMachineHTotalCount + hvmstarting[hname] stats[metricnameVmHTotalStarting] = hvmstarting[hname] else: stats[metricnameVmHTotalStarting] = 0 if hname in hvmstopping: virtualMachineHTotalCount = virtualMachineHTotalCount + hvmstopping[hname] stats[metricnameVmHTotalStopping] = hvmstopping[hname] else: stats[metricnameVmHTotalStopping] = 0 if hname in hvmstopped: virtualMachineHTotalCount = virtualMachineHTotalCount + hvmstopped[hname] stats[metricnameVmHTotalStopped] = hvmstopped[hname] else: stats[metricnameVmHTotalStopped] = 0 stats[metricnameVmHTotal] = virtualMachineHTotalCount for capacity in zone['capacity']: if capacity['type'] == 8: stats[metricnameIpTotal] = capacity['capacitytotal'] stats[metricnameIpAllocated] = capacity['capacityused'] stats[metricnameIpAllocatedPercent] = capacity['percentused'] stats[metricnameZonesCount] = len(zones) stats[metricnameHostZoneTotal] = len(hypervisors) # collect accounts try: logger('verb', "Performing accountStats API call") accounts_stats = cs.accountStats()['accountstats'] logger('verb', "Completed accountStats API call") except Exception: logger('err', "status err Unable to connect to CloudStack URL at %s for accountStats") stats[metric_name('accounts', 'accountscount')] = accounts_stats['total'] stats[metric_name('accounts', 'accountenabled')] = accounts_stats['enabled'] stats[metric_name('accounts', 'accountdisabled')] = accounts_stats['disabled'] # collect capacity try: capacity = cs.listCapacity(sharedonly=True)['capacity'] except Exception: logger('err', "status err Unable to connect to CloudStack URL at %s for ListCapacity") types = {0: 'memory', 1: 'cpu', 2: 'disk', 5: 'privateip', 6: 'ss', 9: 'diskalloc'} for c in capacity: def name(typ, metric): return metric_name('zonecapacity', c['zonename'].lower(), 'zonecapa{0}{1}'.format(types[typ], metric)) if c['type'] not in types: continue for metric, key in [ ('total', 'capacitytotal'), ('used', 'capacityused'), ('percentused', 'percentused'), ]: stats[name(c['type'], metric)] = c[key] return stats