forked from shelleg/prometheus_libvirt_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibvirt_exporter.py
More file actions
318 lines (236 loc) · 9.5 KB
/
libvirt_exporter.py
File metadata and controls
318 lines (236 loc) · 9.5 KB
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
from __future__ import print_function
import sys
import argparse
import libvirt
import sched
import time
import os
import socket
from prometheus_client import start_http_server, Gauge
from xml.etree import ElementTree
import keystoneclient.session
import keystoneclient.client
import novaclient.client
import novaclient.exceptions
parser = argparse.ArgumentParser(description='libvirt_exporter scrapes domains metrics from libvirt daemon')
parser.add_argument('-si','--scrape_interval', help='scrape interval for metrics in seconds', default= 5)
parser.add_argument('-uri','--uniform_resource_identifier', help='Libvirt Uniform Resource Identifier', default= "qemu:///system")
parser.add_argument("-v", "--verbose", action="count")
parser.add_argument("--no-disable", default=False, action="store_true")
parser.add_argument("--region", default=os.environ.get('OS_REGION_NAME'))
parser.add_argument(
'--os-interface',
metavar='<interface>',
dest='interface',
choices=['admin', 'public', 'internal'],
default=os.environ.get('OS_INTERFACE', 'admin'),
help=('Select an interface type.'
' Valid interface types: [admin, public, internal].'
' (Env: OS_INTERFACE)'),
)
keystoneclient.session.Session.register_cli_options(parser)
keystoneclient.auth.register_argparse_arguments(
parser, sys.argv[1:], default="password")
args_os = parser.parse_args()
auth = keystoneclient.auth.load_from_argparse_arguments(args_os)
keystonesession = keystoneclient.session.Session.load_from_cli_options(args_os, auth=auth)
keystone = keystoneclient.client.Client(auth_url=auth.auth_url, session=keystonesession, interface=args_os.interface)
nova = novaclient.client.Client("2", session=keystonesession, interface=args_os.interface, region_name=args_os.region)
args = vars(parser.parse_args())
uri = args["uniform_resource_identifier"]
tenant_instance_cache = {}
tenant_name_instance_cache = {}
def add_tenant_instance_relation(uuid):
server = nova.servers.get(uuid)
tenant_instance_cache[server.id] = server.tenant_id
print(tenant_instance_cache)
def update_tenant_instance_relation():
tenant_instance_cache.clear()
hostname = socket.gethostbyaddr(socket.gethostname())[0]
server = nova.servers.list(search_opts={"all_tenants": 1, "host": hostname})
for srv in server:
tenant_instance_cache[srv.id] = srv.tenant_id
print(tenant_instance_cache)
def add_tenant_name_instance_relation(uuid):
server = nova.servers.get(uuid)
project = keystone.projects.get(server.tenant_id)
tenant_name_instance_cache[server.id] = project.name
print(tenant_name_instance_cache)
def update_tenant_name_instance_relation():
tenant_name_instance_cache.clear()
hostname = socket.gethostbyaddr(socket.gethostname())[0]
server = nova.servers.list(search_opts={"all_tenants": 1, "host": hostname})
for srv in server:
project = keystone.projects.get(srv.tenant_id)
tenant_name_instance_cache[srv.id] = project.name
print(tenant_name_instance_cache)
def get_tenant(uuid):
max_retries = 3
for i in range(max_retries):
try:
tenant_id = tenant_instance_cache[uuid]
return tenant_id
except KeyError as e:
add_tenant_instance_relation(uuid)
continue
return None
def get_tenant_name(uuid):
max_retries = 3
for i in range(max_retries):
try:
tenant_name = tenant_name_instance_cache[uuid]
return tenant_name
except KeyError as e:
add_tenant_name_instance_relation(uuid)
continue
return None
def connect_to_uri(uri):
conn = libvirt.open(uri)
if conn == None:
print('Failed to open connection to ' + uri, file = sys.stderr)
else:
print('Successfully connected to ' + uri)
return conn
def get_domains(conn):
domains = []
for id in conn.listDomainsID():
dom = conn.lookupByID(id)
if dom == None:
print('Failed to find the domain ' + dom.name(), file=sys.stderr)
else:
domains.append(dom)
if len(domains) == 0:
print('No running domains in URI')
return None
else:
return domains
def get_metrics_collections(dom, metric_names, labels, stats):
dimensions = []
metrics_collection = {}
labels['uuid'] = dom.UUIDString()
labels['project_id'] = get_tenant(dom.UUIDString())
labels['project_name'] = get_tenant_name(dom.UUIDString())
for mn in metric_names:
if type(stats) is list:
dimensions = [[stats[0][mn], labels]]
elif type(stats) is dict:
dimensions = [[stats[mn], labels]]
metrics_collection[mn] = dimensions
return metrics_collection
def get_metrics_multidim_collections(dom, metric_names, device):
tree = ElementTree.fromstring(dom.XMLDesc())
targets = []
for target in tree.findall("devices/" + device + "/target"): # !
targets.append(target.get("dev"))
metrics_collection = {}
for mn in metric_names:
dimensions = []
for target in targets:
labels = {'domain': dom.name()}
labels['target_device'] = target
labels['uuid'] = dom.UUIDString()
labels['project_id'] = get_tenant(dom.UUIDString())
labels['project_name'] = get_tenant_name(dom.UUIDString())
if device == "interface":
stats = dom.interfaceStats(target) # !
elif device == "disk":
stats= dom.blockStats(target)
stats = dict(zip(metric_names, stats))
dimension = [stats[mn], labels]
dimensions.append(dimension)
labels = None
metrics_collection[mn] = dimensions
return metrics_collection
def add_metrics(dom, header_mn, g_dict, dom_list):
labels = {'domain':dom.name()}
if header_mn == "libvirt_cpu_stats_":
stats = dom.getCPUStats(True)
metric_names = stats[0].keys()
metrics_collection = get_metrics_collections(dom, metric_names, labels, stats)
unit = "_nanosecs"
elif header_mn == "libvirt_mem_stats_":
stats = dom.memoryStats()
metric_names = stats.keys()
metrics_collection = get_metrics_collections(dom, metric_names, labels, stats)
unit = ""
elif header_mn == "libvirt_block_stats_":
metric_names = \
['read_requests_issued',
'read_bytes' ,
'write_requests_issued',
'write_bytes',
'errors_number']
metrics_collection = get_metrics_multidim_collections(dom, metric_names, device="disk")
unit = ""
elif header_mn == "libvirt_interface_":
metric_names = \
['read_bytes',
'read_packets',
'read_errors',
'read_drops',
'write_bytes',
'write_packets',
'write_errors',
'write_drops']
metrics_collection = get_metrics_multidim_collections(dom, metric_names, device="interface")
unit = ""
for mn in metrics_collection:
metric_name = header_mn + mn + unit
dimensions = metrics_collection[mn]
if metric_name not in g_dict.keys():
metric_help = 'help'
labels_names = metrics_collection[mn][0][1].keys()
g_dict[metric_name] = Gauge(metric_name, metric_help, labels_names)
for dimension in dimensions:
dimension_metric_value = dimension[0]
dimension_label_values = dimension[1].values()
g_dict[metric_name].labels(*dimension_label_values).set(dimension_metric_value)
dom_list[dom.name()][metric_name] = dimension_label_values
else:
for dimension in dimensions:
dimension_metric_value = dimension[0]
dimension_label_values = dimension[1].values()
g_dict[metric_name].labels(*dimension_label_values).set(dimension_metric_value)
dom_list[dom.name()][metric_name] = dimension_label_values
return g_dict
def job(dom_list, uri, g_dict, scheduler):
print('BEGIN JOB :', time.time())
conn = connect_to_uri(uri)
domains = get_domains(conn)
while domains is None:
domains = get_domains(conn)
time.sleep(int(args["scrape_interval"]))
for dom in domains:
if dom.name() in dom_list.keys():
dom_list[dom.name()].clear()
for key, value in dom_list.iteritems():
for d_key, d_value in value.iteritems():
print("Start to remove ", d_key, d_value)
g_dict[d_key].remove(*d_value)
dom_list.clear()
for dom in domains:
print(dom.name())
dom_list[dom.name()] = {}
headers_mn = ["libvirt_cpu_stats_", "libvirt_mem_stats_", \
"libvirt_block_stats_", "libvirt_interface_"]
for header_mn in headers_mn:
g_dict = add_metrics(dom, header_mn, g_dict, dom_list)
conn.close()
print('FINISH JOB :', time.time())
scheduler.enter((int(args["scrape_interval"])), 1, job, (dom_list, uri, g_dict, scheduler))
def update_tenant(scheduler):
print('Start updating tenant information', time.time())
update_tenant_instance_relation()
update_tenant_name_instance_relation()
scheduler.enter(int(args["scrape_interval"])*3600, 2, update_tenant, (scheduler,))
def main():
start_http_server(9177)
g_dict = {}
dom_list = {}
scheduler = sched.scheduler(time.time, time.sleep)
print('START:', time.time())
update_tenant(scheduler)
job(dom_list, uri, g_dict, scheduler)
scheduler.run()
if __name__ == '__main__':
main()