/
libvirt-influxdb.py
270 lines (262 loc) · 9.62 KB
/
libvirt-influxdb.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
#!/usr/bin/python
import logging
import time
import ConfigParser
import json
import xml.etree.ElementTree
import datetime
import libvirt
import signal
from daemon import runner
from influxdb import InfluxDBClient
from threading import Timer
class LibvirtInflux():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/tty'
self.stderr_path = '/dev/tty'
self.pidfile_path = '/var/run/libvirt-influxdb.pid'
self.pidfile_timeout = 5
self.connect_influx(
config.get('influxdb', 'influxdb_host'),
config.getint('influxdb', 'influxdb_port'),
config.get('influxdb', 'influxdb_username'),
config.get('influxdb', 'influxdb_password'),
config.get('influxdb', 'influxdb_database')
)
def run(self):
logger.info('Starting collector')
if config.getboolean('libvirt_vcpus', 'enabled'):
interval = config.getint('libvirt_vcpus', 'interval')
logger.info('Enabling vcpu metrics (interval: %s)' % interval)
self.rt_vcpus = RepeatedTimer(interval, self.libvirt_vcpus)
if config.getboolean('libvirt_interfaces', 'enabled'):
interval = config.getint('libvirt_interfaces', 'interval')
logger.info('Enabling netif metrics (interval: %s)' % interval)
self.rt_interfaces = RepeatedTimer(interval, self.libvirt_interfaces)
if config.getboolean('libvirt_memory', 'enabled'):
interval = config.getint('libvirt_memory', 'interval')
logger.info('Enabling memory metrics (interval: %s)' % interval)
self.rt_memory = RepeatedTimer(interval, self.libvirt_memory)
if config.getboolean('libvirt_block', 'enabled'):
interval = config.getint('libvirt_block', 'interval')
logger.info('Enabling block device metrics (interval: %s)' % interval)
self.rt_block = RepeatedTimer(interval, self.libvirt_block)
while True:
time.sleep(10)
def connect_influx(self, host, port, username, password, database):
self.influxdbclient = InfluxDBClient(host, port, username, password, database)
def libvirt_vcpus(self):
logger.debug('Collecting vcpu metrics')
try:
conn = libvirt.openReadOnly()
if conn is None:
raise Exception('Failed to open connection to the hypervisor')
points = []
for id in conn.listDomainsID():
dom = conn.lookupByID(id)
vcpus = {}
for vcpu in dom.vcpus()[0]:
if vcpu[1] == libvirt.VIR_VCPU_OFFLINE:
state = "offline"
elif vcpu[1] == libvirt.VIR_VCPU_RUNNING:
state = "running"
elif vcpu[1] == libvirt.VIR_VCPU_BLOCKED:
state = "blocked"
elif vcpu[1] == libvirt.VIR_VCPU_LAST:
state = "last"
else:
state = "unknown"
vcpus[vcpu[0]] = { # virtual CPU number
"state": state, # value from virVcpuState
"cpu_time": vcpu[2], # CPU time used, in nanoseconds
"cpu": vcpu[3] # real CPU number, or -1 if offline
}
points.append({
"measurement": 'libvirt_vcpus',
"tags": {
"project_uuid": self.nova_metadata(dom)['project']['uuid'],
"project_name": self.nova_metadata(dom)['project']['name'],
"instance_uuid": dom.UUIDString(),
"libvirt_name": dom.name(),
"libvirt_domid": dom.ID(),
"cpu_number": vcpu[0]
},
"time": self.now(),
"fields": {
"state": vcpus[0]['state'],
"cpu_time": vcpus[0]['cpu_time']
}
})
logger.debug('Sending %s vcpu points to influxdb' % len(points))
self.influxdbclient.write_points(points)
return points
except Exception, e:
logger.error("error: %s" % e)
def libvirt_interfaces(self):
logger.debug('Collecting interfaces metrics')
try:
conn = libvirt.openReadOnly()
if conn is None:
raise Exception('Failed to open connection to the hypervisor')
points = []
for id in conn.listDomainsID():
dom = conn.lookupByID(id)
for dev in self.domain_xml(dom).findall("devices/interface/target"):
devname = dev.get("dev")
stats = dom.interfaceStats(devname)
points.append({
"measurement": "libvirt_interfaces",
"tags": {
"project_uuid": self.nova_metadata(dom)['project']['uuid'],
"project_name": self.nova_metadata(dom)['project']['name'],
"instance_uuid": dom.UUIDString(),
"libvirt_name": dom.name(),
"libvirt_domid": dom.ID(),
"device_name": devname
},
"time": self.now(),
"fields": {
"rx_bytes": stats[0],
"rx_packets": stats[1],
"rx_errs": stats[2],
"rx_drop": stats[3],
"tx_bytes": stats[4],
"tx_packets": stats[5],
"tx_errs": stats[6],
"tx_drop": stats[7]
}
})
logger.debug('Sending %s interfaces points to influxdb' % len(points))
self.influxdbclient.write_points(points)
return points
except Exception, e:
logger.error("error: %s" % e)
def libvirt_memory(self):
logger.debug('Collecting memory metrics')
try:
conn = libvirt.openReadOnly()
if conn is None:
raise Exception('Failed to open connection to the hypervisor')
points = []
for id in conn.listDomainsID():
dom = conn.lookupByID(id)
points.append({
"measurement": "libvirt_memory",
"tags": {
"project_uuid": self.nova_metadata(dom)['project']['uuid'],
"project_name": self.nova_metadata(dom)['project']['name'],
"instance_uuid": dom.UUIDString(),
"libvirt_name": dom.name(),
"libvirt_domid": dom.ID()
},
"time": self.now(),
"fields": {
"actual": dom.memoryStats()['actual'],
"rss": dom.memoryStats()['rss']
}
})
logger.debug('Sending %s memory points to influxdb' % len(points))
self.influxdbclient.write_points(points)
return points
except Exception, e:
logger.error("error: %s" % e)
def libvirt_block(self):
logger.debug('Collecting block device metrics')
try:
conn = libvirt.openReadOnly()
if conn is None:
raise Exception('Failed to open connection to the hypervisor')
points = []
for id in conn.listDomainsID():
dom = conn.lookupByID(id)
for dev in self.domain_xml(dom).findall("devices/disk/target"):
devname = dev.get("dev")
stats = dom.blockStats(devname)
points.append({
"measurement": "libvirt_block",
"tags": {
"project_uuid": self.nova_metadata(dom)['project']['uuid'],
"project_name": self.nova_metadata(dom)['project']['name'],
"instance_uuid": dom.UUIDString(),
"libvirt_name": dom.name(),
"libvirt_domid": dom.ID()
},
"time": self.now(),
"fields": {
"read_ops": stats[0],
"read_bytes": stats[1],
"write_ops": stats[2],
"write_bytes": stats[3],
"errors": stats[4]
}
})
logger.debug('Sending %s block device points to influxdb' % len(points))
self.influxdbclient.write_points(points)
return points
except Exception, e:
logger.error("error: %s" % e)
def now(self):
return datetime.datetime.now().isoformat()
def nova_metadata(self, domain):
metadata = xml.etree.ElementTree.fromstring(
domain.metadata(libvirt.VIR_DOMAIN_METADATA_ELEMENT,
"http://openstack.org/xmlns/libvirt/nova/1.0"))
return {
"name": metadata.find("name").text,
"project": {
"uuid": metadata.find("owner/project").get("uuid"),
"name": metadata.find("owner/project").text
}
}
def domain_xml(self, domain):
return xml.etree.ElementTree.fromstring(domain.XMLDesc())
def handle_exit(self, signum, frame):
logger.info("Shutting down")
if self.rt_vcpus:
self.rt_vcpus.stop()
if self.rt_interfaces:
self.rt_interfaces.stop()
if self.rt_memory:
self.rt_memory.stop()
if self.rt_block:
self.rt_block.stop()
class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
self.start()
def _run(self):
self.is_running = False
self.start()
self.function(*self.args, **self.kwargs)
def start(self):
if not self.is_running:
self._timer = Timer(self.interval, self._run)
self._timer.start()
self.is_running = True
def stop(self):
self._timer.cancel()
self.is_running = False
config = ConfigParser.ConfigParser({
'influxdb_port': '8086',
'interval': '60',
'enabled': 'True',
'loglevel': 'INFO'
})
config.read('libvirt-influxdb.ini')
app = LibvirtInflux()
logger = logging.getLogger("libvirtinflux")
logger.setLevel(config.get('DEFAULT', 'loglevel'))
formatter = logging.Formatter('%(asctime)s %(name)-12s: %(levelname)-8s %(message)s')
handler = logging.FileHandler("/var/log/libvirt-influxdb.log")
handler.setFormatter(formatter)
logger.addHandler(handler)
daemon_runner = runner.DaemonRunner(app)
daemon_runner.daemon_context.files_preserve=[handler.stream]
daemon_runner.daemon_context.signal_map = {signal.SIGUSR1: app.handle_exit}
daemon_runner.do_action()