forked from freedomkk-qfeng/vsphere-monitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vsphere-monitor.py
273 lines (220 loc) · 11.1 KB
/
vsphere-monitor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
#!/usr/bin/env python
#coding=utf-8
"""
Written by freedomkk-qfeng
Github: https://github.com/freedomkk-qfeng
Email: [email protected]
Script to get vSphere metrics and push to Open-Falcon
Version 0.2
"""
import atexit
from pyVmomi import vim, vmodl
from pyVim.connect import SmartConnectNoSSL, Disconnect
import sys
import copy
import requests
import time
import json
import config
from datetime import timedelta
def VmInfo(vm,content,vchtime,interval,perf_dict,tags):
try:
statInt = interval/20
summary = vm.summary
stats = summary.quickStats
uptime = stats.uptimeSeconds
add_data("vm.uptime",uptime,"GAUGE",tags)
cpuUsage = 100 * float(stats.overallCpuUsage)/float(summary.runtime.maxCpuUsage)
add_data("vm.cpu.usage",cpuUsage,"GAUGE",tags)
memoryUsage = stats.guestMemoryUsage * 1024 * 1024
add_data("vm.memory.usage",memoryUsage,"GAUGE",tags)
memoryCapacity = summary.runtime.maxMemoryUsage * 1024 * 1024
add_data("vm.memory.capacity",memoryCapacity,"GAUGE",tags)
freeMemoryPercentage = 100 - (
(float(memoryUsage) / memoryCapacity) * 100
)
add_data("vm.memory.freePercent",freeMemoryPercentage,"GAUGE",tags)
statDatastoreRead = BuildQuery(content, vchtime, (perf_id(perf_dict, 'datastore.read.average')),"*", vm, interval)
DatastoreRead = (float(sum(statDatastoreRead[0].value[0].value) * 1024) / statInt)
add_data("vm.datastore.io.read_bytes",DatastoreRead,"GAUGE",tags)
statDatastoreWrite = BuildQuery(content, vchtime, (perf_id(perf_dict, 'datastore.write.average')),"*", vm, interval)
DatastoreWrite = (float(sum(statDatastoreWrite[0].value[0].value) * 1024) / statInt)
add_data("vm.datastore.io.write_bytes",DatastoreWrite,"GAUGE",tags)
statDatastoreIoRead = BuildQuery(content, vchtime, (perf_id(perf_dict, 'datastore.numberReadAveraged.average')),"*", vm, interval)
DatastoreIoRead = (float(sum(statDatastoreIoRead[0].value[0].value)) / statInt)
add_data("vm.datastore.io.read_numbers",DatastoreIoRead,"GAUGE",tags)
statDatastoreIoWrite = BuildQuery(content, vchtime, (perf_id(perf_dict, 'datastore.numberWriteAveraged.average')),"*", vm, interval)
DatastoreIoWrite = (float(sum(statDatastoreIoWrite[0].value[0].value)) / statInt)
add_data("vm.datastore.io.write_numbers",DatastoreIoWrite,"GAUGE",tags)
statDatastoreLatRead = BuildQuery(content, vchtime, (perf_id(perf_dict, 'datastore.totalReadLatency.average')), "*", vm, interval)
DatastoreLatRead = (float(sum(statDatastoreLatRead[0].value[0].value)) / statInt)
add_data("vm.datastore.io.read_latency",DatastoreLatRead,"GAUGE",tags)
statDatastoreLatWrite = BuildQuery(content, vchtime, (perf_id(perf_dict, 'datastore.totalWriteLatency.average')), "*", vm, interval)
DatastoreLatWrite = (float(sum(statDatastoreLatWrite[0].value[0].value)) / statInt)
add_data("vm.datastore.io.write_latency",DatastoreLatWrite,"GAUGE",tags)
statNetworkTx = BuildQuery(content, vchtime, (perf_id(perf_dict, 'net.transmitted.average')), "", vm, interval)
if statNetworkTx != False:
networkTx = (float(sum(statNetworkTx[0].value[0].value) * 8 * 1024) / statInt)
add_data("vm.net.if.out",networkTx,"GAUGE",tags)
statNetworkRx = BuildQuery(content, vchtime, (perf_id(perf_dict, 'net.received.average')), "", vm, interval)
if statNetworkRx != False:
networkRx = (float(sum(statNetworkRx[0].value[0].value) * 8 * 1024) / statInt)
add_data("vm.net.if.in",networkRx,"GAUGE",tags)
except Exception as error:
print "Unable to access information for host: ", vm.name
print error
pass
def HostInformation(host,datacenter_name,computeResource_name,content,perf_dict,vchtime,interval):
try:
statInt = interval/20
summary = host.summary
stats = summary.quickStats
hardware = host.hardware
tags = "datacenter=" + datacenter_name + ",cluster_name=" + computeResource_name + ",host=" + host.name
uptime = stats.uptime
add_data("esxi.uptime",uptime,"GAUGE",tags)
cpuUsage = 100 * 1000 * 1000 * float(stats.overallCpuUsage) / float(hardware.cpuInfo.numCpuCores * hardware.cpuInfo.hz)
add_data("esxi.cpu.usage",cpuUsage,"GAUGE",tags)
memoryCapacity = hardware.memorySize
add_data("esxi.memory.capacity",memoryCapacity,"GAUGE",tags)
memoryUsage = stats.overallMemoryUsage * 1024 * 1024
add_data("esxi.memory.usage",memoryUsage,"GAUGE",tags)
freeMemoryPercentage = 100 - (
(float(memoryUsage) / memoryCapacity) * 100
)
add_data("esxi.memory.freePercent",freeMemoryPercentage,"GAUGE",tags)
statNetworkTx = BuildQuery(content, vchtime, (perf_id(perf_dict, 'net.transmitted.average')), "", host, interval)
networkTx = (float(sum(statNetworkTx[0].value[0].value) * 8 * 1024) / statInt)
add_data("esxi.net.if.out",networkTx,"GAUGE",tags)
statNetworkRx = BuildQuery(content, vchtime, (perf_id(perf_dict, 'net.received.average')), "", host, interval)
networkRx = (float(sum(statNetworkRx[0].value[0].value) * 8 * 1024) / statInt)
add_data("esxi.net.if.in",networkRx,"GAUGE",tags)
add_data("esxi.alive",1,"GAUGE",tags)
except Exception as error:
print "Unable to access information for host: ", host.name
print error
pass
def perf_id(perf_dict, counter_name):
counter_key = perf_dict[counter_name]
return counter_key
def ComputeResourceInformation(computeResource,datacenter_name,content,perf_dict,vchtime,interval):
try:
hostList = computeResource.host
computeResource_name = computeResource.name
for host in hostList:
if (host.name in config.esxi_names) or (len(config.esxi_names) == 0):
HostInformation(host,datacenter_name,computeResource_name,content,perf_dict,vchtime,interval)
except Exception as error:
print "Unable to access information for compute resource: ",
computeResource.name
print error
pass
def DatastoreInformation(datastore,datacenter_name):
try:
summary = datastore.summary
name = summary.name
TYPE = summary.type
tags = "datacenter=" + datacenter_name + ",datastore=" + name + ",type=" + TYPE
capacity = summary.capacity
add_data("datastore.capacity",capacity,"GAUGE",tags)
freeSpace = summary.freeSpace
add_data("datastore.free",freeSpace,"GAUGE",tags)
freeSpacePercentage = (float(freeSpace) / capacity) * 100
add_data("datastore.freePercent",freeSpacePercentage,"GAUGE",tags)
except Exception as error:
print "Unable to access summary for datastore: ", datastore.name
print error
pass
def add_data(metric,value,conterType,tags):
data = {"endpoint":endpoint,"metric":metric,"timestamp":ts,"step":interval,"value":value,"counterType":conterType,"tags":tags}
payload.append(copy.copy(data))
def run(host,user,pwd,port,interval):
try:
si = SmartConnectNoSSL(host=host, user=user, pwd=pwd, port=port)
atexit.register(Disconnect, si)
content = si.RetrieveContent()
vchtime = si.CurrentTime()
perf_dict = {}
perfList = content.perfManager.perfCounter
for counter in perfList:
counter_full = "{}.{}.{}".format(counter.groupInfo.key, counter.nameInfo.key, counter.rollupType)
perf_dict[counter_full] = counter.key
for datacenter in content.rootFolder.childEntity:
datacenter_name = datacenter.name.encode("utf8")
datastores = datacenter.datastore
for ds in datastores:
if (ds.name in config.datastore_names) or (len(config.datastore_names) == 0):
DatastoreInformation(ds,datacenter_name)
if hasattr(datacenter.hostFolder, 'childEntity'):
hostFolder = datacenter.hostFolder
computeResourceList = []
computeResourceList = getComputeResource(hostFolder,computeResourceList)
for computeResource in computeResourceList:
ComputeResourceInformation(computeResource,datacenter_name,content,perf_dict,vchtime,interval)
if config.vm_enable == True:
obj = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True)
for vm in obj.view:
if (vm.name in config.vm_names) or (len(config.vm_names) == 0):
tags = "vm=" + vm.name
if vm.runtime.powerState == "poweredOn":
VmInfo(vm, content, vchtime, interval, perf_dict, tags)
add_data("vm.power",1,"GAUGE",tags)
else:
add_data("vm.power",0,"GAUGE",tags)
except vmodl.MethodFault as error:
print "Caught vmodl fault : " + error.msg
return False, error.msg
return True, "ok"
def getComputeResource(Folder,computeResourceList):
if hasattr(Folder, 'childEntity'):
for computeResource in Folder.childEntity:
getComputeResource(computeResource,computeResourceList)
else:
computeResourceList.append(Folder)
return computeResourceList
def hello_vcenter(vchost,username,password,port):
try:
si = SmartConnectNoSSL(
host=vchost,
user=username,
pwd=password,
port=port)
atexit.register(Disconnect, si)
return True, "ok"
except vmodl.MethodFault as error:
return False, error.msg
except Exception as e:
return False, str(e)
def BuildQuery(content, vchtime, counterId, instance, entity, interval):
perfManager = content.perfManager
metricId = vim.PerformanceManager.MetricId(counterId=counterId, instance=instance)
startTime = vchtime - timedelta(seconds=(interval + 60))
endTime = vchtime - timedelta(seconds=60)
query = vim.PerformanceManager.QuerySpec(intervalId=20, entity=entity, metricId=[metricId], startTime=startTime,
endTime=endTime)
perfResults = perfManager.QueryPerf(querySpec=[query])
if perfResults:
return perfResults
else:
return False
if __name__ == "__main__":
host = config.host
user = config.user
pwd = config.pwd
port = config.port
endpoint = config.endpoint
push_api = config.push_api
interval = config.interval
ts = int(time.time())
payload = []
success, msg = hello_vcenter(host,user,pwd,port)
if success == False:
print msg
add_data("vcenter.alive",0,"GAUGE","")
#print json.dumps(payload,indent=4)
r= requests.post(push_api, data=json.dumps(payload))
sys.exit(1)
add_data("vcenter.alive",1,"GAUGE","")
run(host,user,pwd,port,interval)
#print json.dumps(payload,indent=4)
r = requests.post(push_api, data=json.dumps(payload))