1 /**
2 * collectd - src/virt.c
3 * Copyright (C) 2006-2008 Red Hat Inc.
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; only version 2 of the license is applicable.
8 *
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
17 *
18 * Authors:
19 * Richard W.M. Jones <rjones@redhat.com>
20 * Przemyslaw Szczerbik <przemyslawx.szczerbik@intel.com>
21 **/
22
23 #include "collectd.h"
24
25 #include "plugin.h"
26 #include "utils/common/common.h"
27 #include "utils/ignorelist/ignorelist.h"
28 #include "utils_complain.h"
29
30 #include <libgen.h> /* for basename(3) */
31 #include <libvirt/libvirt.h>
32 #include <libvirt/virterror.h>
33 #include <libxml/parser.h>
34 #include <libxml/tree.h>
35 #include <libxml/xpath.h>
36 #include <libxml/xpathInternals.h>
37 #include <stdbool.h>
38
39 /* Plugin name */
40 #define PLUGIN_NAME "virt"
41
42 /* Secure strcat macro assuring null termination. Parameter (n) is the size of
43 buffer (d), allowing this macro to be safe for static and dynamic buffers */
44 #define SSTRNCAT(d, s, n) \
45 do { \
46 size_t _l = strlen(d); \
47 sstrncpy((d) + _l, (s), (n)-_l); \
48 } while (0)
49
50 #ifdef LIBVIR_CHECK_VERSION
51
52 #if LIBVIR_CHECK_VERSION(0, 9, 2)
53 #define HAVE_DOM_REASON 1
54 #endif
55
56 #if LIBVIR_CHECK_VERSION(0, 9, 5)
57 #define HAVE_BLOCK_STATS_FLAGS 1
58 #define HAVE_DOM_REASON_PAUSED_SHUTTING_DOWN 1
59 #endif
60
61 #if LIBVIR_CHECK_VERSION(0, 9, 10)
62 #define HAVE_DISK_ERR 1
63 #endif
64
65 #if LIBVIR_CHECK_VERSION(0, 9, 11)
66 #define HAVE_CPU_STATS 1
67 #define HAVE_DOM_STATE_PMSUSPENDED 1
68 #define HAVE_DOM_REASON_RUNNING_WAKEUP 1
69 #endif
70
71 /*
72 virConnectListAllDomains() appeared in 0.10.2 (Sep 2012)
73 Note that LIBVIR_CHECK_VERSION appeared a year later (Dec 2013,
74 libvirt-1.2.0),
75 so in some systems which actually have virConnectListAllDomains()
76 we can't detect this.
77 */
78 #if LIBVIR_CHECK_VERSION(0, 10, 2)
79 #define HAVE_LIST_ALL_DOMAINS 1
80 #endif
81
82 #if LIBVIR_CHECK_VERSION(1, 0, 1)
83 #define HAVE_DOM_REASON_PAUSED_SNAPSHOT 1
84 #endif
85
86 #if LIBVIR_CHECK_VERSION(1, 1, 1)
87 #define HAVE_DOM_REASON_PAUSED_CRASHED 1
88 #endif
89
90 #if LIBVIR_CHECK_VERSION(1, 2, 9)
91 #define HAVE_JOB_STATS 1
92 #endif
93
94 #if LIBVIR_CHECK_VERSION(1, 2, 10)
95 #define HAVE_DOM_REASON_CRASHED 1
96 #endif
97
98 #if LIBVIR_CHECK_VERSION(1, 2, 11)
99 #define HAVE_FS_INFO 1
100 #endif
101
102 #if LIBVIR_CHECK_VERSION(1, 2, 15)
103 #define HAVE_DOM_REASON_PAUSED_STARTING_UP 1
104 #endif
105
106 #if LIBVIR_CHECK_VERSION(1, 3, 3)
107 #define HAVE_PERF_STATS 1
108 #define HAVE_DOM_REASON_POSTCOPY 1
109 #endif
110
111 #if LIBVIR_CHECK_VERSION(4, 10, 0)
112 #define HAVE_DOM_REASON_SHUTOFF_DAEMON 1
113 #endif
114 #endif /* LIBVIR_CHECK_VERSION */
115
116 /* structure used for aggregating notification-thread data*/
117 typedef struct virt_notif_thread_s {
118 pthread_t event_loop_tid;
119 int domain_event_cb_id;
120 pthread_mutex_t active_mutex; /* protects 'is_active' member access*/
121 bool is_active;
122 } virt_notif_thread_t;
123
124 /* PersistentNotification is false by default */
125 static bool persistent_notification = false;
126
127 static bool report_block_devices = true;
128 static bool report_network_interfaces = true;
129
130 /* Thread used for handling libvirt notifications events */
131 static virt_notif_thread_t notif_thread;
132
133 const char *domain_states[] = {
134 [VIR_DOMAIN_NOSTATE] = "no state",
135 [VIR_DOMAIN_RUNNING] = "the domain is running",
136 [VIR_DOMAIN_BLOCKED] = "the domain is blocked on resource",
137 [VIR_DOMAIN_PAUSED] = "the domain is paused by user",
138 [VIR_DOMAIN_SHUTDOWN] = "the domain is being shut down",
139 [VIR_DOMAIN_SHUTOFF] = "the domain is shut off",
140 [VIR_DOMAIN_CRASHED] = "the domain is crashed",
141 #ifdef HAVE_DOM_STATE_PMSUSPENDED
142 [VIR_DOMAIN_PMSUSPENDED] =
143 "the domain is suspended by guest power management",
144 #endif
145 };
146
map_domain_event_to_state(int event)147 static int map_domain_event_to_state(int event) {
148 int ret;
149 switch (event) {
150 case VIR_DOMAIN_EVENT_STARTED:
151 ret = VIR_DOMAIN_RUNNING;
152 break;
153 case VIR_DOMAIN_EVENT_SUSPENDED:
154 ret = VIR_DOMAIN_PAUSED;
155 break;
156 case VIR_DOMAIN_EVENT_RESUMED:
157 ret = VIR_DOMAIN_RUNNING;
158 break;
159 case VIR_DOMAIN_EVENT_STOPPED:
160 ret = VIR_DOMAIN_SHUTOFF;
161 break;
162 case VIR_DOMAIN_EVENT_SHUTDOWN:
163 ret = VIR_DOMAIN_SHUTDOWN;
164 break;
165 #ifdef HAVE_DOM_STATE_PMSUSPENDED
166 case VIR_DOMAIN_EVENT_PMSUSPENDED:
167 ret = VIR_DOMAIN_PMSUSPENDED;
168 break;
169 #endif
170 #ifdef HAVE_DOM_REASON_CRASHED
171 case VIR_DOMAIN_EVENT_CRASHED:
172 ret = VIR_DOMAIN_CRASHED;
173 break;
174 #endif
175 default:
176 ret = VIR_DOMAIN_NOSTATE;
177 }
178 return ret;
179 }
180
181 #ifdef HAVE_DOM_REASON
map_domain_event_detail_to_reason(int event,int detail)182 static int map_domain_event_detail_to_reason(int event, int detail) {
183 int ret;
184 switch (event) {
185 case VIR_DOMAIN_EVENT_STARTED:
186 switch (detail) {
187 case VIR_DOMAIN_EVENT_STARTED_BOOTED: /* Normal startup from boot */
188 ret = VIR_DOMAIN_RUNNING_BOOTED;
189 break;
190 case VIR_DOMAIN_EVENT_STARTED_MIGRATED: /* Incoming migration from another
191 host */
192 ret = VIR_DOMAIN_RUNNING_MIGRATED;
193 break;
194 case VIR_DOMAIN_EVENT_STARTED_RESTORED: /* Restored from a state file */
195 ret = VIR_DOMAIN_RUNNING_RESTORED;
196 break;
197 case VIR_DOMAIN_EVENT_STARTED_FROM_SNAPSHOT: /* Restored from snapshot */
198 ret = VIR_DOMAIN_RUNNING_FROM_SNAPSHOT;
199 break;
200 #ifdef HAVE_DOM_REASON_RUNNING_WAKEUP
201 case VIR_DOMAIN_EVENT_STARTED_WAKEUP: /* Started due to wakeup event */
202 ret = VIR_DOMAIN_RUNNING_WAKEUP;
203 break;
204 #endif
205 default:
206 ret = VIR_DOMAIN_RUNNING_UNKNOWN;
207 }
208 break;
209 case VIR_DOMAIN_EVENT_SUSPENDED:
210 switch (detail) {
211 case VIR_DOMAIN_EVENT_SUSPENDED_PAUSED: /* Normal suspend due to admin
212 pause */
213 ret = VIR_DOMAIN_PAUSED_USER;
214 break;
215 case VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED: /* Suspended for offline
216 migration */
217 ret = VIR_DOMAIN_PAUSED_MIGRATION;
218 break;
219 case VIR_DOMAIN_EVENT_SUSPENDED_IOERROR: /* Suspended due to a disk I/O
220 error */
221 ret = VIR_DOMAIN_PAUSED_IOERROR;
222 break;
223 case VIR_DOMAIN_EVENT_SUSPENDED_WATCHDOG: /* Suspended due to a watchdog
224 firing */
225 ret = VIR_DOMAIN_PAUSED_WATCHDOG;
226 break;
227 case VIR_DOMAIN_EVENT_SUSPENDED_RESTORED: /* Restored from paused state
228 file */
229 ret = VIR_DOMAIN_PAUSED_UNKNOWN;
230 break;
231 case VIR_DOMAIN_EVENT_SUSPENDED_FROM_SNAPSHOT: /* Restored from paused
232 snapshot */
233 ret = VIR_DOMAIN_PAUSED_FROM_SNAPSHOT;
234 break;
235 case VIR_DOMAIN_EVENT_SUSPENDED_API_ERROR: /* Suspended after failure during
236 libvirt API call */
237 ret = VIR_DOMAIN_PAUSED_UNKNOWN;
238 break;
239 #ifdef HAVE_DOM_REASON_POSTCOPY
240 case VIR_DOMAIN_EVENT_SUSPENDED_POSTCOPY: /* Suspended for post-copy
241 migration */
242 ret = VIR_DOMAIN_PAUSED_POSTCOPY;
243 break;
244 case VIR_DOMAIN_EVENT_SUSPENDED_POSTCOPY_FAILED: /* Suspended after failed
245 post-copy */
246 ret = VIR_DOMAIN_PAUSED_POSTCOPY_FAILED;
247 break;
248 #endif
249 default:
250 ret = VIR_DOMAIN_PAUSED_UNKNOWN;
251 }
252 break;
253 case VIR_DOMAIN_EVENT_RESUMED:
254 switch (detail) {
255 case VIR_DOMAIN_EVENT_RESUMED_UNPAUSED: /* Normal resume due to admin
256 unpause */
257 ret = VIR_DOMAIN_RUNNING_UNPAUSED;
258 break;
259 case VIR_DOMAIN_EVENT_RESUMED_MIGRATED: /* Resumed for completion of
260 migration */
261 ret = VIR_DOMAIN_RUNNING_MIGRATED;
262 break;
263 case VIR_DOMAIN_EVENT_RESUMED_FROM_SNAPSHOT: /* Resumed from snapshot */
264 ret = VIR_DOMAIN_RUNNING_FROM_SNAPSHOT;
265 break;
266 #ifdef HAVE_DOM_REASON_POSTCOPY
267 case VIR_DOMAIN_EVENT_RESUMED_POSTCOPY: /* Resumed, but migration is still
268 running in post-copy mode */
269 ret = VIR_DOMAIN_RUNNING_POSTCOPY;
270 break;
271 #endif
272 default:
273 ret = VIR_DOMAIN_RUNNING_UNKNOWN;
274 }
275 break;
276 case VIR_DOMAIN_EVENT_STOPPED:
277 switch (detail) {
278 case VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN: /* Normal shutdown */
279 ret = VIR_DOMAIN_SHUTOFF_SHUTDOWN;
280 break;
281 case VIR_DOMAIN_EVENT_STOPPED_DESTROYED: /* Forced poweroff from host */
282 ret = VIR_DOMAIN_SHUTOFF_DESTROYED;
283 break;
284 case VIR_DOMAIN_EVENT_STOPPED_CRASHED: /* Guest crashed */
285 ret = VIR_DOMAIN_SHUTOFF_CRASHED;
286 break;
287 case VIR_DOMAIN_EVENT_STOPPED_MIGRATED: /* Migrated off to another host */
288 ret = VIR_DOMAIN_SHUTOFF_MIGRATED;
289 break;
290 case VIR_DOMAIN_EVENT_STOPPED_SAVED: /* Saved to a state file */
291 ret = VIR_DOMAIN_SHUTOFF_SAVED;
292 break;
293 case VIR_DOMAIN_EVENT_STOPPED_FAILED: /* Host emulator/mgmt failed */
294 ret = VIR_DOMAIN_SHUTOFF_FAILED;
295 break;
296 case VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT: /* Offline snapshot loaded */
297 ret = VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT;
298 break;
299 default:
300 ret = VIR_DOMAIN_SHUTOFF_UNKNOWN;
301 }
302 break;
303 case VIR_DOMAIN_EVENT_SHUTDOWN:
304 switch (detail) {
305 case VIR_DOMAIN_EVENT_SHUTDOWN_FINISHED: /* Guest finished shutdown
306 sequence */
307 #ifdef LIBVIR_CHECK_VERSION
308 #if LIBVIR_CHECK_VERSION(3, 4, 0)
309 case VIR_DOMAIN_EVENT_SHUTDOWN_GUEST: /* Domain finished shutting down after
310 request from the guest itself (e.g.
311 hardware-specific action) */
312 case VIR_DOMAIN_EVENT_SHUTDOWN_HOST: /* Domain finished shutting down after
313 request from the host (e.g. killed
314 by a signal) */
315 #endif
316 #endif
317 ret = VIR_DOMAIN_SHUTDOWN_USER;
318 break;
319 default:
320 ret = VIR_DOMAIN_SHUTDOWN_UNKNOWN;
321 }
322 break;
323 #ifdef HAVE_DOM_STATE_PMSUSPENDED
324 case VIR_DOMAIN_EVENT_PMSUSPENDED:
325 switch (detail) {
326 case VIR_DOMAIN_EVENT_PMSUSPENDED_MEMORY: /* Guest was PM suspended to
327 memory */
328 ret = VIR_DOMAIN_PMSUSPENDED_UNKNOWN;
329 break;
330 case VIR_DOMAIN_EVENT_PMSUSPENDED_DISK: /* Guest was PM suspended to disk */
331 ret = VIR_DOMAIN_PMSUSPENDED_DISK_UNKNOWN;
332 break;
333 default:
334 ret = VIR_DOMAIN_PMSUSPENDED_UNKNOWN;
335 }
336 break;
337 #endif
338 case VIR_DOMAIN_EVENT_CRASHED:
339 switch (detail) {
340 case VIR_DOMAIN_EVENT_CRASHED_PANICKED: /* Guest was panicked */
341 ret = VIR_DOMAIN_CRASHED_PANICKED;
342 break;
343 default:
344 ret = VIR_DOMAIN_CRASHED_UNKNOWN;
345 }
346 break;
347 default:
348 ret = VIR_DOMAIN_NOSTATE_UNKNOWN;
349 }
350 return ret;
351 }
352
353 #define DOMAIN_STATE_REASON_MAX_SIZE 20
354 const char *domain_reasons[][DOMAIN_STATE_REASON_MAX_SIZE] = {
355 [VIR_DOMAIN_NOSTATE][VIR_DOMAIN_NOSTATE_UNKNOWN] = "the reason is unknown",
356
357 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_UNKNOWN] = "the reason is unknown",
358 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_BOOTED] =
359 "normal startup from boot",
360 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_MIGRATED] =
361 "migrated from another host",
362 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_RESTORED] =
363 "restored from a state file",
364 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_FROM_SNAPSHOT] =
365 "restored from snapshot",
366 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_UNPAUSED] =
367 "returned from paused state",
368 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_MIGRATION_CANCELED] =
369 "returned from migration",
370 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_SAVE_CANCELED] =
371 "returned from failed save process",
372 #ifdef HAVE_DOM_REASON_RUNNING_WAKEUP
373 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_WAKEUP] =
374 "returned from pmsuspended due to wakeup event",
375 #endif
376 #ifdef HAVE_DOM_REASON_CRASHED
377 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_CRASHED] = "resumed from crashed",
378 #endif
379 #ifdef HAVE_DOM_REASON_POSTCOPY
380 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_POSTCOPY] =
381 "running in post-copy migration mode",
382 #endif
383 [VIR_DOMAIN_BLOCKED][VIR_DOMAIN_BLOCKED_UNKNOWN] = "the reason is unknown",
384
385 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_UNKNOWN] = "the reason is unknown",
386 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_USER] = "paused on user request",
387 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_MIGRATION] =
388 "paused for offline migration",
389 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_SAVE] = "paused for save",
390 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_DUMP] =
391 "paused for offline core dump",
392 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_IOERROR] =
393 "paused due to a disk I/O error",
394 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_WATCHDOG] =
395 "paused due to a watchdog event",
396 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_FROM_SNAPSHOT] =
397 "paused after restoring from snapshot",
398 #ifdef HAVE_DOM_REASON_PAUSED_SHUTTING_DOWN
399 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_SHUTTING_DOWN] =
400 "paused during shutdown process",
401 #endif
402 #ifdef HAVE_DOM_REASON_PAUSED_SNAPSHOT
403 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_SNAPSHOT] =
404 "paused while creating a snapshot",
405 #endif
406 #ifdef HAVE_DOM_REASON_PAUSED_CRASHED
407 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_CRASHED] =
408 "paused due to a guest crash",
409 #endif
410 #ifdef HAVE_DOM_REASON_PAUSED_STARTING_UP
411 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_STARTING_UP] =
412 "the domain is being started",
413 #endif
414 #ifdef HAVE_DOM_REASON_POSTCOPY
415 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_POSTCOPY] =
416 "paused for post-copy migration",
417 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_POSTCOPY_FAILED] =
418 "paused after failed post-copy",
419 #endif
420 [VIR_DOMAIN_SHUTDOWN][VIR_DOMAIN_SHUTDOWN_UNKNOWN] =
421 "the reason is unknown",
422 [VIR_DOMAIN_SHUTDOWN][VIR_DOMAIN_SHUTDOWN_USER] =
423 "shutting down on user request",
424
425 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_UNKNOWN] = "the reason is unknown",
426 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_SHUTDOWN] = "normal shutdown",
427 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_DESTROYED] = "forced poweroff",
428 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_CRASHED] = "domain crashed",
429 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_MIGRATED] =
430 "migrated to another host",
431 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_SAVED] = "saved to a file",
432 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_FAILED] = "domain failed to start",
433 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT] =
434 "restored from a snapshot which was taken while domain was shutoff",
435 #ifdef HAVE_DOM_REASON_SHUTOFF_DAEMON
436 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_DAEMON] =
437 "daemon decides to kill domain during reconnection processing",
438 #endif
439
440 [VIR_DOMAIN_CRASHED][VIR_DOMAIN_CRASHED_UNKNOWN] = "the reason is unknown",
441 #ifdef VIR_DOMAIN_CRASHED_PANICKED
442 [VIR_DOMAIN_CRASHED][VIR_DOMAIN_CRASHED_PANICKED] = "domain panicked",
443 #endif
444
445 #ifdef HAVE_DOM_STATE_PMSUSPENDED
446 [VIR_DOMAIN_PMSUSPENDED][VIR_DOMAIN_PMSUSPENDED_UNKNOWN] =
447 "the reason is unknown",
448 #endif
449 };
450 #endif /* HAVE_DOM_REASON */
451
452 #define NANOSEC_IN_SEC 1e9
453
454 #define GET_STATS(_f, _name, ...) \
455 do { \
456 status = _f(__VA_ARGS__); \
457 if (status != 0) \
458 ERROR(PLUGIN_NAME " plugin: Failed to get " _name); \
459 } while (0)
460
461 /* Connection. */
462 static virConnectPtr conn;
463 static char *conn_string;
464 static c_complain_t conn_complain = C_COMPLAIN_INIT_STATIC;
465
466 /* Node information required for %CPU */
467 static virNodeInfo nodeinfo;
468
469 /* Seconds between list refreshes, 0 disables completely. */
470 static int interval = 60;
471
472 /* List of domains, if specified. */
473 static ignorelist_t *il_domains;
474 /* List of block devices, if specified. */
475 static ignorelist_t *il_block_devices;
476 /* List of network interface devices, if specified. */
477 static ignorelist_t *il_interface_devices;
478
479 static int ignore_device_match(ignorelist_t *, const char *domname,
480 const char *devpath);
481
482 /* Actual list of block devices found on last refresh. */
483 struct block_device {
484 virDomainPtr dom; /* domain */
485 char *path; /* name of block device */
486 bool has_source; /* information whether source is defined or not */
487 };
488
489 /* Actual list of network interfaces found on last refresh. */
490 struct interface_device {
491 virDomainPtr dom; /* domain */
492 char *path; /* name of interface device */
493 char *address; /* mac address of interface device */
494 char *number; /* interface device number */
495 };
496
497 typedef struct domain_s {
498 virDomainPtr ptr;
499 virDomainInfo info;
500 bool active;
501 } domain_t;
502
503 struct lv_read_state {
504 /* Actual list of domains found on last refresh. */
505 domain_t *domains;
506 int nr_domains;
507
508 struct block_device *block_devices;
509 int nr_block_devices;
510
511 struct interface_device *interface_devices;
512 int nr_interface_devices;
513 };
514
515 static void free_domains(struct lv_read_state *state);
516 static int add_domain(struct lv_read_state *state, virDomainPtr dom,
517 bool active);
518
519 static void free_block_devices(struct lv_read_state *state);
520 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
521 const char *path, bool has_source);
522
523 static void free_interface_devices(struct lv_read_state *state);
524 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
525 const char *path, const char *address,
526 unsigned int number);
527
528 #define METADATA_VM_PARTITION_URI "http://ovirt.org/ovirtmap/tag/1.0"
529 #define METADATA_VM_PARTITION_ELEMENT "tag"
530 #define METADATA_VM_PARTITION_PREFIX "ovirtmap"
531
532 #define BUFFER_MAX_LEN 256
533 #define PARTITION_TAG_MAX_LEN 32
534
535 struct lv_read_instance {
536 struct lv_read_state read_state;
537 char tag[PARTITION_TAG_MAX_LEN];
538 size_t id;
539 };
540
541 struct lv_user_data {
542 struct lv_read_instance inst;
543 user_data_t ud;
544 };
545
546 #define NR_INSTANCES_DEFAULT 1
547 #define NR_INSTANCES_MAX 128
548 static int nr_instances = NR_INSTANCES_DEFAULT;
549 static struct lv_user_data lv_read_user_data[NR_INSTANCES_MAX];
550
551 /* HostnameFormat. */
552 #define HF_MAX_FIELDS 4
553
554 enum hf_field { hf_none = 0, hf_hostname, hf_name, hf_uuid, hf_metadata };
555
556 static enum hf_field hostname_format[HF_MAX_FIELDS] = {hf_name};
557
558 /* PluginInstanceFormat */
559 #define PLGINST_MAX_FIELDS 3
560
561 enum plginst_field {
562 plginst_none = 0,
563 plginst_name,
564 plginst_uuid,
565 plginst_metadata
566 };
567
568 static enum plginst_field plugin_instance_format[PLGINST_MAX_FIELDS] = {
569 plginst_none};
570
571 /* HostnameMetadataNS && HostnameMetadataXPath */
572 static char *hm_xpath;
573 static char *hm_ns;
574
575 /* BlockDeviceFormat */
576 enum bd_field { target, source };
577
578 /* InterfaceFormat. */
579 enum if_field { if_address, if_name, if_number };
580
581 /* ExtraStats */
582 #define EX_STATS_MAX_FIELDS 15
583 enum ex_stats {
584 ex_stats_none = 0,
585 ex_stats_disk = 1 << 0,
586 ex_stats_pcpu = 1 << 1,
587 ex_stats_cpu_util = 1 << 2,
588 ex_stats_domain_state = 1 << 3,
589 #ifdef HAVE_PERF_STATS
590 ex_stats_perf = 1 << 4,
591 #endif
592 ex_stats_vcpupin = 1 << 5,
593 #ifdef HAVE_DISK_ERR
594 ex_stats_disk_err = 1 << 6,
595 #endif
596 #ifdef HAVE_FS_INFO
597 ex_stats_fs_info = 1 << 7,
598 #endif
599 #ifdef HAVE_JOB_STATS
600 ex_stats_job_stats_completed = 1 << 8,
601 ex_stats_job_stats_background = 1 << 9,
602 #endif
603 ex_stats_disk_allocation = 1 << 10,
604 ex_stats_disk_capacity = 1 << 11,
605 ex_stats_disk_physical = 1 << 12,
606 ex_stats_memory = 1 << 13,
607 ex_stats_vcpu = 1 << 14
608 };
609
610 static unsigned int extra_stats = ex_stats_none;
611
612 struct ex_stats_item {
613 const char *name;
614 enum ex_stats flag;
615 };
616 static const struct ex_stats_item ex_stats_table[] = {
617 {"disk", ex_stats_disk},
618 {"pcpu", ex_stats_pcpu},
619 {"cpu_util", ex_stats_cpu_util},
620 {"domain_state", ex_stats_domain_state},
621 #ifdef HAVE_PERF_STATS
622 {"perf", ex_stats_perf},
623 #endif
624 {"vcpupin", ex_stats_vcpupin},
625 #ifdef HAVE_DISK_ERR
626 {"disk_err", ex_stats_disk_err},
627 #endif
628 #ifdef HAVE_FS_INFO
629 {"fs_info", ex_stats_fs_info},
630 #endif
631 #ifdef HAVE_JOB_STATS
632 {"job_stats_completed", ex_stats_job_stats_completed},
633 {"job_stats_background", ex_stats_job_stats_background},
634 #endif
635 {"disk_allocation", ex_stats_disk_allocation},
636 {"disk_capacity", ex_stats_disk_capacity},
637 {"disk_physical", ex_stats_disk_physical},
638 {"memory", ex_stats_memory},
639 {"vcpu", ex_stats_vcpu},
640 {NULL, ex_stats_none},
641 };
642
643 /* BlockDeviceFormatBasename */
644 static bool blockdevice_format_basename;
645 static enum bd_field blockdevice_format = target;
646 static enum if_field interface_format = if_name;
647
648 /* Time that we last refreshed. */
649 static time_t last_refresh = (time_t)0;
650
651 static int refresh_lists(struct lv_read_instance *inst);
652 static int register_event_impl(void);
653 static int start_event_loop(virt_notif_thread_t *thread_data);
654
655 struct lv_block_stats {
656 virDomainBlockStatsStruct bi;
657
658 long long rd_total_times;
659 long long wr_total_times;
660
661 long long fl_req;
662 long long fl_total_times;
663 };
664
init_block_stats(struct lv_block_stats * bstats)665 static void init_block_stats(struct lv_block_stats *bstats) {
666 if (bstats == NULL)
667 return;
668
669 bstats->bi.rd_req = -1;
670 bstats->bi.wr_req = -1;
671 bstats->bi.rd_bytes = -1;
672 bstats->bi.wr_bytes = -1;
673
674 bstats->rd_total_times = -1;
675 bstats->wr_total_times = -1;
676 bstats->fl_req = -1;
677 bstats->fl_total_times = -1;
678 }
679
init_block_info(virDomainBlockInfoPtr binfo)680 static void init_block_info(virDomainBlockInfoPtr binfo) {
681 binfo->allocation = -1;
682 binfo->capacity = -1;
683 binfo->physical = -1;
684 }
685
686 #ifdef HAVE_BLOCK_STATS_FLAGS
687
688 #define GET_BLOCK_STATS_VALUE(NAME, FIELD) \
689 if (!strcmp(param[i].field, NAME)) { \
690 bstats->FIELD = param[i].value.l; \
691 continue; \
692 }
693
get_block_stats(struct lv_block_stats * bstats,virTypedParameterPtr param,int nparams)694 static int get_block_stats(struct lv_block_stats *bstats,
695 virTypedParameterPtr param, int nparams) {
696 if (bstats == NULL || param == NULL)
697 return -1;
698
699 for (int i = 0; i < nparams; ++i) {
700 /* ignore type. Everything must be LLONG anyway. */
701 GET_BLOCK_STATS_VALUE("rd_operations", bi.rd_req);
702 GET_BLOCK_STATS_VALUE("wr_operations", bi.wr_req);
703 GET_BLOCK_STATS_VALUE("rd_bytes", bi.rd_bytes);
704 GET_BLOCK_STATS_VALUE("wr_bytes", bi.wr_bytes);
705 GET_BLOCK_STATS_VALUE("rd_total_times", rd_total_times);
706 GET_BLOCK_STATS_VALUE("wr_total_times", wr_total_times);
707 GET_BLOCK_STATS_VALUE("flush_operations", fl_req);
708 GET_BLOCK_STATS_VALUE("flush_total_times", fl_total_times);
709 }
710
711 return 0;
712 }
713
714 #undef GET_BLOCK_STATS_VALUE
715
716 #endif /* HAVE_BLOCK_STATS_FLAGS */
717
718 /* ERROR(...) macro for virterrors. */
719 #define VIRT_ERROR(conn, s) \
720 do { \
721 virErrorPtr err; \
722 err = (conn) ? virConnGetLastError((conn)) : virGetLastError(); \
723 if (err) \
724 ERROR(PLUGIN_NAME " plugin: %s failed: %s", (s), err->message); \
725 } while (0)
726
727 enum metadata_set_type_e { META_APPEND_HOST, META_APPEND_PLUGIN_INSTANCE };
728
set_field_from_metadata(value_list_t * vl,virDomainPtr dom,enum metadata_set_type_e field)729 static void set_field_from_metadata(value_list_t *vl, virDomainPtr dom,
730 enum metadata_set_type_e field) {
731 const char *xpath_str = NULL;
732 if (hm_xpath == NULL)
733 xpath_str = "/instance/name/text()";
734 else
735 xpath_str = hm_xpath;
736
737 const char *namespace = NULL;
738 if (hm_ns == NULL) {
739 namespace = "http://openstack.org/xmlns/libvirt/nova/1.0";
740 } // namespace =hm_ns;
741 else {
742 namespace = hm_ns;
743 }
744
745 char *metadata_str = virDomainGetMetadata(
746 dom, VIR_DOMAIN_METADATA_ELEMENT, namespace, VIR_DOMAIN_AFFECT_CURRENT);
747 if (metadata_str == NULL) {
748 return;
749 }
750
751 const char *value = NULL;
752 xmlXPathContextPtr xpath_ctx = NULL;
753 xmlXPathObjectPtr xpath_obj = NULL;
754 xmlNodePtr xml_node = NULL;
755
756 xmlDocPtr xml_doc =
757 xmlReadDoc((xmlChar *)metadata_str, NULL, NULL, XML_PARSE_NONET);
758 if (xml_doc == NULL) {
759 ERROR(PLUGIN_NAME " plugin: xmlReadDoc failed to read metadata");
760 goto metadata_end;
761 }
762
763 xpath_ctx = xmlXPathNewContext(xml_doc);
764 if (xpath_ctx == NULL) {
765 ERROR(PLUGIN_NAME " plugin: xmlXPathNewContext(%s) failed for metadata",
766 metadata_str);
767 goto metadata_end;
768 }
769 xpath_obj = xmlXPathEval((xmlChar *)xpath_str, xpath_ctx);
770 if (xpath_obj == NULL) {
771 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) failed for metadata",
772 xpath_str);
773 goto metadata_end;
774 }
775
776 if (xpath_obj->type != XPATH_NODESET) {
777 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) unexpected return type %d "
778 "(wanted %d) for metadata",
779 xpath_str, xpath_obj->type, XPATH_NODESET);
780 goto metadata_end;
781 }
782
783 // TODO(sileht): We can support || operator by looping on nodes here
784 if (xpath_obj->nodesetval == NULL || xpath_obj->nodesetval->nodeNr != 1) {
785 WARNING(PLUGIN_NAME " plugin: xmlXPathEval(%s) return nodeset size=%i "
786 "expected=1 for metadata",
787 xpath_str,
788 (xpath_obj->nodesetval == NULL) ? 0
789 : xpath_obj->nodesetval->nodeNr);
790 goto metadata_end;
791 }
792
793 xml_node = xpath_obj->nodesetval->nodeTab[0];
794 if (xml_node->type == XML_TEXT_NODE) {
795 value = (const char *)xml_node->content;
796 } else if (xml_node->type == XML_ATTRIBUTE_NODE) {
797 value = (const char *)xml_node->children->content;
798 } else {
799 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) unsupported node type %d",
800 xpath_str, xml_node->type);
801 goto metadata_end;
802 }
803
804 if (value == NULL)
805 goto metadata_end;
806
807 switch (field) {
808 case META_APPEND_HOST:
809 SSTRNCAT(vl->host, value, sizeof(vl->host));
810 break;
811 case META_APPEND_PLUGIN_INSTANCE:
812 SSTRNCAT(vl->plugin_instance, value, sizeof(vl->plugin_instance));
813 break;
814 }
815
816 metadata_end:
817 if (xpath_obj)
818 xmlXPathFreeObject(xpath_obj);
819 if (xpath_ctx)
820 xmlXPathFreeContext(xpath_ctx);
821 if (xml_doc)
822 xmlFreeDoc(xml_doc);
823 sfree(metadata_str);
824 }
825
init_value_list(value_list_t * vl,virDomainPtr dom)826 static void init_value_list(value_list_t *vl, virDomainPtr dom) {
827 const char *name;
828 char uuid[VIR_UUID_STRING_BUFLEN];
829
830 sstrncpy(vl->plugin, PLUGIN_NAME, sizeof(vl->plugin));
831
832 vl->host[0] = '\0';
833
834 /* Construct the hostname field according to HostnameFormat. */
835 for (int i = 0; i < HF_MAX_FIELDS; ++i) {
836 if (hostname_format[i] == hf_none)
837 continue;
838
839 if (i > 0)
840 SSTRNCAT(vl->host, ":", sizeof(vl->host));
841
842 switch (hostname_format[i]) {
843 case hf_none:
844 break;
845 case hf_hostname:
846 SSTRNCAT(vl->host, hostname_g, sizeof(vl->host));
847 break;
848 case hf_name:
849 name = virDomainGetName(dom);
850 if (name)
851 SSTRNCAT(vl->host, name, sizeof(vl->host));
852 break;
853 case hf_uuid:
854 if (virDomainGetUUIDString(dom, uuid) == 0)
855 SSTRNCAT(vl->host, uuid, sizeof(vl->host));
856 break;
857 case hf_metadata:
858 set_field_from_metadata(vl, dom, META_APPEND_HOST);
859 break;
860 }
861 }
862
863 /* Construct the plugin instance field according to PluginInstanceFormat. */
864 for (int i = 0; i < PLGINST_MAX_FIELDS; ++i) {
865 if (plugin_instance_format[i] == plginst_none)
866 continue;
867
868 if (i > 0)
869 SSTRNCAT(vl->plugin_instance, ":", sizeof(vl->plugin_instance));
870
871 switch (plugin_instance_format[i]) {
872 case plginst_none:
873 break;
874 case plginst_name:
875 name = virDomainGetName(dom);
876 if (name)
877 SSTRNCAT(vl->plugin_instance, name, sizeof(vl->plugin_instance));
878 break;
879 case plginst_uuid:
880 if (virDomainGetUUIDString(dom, uuid) == 0)
881 SSTRNCAT(vl->plugin_instance, uuid, sizeof(vl->plugin_instance));
882 break;
883 case plginst_metadata:
884 set_field_from_metadata(vl, dom, META_APPEND_PLUGIN_INSTANCE);
885 break;
886 }
887 }
888 } /* void init_value_list */
889
init_notif(notification_t * notif,const virDomainPtr domain,int severity,const char * msg,const char * type,const char * type_instance)890 static int init_notif(notification_t *notif, const virDomainPtr domain,
891 int severity, const char *msg, const char *type,
892 const char *type_instance) {
893 value_list_t vl = VALUE_LIST_INIT;
894
895 if (!notif) {
896 ERROR(PLUGIN_NAME " plugin: init_notif: NULL pointer");
897 return -1;
898 }
899
900 init_value_list(&vl, domain);
901 notification_init(notif, severity, msg, vl.host, vl.plugin,
902 vl.plugin_instance, type, type_instance);
903 notif->time = cdtime();
904 return 0;
905 }
906
submit_notif(const virDomainPtr domain,int severity,const char * msg,const char * type,const char * type_instance)907 static void submit_notif(const virDomainPtr domain, int severity,
908 const char *msg, const char *type,
909 const char *type_instance) {
910 notification_t notif;
911
912 init_notif(¬if, domain, severity, msg, type, type_instance);
913 plugin_dispatch_notification(¬if);
914 if (notif.meta)
915 plugin_notification_meta_free(notif.meta);
916 }
917
submit(virDomainPtr dom,char const * type,char const * type_instance,value_t * values,size_t values_len)918 static void submit(virDomainPtr dom, char const *type,
919 char const *type_instance, value_t *values,
920 size_t values_len) {
921 value_list_t vl = VALUE_LIST_INIT;
922 init_value_list(&vl, dom);
923
924 vl.values = values;
925 vl.values_len = values_len;
926
927 sstrncpy(vl.type, type, sizeof(vl.type));
928 if (type_instance != NULL)
929 sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
930
931 plugin_dispatch_values(&vl);
932 }
933
memory_submit(virDomainPtr dom,gauge_t value)934 static void memory_submit(virDomainPtr dom, gauge_t value) {
935 submit(dom, "memory", "total", &(value_t){.gauge = value}, 1);
936 }
937
memory_stats_submit(gauge_t value,virDomainPtr dom,int tag_index)938 static void memory_stats_submit(gauge_t value, virDomainPtr dom,
939 int tag_index) {
940 static const char *tags[] = {"swap_in", "swap_out", "major_fault",
941 "minor_fault", "unused", "available",
942 "actual_balloon", "rss", "usable",
943 "last_update", "disk_caches"};
944
945 if ((tag_index < 0) || (tag_index >= (int)STATIC_ARRAY_SIZE(tags))) {
946 ERROR(PLUGIN_NAME " plugin: Array index out of bounds: tag_index = %d",
947 tag_index);
948 return;
949 }
950
951 submit(dom, "memory", tags[tag_index], &(value_t){.gauge = value}, 1);
952 }
953
submit_derive2(const char * type,derive_t v0,derive_t v1,virDomainPtr dom,const char * devname)954 static void submit_derive2(const char *type, derive_t v0, derive_t v1,
955 virDomainPtr dom, const char *devname) {
956 value_t values[] = {
957 {.derive = v0},
958 {.derive = v1},
959 };
960
961 submit(dom, type, devname, values, STATIC_ARRAY_SIZE(values));
962 } /* void submit_derive2 */
963
cpu_ns_to_percent(unsigned int node_cpus,unsigned long long cpu_time_old,unsigned long long cpu_time_new)964 static double cpu_ns_to_percent(unsigned int node_cpus,
965 unsigned long long cpu_time_old,
966 unsigned long long cpu_time_new) {
967 double percent = 0.0;
968 unsigned long long cpu_time_diff = 0;
969 double time_diff_sec = CDTIME_T_TO_DOUBLE(plugin_get_interval());
970
971 if (node_cpus != 0 && time_diff_sec != 0 && cpu_time_old != 0) {
972 cpu_time_diff = cpu_time_new - cpu_time_old;
973 percent = ((double)(100 * cpu_time_diff)) /
974 (time_diff_sec * node_cpus * NANOSEC_IN_SEC);
975 }
976
977 DEBUG(PLUGIN_NAME " plugin: node_cpus=%u cpu_time_old=%" PRIu64
978 " cpu_time_new=%" PRIu64 " cpu_time_diff=%" PRIu64
979 " time_diff_sec=%f percent=%f",
980 node_cpus, (uint64_t)cpu_time_old, (uint64_t)cpu_time_new,
981 (uint64_t)cpu_time_diff, time_diff_sec, percent);
982
983 return percent;
984 }
985
cpu_submit(const domain_t * dom,unsigned long long cpuTime_new)986 static void cpu_submit(const domain_t *dom, unsigned long long cpuTime_new) {
987
988 if (!dom)
989 return;
990
991 if (extra_stats & ex_stats_cpu_util) {
992 /* Computing %CPU requires 2 samples of cpuTime */
993 if (dom->info.cpuTime != 0 && cpuTime_new != 0) {
994
995 submit(dom->ptr, "percent", "virt_cpu_total",
996 &(value_t){.gauge = cpu_ns_to_percent(
997 nodeinfo.cpus, dom->info.cpuTime, cpuTime_new)},
998 1);
999 }
1000 }
1001
1002 submit(dom->ptr, "virt_cpu_total", NULL, &(value_t){.derive = cpuTime_new},
1003 1);
1004 }
1005
vcpu_submit(derive_t value,virDomainPtr dom,int vcpu_nr,const char * type)1006 static void vcpu_submit(derive_t value, virDomainPtr dom, int vcpu_nr,
1007 const char *type) {
1008 char type_instance[DATA_MAX_NAME_LEN];
1009
1010 ssnprintf(type_instance, sizeof(type_instance), "%d", vcpu_nr);
1011 submit(dom, type, type_instance, &(value_t){.derive = value}, 1);
1012 }
1013
disk_block_stats_submit(struct lv_block_stats * bstats,virDomainPtr dom,const char * dev,virDomainBlockInfoPtr binfo)1014 static void disk_block_stats_submit(struct lv_block_stats *bstats,
1015 virDomainPtr dom, const char *dev,
1016 virDomainBlockInfoPtr binfo) {
1017 char *dev_copy = strdup(dev);
1018 const char *type_instance = dev_copy;
1019
1020 if (!dev_copy)
1021 return;
1022
1023 if (blockdevice_format_basename && blockdevice_format == source)
1024 type_instance = basename(dev_copy);
1025
1026 if (!type_instance) {
1027 sfree(dev_copy);
1028 return;
1029 }
1030
1031 char flush_type_instance[DATA_MAX_NAME_LEN];
1032 ssnprintf(flush_type_instance, sizeof(flush_type_instance), "flush-%s",
1033 type_instance);
1034
1035 if ((bstats->bi.rd_req != -1) && (bstats->bi.wr_req != -1))
1036 submit_derive2("disk_ops", (derive_t)bstats->bi.rd_req,
1037 (derive_t)bstats->bi.wr_req, dom, type_instance);
1038
1039 if ((bstats->bi.rd_bytes != -1) && (bstats->bi.wr_bytes != -1))
1040 submit_derive2("disk_octets", (derive_t)bstats->bi.rd_bytes,
1041 (derive_t)bstats->bi.wr_bytes, dom, type_instance);
1042
1043 if (extra_stats & ex_stats_disk) {
1044 if ((bstats->rd_total_times != -1) && (bstats->wr_total_times != -1))
1045 submit_derive2("disk_time", (derive_t)bstats->rd_total_times,
1046 (derive_t)bstats->wr_total_times, dom, type_instance);
1047
1048 if (bstats->fl_req != -1)
1049 submit(dom, "total_requests", flush_type_instance,
1050 &(value_t){.derive = (derive_t)bstats->fl_req}, 1);
1051 if (bstats->fl_total_times != -1) {
1052 derive_t value = bstats->fl_total_times / 1000; // ns -> ms
1053 submit(dom, "total_time_in_ms", flush_type_instance,
1054 &(value_t){.derive = value}, 1);
1055 }
1056 }
1057
1058 /* disk_allocation, disk_capacity and disk_physical are stored only
1059 * if corresponding extrastats are set in collectd configuration file */
1060 if ((extra_stats & ex_stats_disk_allocation) && binfo->allocation != -1)
1061 submit(dom, "disk_allocation", type_instance,
1062 &(value_t){.gauge = (gauge_t)binfo->allocation}, 1);
1063
1064 if ((extra_stats & ex_stats_disk_capacity) && binfo->capacity != -1)
1065 submit(dom, "disk_capacity", type_instance,
1066 &(value_t){.gauge = (gauge_t)binfo->capacity}, 1);
1067
1068 if ((extra_stats & ex_stats_disk_physical) && binfo->physical != -1)
1069 submit(dom, "disk_physical", type_instance,
1070 &(value_t){.gauge = (gauge_t)binfo->physical}, 1);
1071
1072 sfree(dev_copy);
1073 }
1074
1075 /**
1076 * Function for parsing ExtraStats configuration options.
1077 * Result of parsing is stored under 'out_parsed_flags' pointer.
1078 *
1079 * Returns 0 in case of success and 1 in case of parsing error
1080 */
parse_ex_stats_flags(unsigned int * out_parsed_flags,char ** exstats,int numexstats)1081 static int parse_ex_stats_flags(unsigned int *out_parsed_flags, char **exstats,
1082 int numexstats) {
1083 unsigned int ex_stats_flags = ex_stats_none;
1084
1085 assert(out_parsed_flags != NULL);
1086
1087 for (int i = 0; i < numexstats; i++) {
1088 for (int j = 0; ex_stats_table[j].name != NULL; j++) {
1089 if (strcasecmp(exstats[i], ex_stats_table[j].name) == 0) {
1090 DEBUG(PLUGIN_NAME " plugin: enabling extra stats for '%s'",
1091 ex_stats_table[j].name);
1092 ex_stats_flags |= ex_stats_table[j].flag;
1093 break;
1094 }
1095
1096 if (ex_stats_table[j + 1].name == NULL) {
1097 ERROR(PLUGIN_NAME " plugin: Unmatched ExtraStats option: %s",
1098 exstats[i]);
1099 return 1;
1100 }
1101 }
1102 }
1103
1104 *out_parsed_flags = ex_stats_flags;
1105 return 0;
1106 }
1107
domain_state_submit_notif(virDomainPtr dom,int state,int reason)1108 static void domain_state_submit_notif(virDomainPtr dom, int state, int reason) {
1109 if ((state < 0) || ((size_t)state >= STATIC_ARRAY_SIZE(domain_states))) {
1110 ERROR(PLUGIN_NAME " plugin: Array index out of bounds: state=%d", state);
1111 return;
1112 }
1113
1114 char msg[DATA_MAX_NAME_LEN];
1115 const char *state_str = domain_states[state];
1116 #ifdef HAVE_DOM_REASON
1117 if ((reason < 0) ||
1118 ((size_t)reason >= STATIC_ARRAY_SIZE(domain_reasons[0]))) {
1119 ERROR(PLUGIN_NAME " plugin: Array index out of bounds: reason=%d", reason);
1120 return;
1121 }
1122
1123 const char *reason_str = domain_reasons[state][reason];
1124 /* Array size for domain reasons is fixed, but different domain states can
1125 * have different number of reasons. We need to check if reason was
1126 * successfully parsed */
1127 if (!reason_str) {
1128 ERROR(PLUGIN_NAME " plugin: Invalid reason (%d) for domain state: %s",
1129 reason, state_str);
1130 return;
1131 }
1132 #else
1133 const char *reason_str = "N/A";
1134 #endif
1135
1136 ssnprintf(msg, sizeof(msg), "Domain state: %s. Reason: %s", state_str,
1137 reason_str);
1138
1139 int severity;
1140 switch (state) {
1141 case VIR_DOMAIN_NOSTATE:
1142 case VIR_DOMAIN_RUNNING:
1143 case VIR_DOMAIN_SHUTDOWN:
1144 case VIR_DOMAIN_SHUTOFF:
1145 severity = NOTIF_OKAY;
1146 break;
1147 case VIR_DOMAIN_BLOCKED:
1148 case VIR_DOMAIN_PAUSED:
1149 #ifdef DOM_STATE_PMSUSPENDED
1150 case VIR_DOMAIN_PMSUSPENDED:
1151 #endif
1152 severity = NOTIF_WARNING;
1153 break;
1154 case VIR_DOMAIN_CRASHED:
1155 severity = NOTIF_FAILURE;
1156 break;
1157 default:
1158 ERROR(PLUGIN_NAME " plugin: Unrecognized domain state (%d)", state);
1159 return;
1160 }
1161 submit_notif(dom, severity, msg, "domain_state", NULL);
1162 }
1163
lv_init_ignorelists()1164 static int lv_init_ignorelists() {
1165 if (il_domains == NULL)
1166 il_domains = ignorelist_create(1);
1167 if (il_block_devices == NULL)
1168 il_block_devices = ignorelist_create(1);
1169 if (il_interface_devices == NULL)
1170 il_interface_devices = ignorelist_create(1);
1171
1172 if (!il_domains || !il_block_devices || !il_interface_devices)
1173 return 1;
1174
1175 return 0;
1176 }
1177
1178 /* Validates config option that may take multiple strings arguments.
1179 * Returns 0 on success, -1 otherwise */
check_config_multiple_string_entry(const oconfig_item_t * ci)1180 static int check_config_multiple_string_entry(const oconfig_item_t *ci) {
1181 if (ci == NULL) {
1182 ERROR(PLUGIN_NAME " plugin: ci oconfig_item can't be NULL");
1183 return -1;
1184 }
1185
1186 if (ci->values_num < 1) {
1187 ERROR(PLUGIN_NAME
1188 " plugin: the '%s' option requires at least one string argument",
1189 ci->key);
1190 return -1;
1191 }
1192
1193 for (int i = 0; i < ci->values_num; ++i) {
1194 if (ci->values[i].type != OCONFIG_TYPE_STRING) {
1195 ERROR(PLUGIN_NAME
1196 " plugin: one of the '%s' options is not a valid string",
1197 ci->key);
1198 return -1;
1199 }
1200 }
1201
1202 return 0;
1203 }
1204
lv_config(oconfig_item_t * ci)1205 static int lv_config(oconfig_item_t *ci) {
1206 if (lv_init_ignorelists() != 0) {
1207 ERROR(PLUGIN_NAME " plugin: lv_init_ignorelist failed.");
1208 return -1;
1209 }
1210
1211 for (int i = 0; i < ci->children_num; ++i) {
1212 oconfig_item_t *c = ci->children + i;
1213
1214 if (strcasecmp(c->key, "Connection") == 0) {
1215 if (cf_util_get_string(c, &conn_string) != 0 || conn_string == NULL)
1216 return -1;
1217
1218 continue;
1219 } else if (strcasecmp(c->key, "RefreshInterval") == 0) {
1220 if (cf_util_get_int(c, &interval) != 0)
1221 return -1;
1222
1223 continue;
1224 } else if (strcasecmp(c->key, "Domain") == 0) {
1225 char *domain_name = NULL;
1226 if (cf_util_get_string(c, &domain_name) != 0)
1227 return -1;
1228
1229 if (ignorelist_add(il_domains, domain_name)) {
1230 ERROR(PLUGIN_NAME " plugin: Adding '%s' to domain-ignorelist failed",
1231 domain_name);
1232 sfree(domain_name);
1233 return -1;
1234 }
1235
1236 sfree(domain_name);
1237 continue;
1238 } else if (strcasecmp(c->key, "BlockDevice") == 0) {
1239 char *device_name = NULL;
1240 if (cf_util_get_string(c, &device_name) != 0)
1241 return -1;
1242
1243 if (ignorelist_add(il_block_devices, device_name) != 0) {
1244 ERROR(PLUGIN_NAME
1245 " plugin: Adding '%s' to block-device-ignorelist failed",
1246 device_name);
1247 sfree(device_name);
1248 return -1;
1249 }
1250
1251 sfree(device_name);
1252 continue;
1253 } else if (strcasecmp(c->key, "BlockDeviceFormat") == 0) {
1254 char *device_format = NULL;
1255 if (cf_util_get_string(c, &device_format) != 0)
1256 return -1;
1257
1258 if (strcasecmp(device_format, "target") == 0)
1259 blockdevice_format = target;
1260 else if (strcasecmp(device_format, "source") == 0)
1261 blockdevice_format = source;
1262 else {
1263 ERROR(PLUGIN_NAME " plugin: unknown BlockDeviceFormat: %s",
1264 device_format);
1265 sfree(device_format);
1266 return -1;
1267 }
1268
1269 sfree(device_format);
1270 continue;
1271 } else if (strcasecmp(c->key, "BlockDeviceFormatBasename") == 0) {
1272 if (cf_util_get_boolean(c, &blockdevice_format_basename) != 0)
1273 return -1;
1274
1275 continue;
1276 } else if (strcasecmp(c->key, "InterfaceDevice") == 0) {
1277 char *interface_name = NULL;
1278 if (cf_util_get_string(c, &interface_name) != 0)
1279 return -1;
1280
1281 if (ignorelist_add(il_interface_devices, interface_name)) {
1282 ERROR(PLUGIN_NAME " plugin: Adding '%s' to interface-ignorelist failed",
1283 interface_name);
1284 sfree(interface_name);
1285 return -1;
1286 }
1287
1288 sfree(interface_name);
1289 continue;
1290 } else if (strcasecmp(c->key, "IgnoreSelected") == 0) {
1291 bool ignore_selected = false;
1292 if (cf_util_get_boolean(c, &ignore_selected) != 0)
1293 return -1;
1294
1295 if (ignore_selected) {
1296 ignorelist_set_invert(il_domains, 0);
1297 ignorelist_set_invert(il_block_devices, 0);
1298 ignorelist_set_invert(il_interface_devices, 0);
1299 } else {
1300 ignorelist_set_invert(il_domains, 1);
1301 ignorelist_set_invert(il_block_devices, 1);
1302 ignorelist_set_invert(il_interface_devices, 1);
1303 }
1304
1305 continue;
1306 } else if (strcasecmp(c->key, "HostnameMetadataNS") == 0) {
1307 if (cf_util_get_string(c, &hm_ns) != 0)
1308 return -1;
1309
1310 continue;
1311 } else if (strcasecmp(c->key, "HostnameMetadataXPath") == 0) {
1312 if (cf_util_get_string(c, &hm_xpath) != 0)
1313 return -1;
1314
1315 continue;
1316 } else if (strcasecmp(c->key, "HostnameFormat") == 0) {
1317 /* this option can take multiple strings arguments in one config line*/
1318 if (check_config_multiple_string_entry(c) != 0) {
1319 ERROR(PLUGIN_NAME " plugin: Could not get 'HostnameFormat' parameter");
1320 return -1;
1321 }
1322
1323 const int params_num = c->values_num;
1324 for (int i = 0; i < params_num; ++i) {
1325 const char *param_name = c->values[i].value.string;
1326 if (strcasecmp(param_name, "hostname") == 0)
1327 hostname_format[i] = hf_hostname;
1328 else if (strcasecmp(param_name, "name") == 0)
1329 hostname_format[i] = hf_name;
1330 else if (strcasecmp(param_name, "uuid") == 0)
1331 hostname_format[i] = hf_uuid;
1332 else if (strcasecmp(param_name, "metadata") == 0)
1333 hostname_format[i] = hf_metadata;
1334 else {
1335 ERROR(PLUGIN_NAME " plugin: unknown HostnameFormat field: %s",
1336 param_name);
1337 return -1;
1338 }
1339 }
1340
1341 for (int i = params_num; i < HF_MAX_FIELDS; ++i)
1342 hostname_format[i] = hf_none;
1343
1344 continue;
1345 } else if (strcasecmp(c->key, "PluginInstanceFormat") == 0) {
1346 /* this option can handle list of string parameters in one line*/
1347 if (check_config_multiple_string_entry(c) != 0) {
1348 ERROR(PLUGIN_NAME
1349 " plugin: Could not get 'PluginInstanceFormat' parameter");
1350 return -1;
1351 }
1352
1353 const int params_num = c->values_num;
1354 for (int i = 0; i < params_num; ++i) {
1355 const char *param_name = c->values[i].value.string;
1356 if (strcasecmp(param_name, "none") == 0) {
1357 plugin_instance_format[i] = plginst_none;
1358 break;
1359 } else if (strcasecmp(param_name, "name") == 0)
1360 plugin_instance_format[i] = plginst_name;
1361 else if (strcasecmp(param_name, "uuid") == 0)
1362 plugin_instance_format[i] = plginst_uuid;
1363 else if (strcasecmp(param_name, "metadata") == 0)
1364 plugin_instance_format[i] = plginst_metadata;
1365 else {
1366 ERROR(PLUGIN_NAME " plugin: unknown PluginInstanceFormat field: %s",
1367 param_name);
1368
1369 return -1;
1370 }
1371 }
1372
1373 for (int i = params_num; i < PLGINST_MAX_FIELDS; ++i)
1374 plugin_instance_format[i] = plginst_none;
1375
1376 continue;
1377 } else if (strcasecmp(c->key, "InterfaceFormat") == 0) {
1378 char *format = NULL;
1379 if (cf_util_get_string(c, &format) != 0)
1380 return -1;
1381
1382 if (strcasecmp(format, "name") == 0)
1383 interface_format = if_name;
1384 else if (strcasecmp(format, "address") == 0)
1385 interface_format = if_address;
1386 else if (strcasecmp(format, "number") == 0)
1387 interface_format = if_number;
1388 else {
1389 ERROR(PLUGIN_NAME " plugin: unknown InterfaceFormat: %s", format);
1390 sfree(format);
1391 return -1;
1392 }
1393
1394 sfree(format);
1395 continue;
1396 } else if (strcasecmp(c->key, "Instances") == 0) {
1397 if (cf_util_get_int(c, &nr_instances) != 0)
1398 return -1;
1399
1400 if (nr_instances <= 0) {
1401 ERROR(PLUGIN_NAME " plugin: Instances <= 0 makes no sense.");
1402 return -1;
1403 }
1404 if (nr_instances > NR_INSTANCES_MAX) {
1405 ERROR(PLUGIN_NAME " plugin: Instances=%i > NR_INSTANCES_MAX=%i"
1406 " use a lower setting or recompile the plugin.",
1407 nr_instances, NR_INSTANCES_MAX);
1408 return -1;
1409 }
1410
1411 DEBUG(PLUGIN_NAME " plugin: configured %i instances", nr_instances);
1412 continue;
1413 } else if (strcasecmp(c->key, "ExtraStats") == 0) {
1414 char *ex_str = NULL;
1415
1416 if (cf_util_get_string(c, &ex_str) != 0)
1417 return -1;
1418
1419 char *exstats[EX_STATS_MAX_FIELDS];
1420 int numexstats = strsplit(ex_str, exstats, STATIC_ARRAY_SIZE(exstats));
1421 int status = parse_ex_stats_flags(&extra_stats, exstats, numexstats);
1422 sfree(ex_str);
1423 if (status != 0) {
1424 ERROR(PLUGIN_NAME " plugin: parsing 'ExtraStats' option failed");
1425 return status;
1426 }
1427
1428 #ifdef HAVE_JOB_STATS
1429 if ((extra_stats & ex_stats_job_stats_completed) &&
1430 (extra_stats & ex_stats_job_stats_background)) {
1431 ERROR(PLUGIN_NAME " plugin: Invalid job stats configuration. Only one "
1432 "type of job statistics can be collected at the same "
1433 "time");
1434 return -1;
1435 }
1436 #endif
1437
1438 /* ExtraStats parsed successfully */
1439 continue;
1440 } else if (strcasecmp(c->key, "PersistentNotification") == 0) {
1441 if (cf_util_get_boolean(c, &persistent_notification) != 0)
1442 return -1;
1443
1444 continue;
1445 } else if (strcasecmp(c->key, "ReportBlockDevices") == 0) {
1446 if (cf_util_get_boolean(c, &report_block_devices) != 0)
1447 return -1;
1448
1449 continue;
1450 } else if (strcasecmp(c->key, "ReportNetworkInterfaces") == 0) {
1451 if (cf_util_get_boolean(c, &report_network_interfaces) != 0)
1452 return -1;
1453
1454 continue;
1455 } else {
1456 /* Unrecognised option. */
1457 ERROR(PLUGIN_NAME " plugin: Unrecognized option: '%s'", c->key);
1458 return -1;
1459 }
1460 }
1461
1462 return 0;
1463 }
1464
lv_connect(void)1465 static int lv_connect(void) {
1466 if (conn == NULL) {
1467 /* event implementation must be registered before connection is opened */
1468 if (!persistent_notification)
1469 if (register_event_impl() != 0)
1470 return -1;
1471
1472 /* `conn_string == NULL' is acceptable */
1473 #ifdef HAVE_FS_INFO
1474 /* virDomainGetFSInfo requires full read-write access connection */
1475 if (extra_stats & ex_stats_fs_info)
1476 conn = virConnectOpen(conn_string);
1477 else
1478 #endif
1479 conn = virConnectOpenReadOnly(conn_string);
1480 if (conn == NULL) {
1481 c_complain(LOG_ERR, &conn_complain,
1482 PLUGIN_NAME " plugin: Unable to connect: "
1483 "virConnectOpen failed.");
1484 return -1;
1485 }
1486 int status = virNodeGetInfo(conn, &nodeinfo);
1487 if (status != 0) {
1488 ERROR(PLUGIN_NAME " plugin: virNodeGetInfo failed");
1489 virConnectClose(conn);
1490 conn = NULL;
1491 return -1;
1492 }
1493
1494 if (!persistent_notification)
1495 if (start_event_loop(¬if_thread) != 0) {
1496 virConnectClose(conn);
1497 conn = NULL;
1498 return -1;
1499 }
1500 }
1501 c_release(LOG_NOTICE, &conn_complain,
1502 PLUGIN_NAME " plugin: Connection established.");
1503 return 0;
1504 }
1505
lv_disconnect(void)1506 static void lv_disconnect(void) {
1507 if (conn != NULL)
1508 virConnectClose(conn);
1509 conn = NULL;
1510 WARNING(PLUGIN_NAME " plugin: closed connection to libvirt");
1511 }
1512
lv_domain_block_stats(virDomainPtr dom,const char * path,struct lv_block_stats * bstats)1513 static int lv_domain_block_stats(virDomainPtr dom, const char *path,
1514 struct lv_block_stats *bstats) {
1515 #ifdef HAVE_BLOCK_STATS_FLAGS
1516 int nparams = 0;
1517 if (virDomainBlockStatsFlags(dom, path, NULL, &nparams, 0) < 0 ||
1518 nparams <= 0) {
1519 VIRT_ERROR(conn, "getting the disk params count");
1520 return -1;
1521 }
1522
1523 virTypedParameterPtr params = calloc(nparams, sizeof(*params));
1524 if (params == NULL) {
1525 ERROR(PLUGIN_NAME " plugin: alloc(%i) for block=%s parameters failed.",
1526 nparams, path);
1527 return -1;
1528 }
1529
1530 int rc = -1;
1531 if (virDomainBlockStatsFlags(dom, path, params, &nparams, 0) < 0) {
1532 VIRT_ERROR(conn, "getting the disk params values");
1533 } else {
1534 rc = get_block_stats(bstats, params, nparams);
1535 }
1536
1537 virTypedParamsClear(params, nparams);
1538 sfree(params);
1539 return rc;
1540 #else
1541 return virDomainBlockStats(dom, path, &(bstats->bi), sizeof(bstats->bi));
1542 #endif /* HAVE_BLOCK_STATS_FLAGS */
1543 }
1544
1545 #ifdef HAVE_PERF_STATS
perf_submit(virDomainStatsRecordPtr stats)1546 static void perf_submit(virDomainStatsRecordPtr stats) {
1547 for (int i = 0; i < stats->nparams; ++i) {
1548 /* Replace '.' with '_' in event field to match other metrics' naming
1549 * convention */
1550 char *c = strchr(stats->params[i].field, '.');
1551 if (c)
1552 *c = '_';
1553 submit(stats->dom, "perf", stats->params[i].field,
1554 &(value_t){.derive = stats->params[i].value.ul}, 1);
1555 }
1556 }
1557
get_perf_events(virDomainPtr domain)1558 static int get_perf_events(virDomainPtr domain) {
1559 virDomainStatsRecordPtr *stats = NULL;
1560 /* virDomainListGetStats requires a NULL terminated list of domains */
1561 virDomainPtr domain_array[] = {domain, NULL};
1562
1563 int status =
1564 virDomainListGetStats(domain_array, VIR_DOMAIN_STATS_PERF, &stats, 0);
1565 if (status == -1) {
1566 ERROR(PLUGIN_NAME " plugin: virDomainListGetStats failed with status %i.",
1567 status);
1568
1569 virErrorPtr err = virGetLastError();
1570 if (err->code == VIR_ERR_NO_SUPPORT) {
1571 ERROR(PLUGIN_NAME
1572 " plugin: Disabled unsupported ExtraStats selector: perf");
1573 extra_stats &= ~(ex_stats_perf);
1574 }
1575
1576 return -1;
1577 }
1578
1579 for (int i = 0; i < status; ++i)
1580 perf_submit(stats[i]);
1581
1582 virDomainStatsRecordListFree(stats);
1583 return 0;
1584 }
1585 #endif /* HAVE_PERF_STATS */
1586
vcpu_pin_submit(virDomainPtr dom,int max_cpus,int vcpu,unsigned char * cpu_maps,int cpu_map_len)1587 static void vcpu_pin_submit(virDomainPtr dom, int max_cpus, int vcpu,
1588 unsigned char *cpu_maps, int cpu_map_len) {
1589 for (int cpu = 0; cpu < max_cpus; ++cpu) {
1590 char type_instance[DATA_MAX_NAME_LEN];
1591 bool is_set = VIR_CPU_USABLE(cpu_maps, cpu_map_len, vcpu, cpu);
1592
1593 ssnprintf(type_instance, sizeof(type_instance), "vcpu_%d-cpu_%d", vcpu,
1594 cpu);
1595 submit(dom, "cpu_affinity", type_instance, &(value_t){.gauge = is_set}, 1);
1596 }
1597 }
1598
get_vcpu_stats(virDomainPtr domain,unsigned short nr_virt_cpu)1599 static int get_vcpu_stats(virDomainPtr domain, unsigned short nr_virt_cpu) {
1600 int max_cpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
1601
1602 virVcpuInfoPtr vinfo = calloc(nr_virt_cpu, sizeof(*vinfo));
1603 if (vinfo == NULL) {
1604 ERROR(PLUGIN_NAME " plugin: calloc failed.");
1605 return -1;
1606 }
1607
1608 int cpu_map_len = 0;
1609 unsigned char *cpumaps = NULL;
1610 if (extra_stats & ex_stats_vcpupin) {
1611 cpu_map_len = VIR_CPU_MAPLEN(max_cpus);
1612 cpumaps = calloc(nr_virt_cpu, cpu_map_len);
1613
1614 if (cpumaps == NULL) {
1615 ERROR(PLUGIN_NAME " plugin: calloc failed.");
1616 sfree(vinfo);
1617 return -1;
1618 }
1619 }
1620
1621 int status =
1622 virDomainGetVcpus(domain, vinfo, nr_virt_cpu, cpumaps, cpu_map_len);
1623 if (status < 0) {
1624 ERROR(PLUGIN_NAME " plugin: virDomainGetVcpus failed with status %i.",
1625 status);
1626
1627 virErrorPtr err = virGetLastError();
1628 if (err->code == VIR_ERR_NO_SUPPORT) {
1629 if (extra_stats & ex_stats_vcpu)
1630 ERROR(PLUGIN_NAME
1631 " plugin: Disabled unsupported ExtraStats selector: vcpu");
1632 if (extra_stats & ex_stats_vcpupin)
1633 ERROR(PLUGIN_NAME
1634 " plugin: Disabled unsupported ExtraStats selector: vcpupin");
1635 extra_stats &= ~(ex_stats_vcpu | ex_stats_vcpupin);
1636 }
1637
1638 sfree(cpumaps);
1639 sfree(vinfo);
1640 return -1;
1641 }
1642
1643 for (int i = 0; i < nr_virt_cpu; ++i) {
1644 if (extra_stats & ex_stats_vcpu)
1645 vcpu_submit(vinfo[i].cpuTime, domain, vinfo[i].number, "virt_vcpu");
1646 if (extra_stats & ex_stats_vcpupin)
1647 vcpu_pin_submit(domain, max_cpus, i, cpumaps, cpu_map_len);
1648 }
1649
1650 sfree(cpumaps);
1651 sfree(vinfo);
1652 return 0;
1653 }
1654
1655 #ifdef HAVE_CPU_STATS
get_pcpu_stats(virDomainPtr dom)1656 static int get_pcpu_stats(virDomainPtr dom) {
1657 int nparams = virDomainGetCPUStats(dom, NULL, 0, -1, 1, 0);
1658 if (nparams < 0) {
1659 VIRT_ERROR(conn, "getting the CPU params count");
1660
1661 virErrorPtr err = virGetLastError();
1662 if (err->code == VIR_ERR_NO_SUPPORT) {
1663 ERROR(PLUGIN_NAME
1664 " plugin: Disabled unsupported ExtraStats selector: pcpu");
1665 extra_stats &= ~(ex_stats_pcpu);
1666 }
1667
1668 return -1;
1669 }
1670
1671 virTypedParameterPtr param = calloc(nparams, sizeof(*param));
1672 if (param == NULL) {
1673 ERROR(PLUGIN_NAME " plugin: alloc(%i) for cpu parameters failed.", nparams);
1674 return -1;
1675 }
1676
1677 int ret = virDomainGetCPUStats(dom, param, nparams, -1, 1, 0); // total stats.
1678 if (ret < 0) {
1679 virTypedParamsClear(param, nparams);
1680 sfree(param);
1681 VIRT_ERROR(conn, "getting the CPU params values");
1682 return -1;
1683 }
1684
1685 unsigned long long total_user_cpu_time = 0;
1686 unsigned long long total_syst_cpu_time = 0;
1687
1688 for (int i = 0; i < nparams; ++i) {
1689 if (!strcmp(param[i].field, "user_time"))
1690 total_user_cpu_time = param[i].value.ul;
1691 else if (!strcmp(param[i].field, "system_time"))
1692 total_syst_cpu_time = param[i].value.ul;
1693 }
1694
1695 if (total_user_cpu_time > 0 || total_syst_cpu_time > 0)
1696 submit_derive2("ps_cputime", total_user_cpu_time, total_syst_cpu_time, dom,
1697 NULL);
1698
1699 virTypedParamsClear(param, nparams);
1700 sfree(param);
1701
1702 return 0;
1703 }
1704 #endif /* HAVE_CPU_STATS */
1705
1706 #ifdef HAVE_DOM_REASON
submit_domain_state(virDomainPtr domain)1707 static int submit_domain_state(virDomainPtr domain) {
1708 int domain_state = 0;
1709 int domain_reason = 0;
1710
1711 int status = virDomainGetState(domain, &domain_state, &domain_reason, 0);
1712 if (status != 0) {
1713 ERROR(PLUGIN_NAME " plugin: virDomainGetState failed with status %i.",
1714 status);
1715 return status;
1716 }
1717
1718 value_t values[] = {
1719 {.gauge = (gauge_t)domain_state},
1720 {.gauge = (gauge_t)domain_reason},
1721 };
1722
1723 submit(domain, "domain_state", NULL, values, STATIC_ARRAY_SIZE(values));
1724
1725 return 0;
1726 }
1727
1728 #ifdef HAVE_LIST_ALL_DOMAINS
get_domain_state_notify(virDomainPtr domain)1729 static int get_domain_state_notify(virDomainPtr domain) {
1730 int domain_state = 0;
1731 int domain_reason = 0;
1732
1733 int status = virDomainGetState(domain, &domain_state, &domain_reason, 0);
1734 if (status != 0) {
1735 ERROR(PLUGIN_NAME " plugin: virDomainGetState failed with status %i.",
1736 status);
1737 return status;
1738 }
1739
1740 domain_state_submit_notif(domain, domain_state, domain_reason);
1741
1742 return status;
1743 }
1744 #endif /* HAVE_LIST_ALL_DOMAINS */
1745 #endif /* HAVE_DOM_REASON */
1746
get_memory_stats(virDomainPtr domain)1747 static int get_memory_stats(virDomainPtr domain) {
1748 virDomainMemoryStatPtr minfo =
1749 calloc(VIR_DOMAIN_MEMORY_STAT_NR, sizeof(*minfo));
1750 if (minfo == NULL) {
1751 ERROR(PLUGIN_NAME " plugin: calloc failed.");
1752 return -1;
1753 }
1754
1755 int mem_stats =
1756 virDomainMemoryStats(domain, minfo, VIR_DOMAIN_MEMORY_STAT_NR, 0);
1757 if (mem_stats < 0) {
1758 ERROR(PLUGIN_NAME " plugin: virDomainMemoryStats failed with mem_stats %i.",
1759 mem_stats);
1760 sfree(minfo);
1761
1762 virErrorPtr err = virGetLastError();
1763 if (err->code == VIR_ERR_NO_SUPPORT) {
1764 ERROR(PLUGIN_NAME
1765 " plugin: Disabled unsupported ExtraStats selector: memory");
1766 extra_stats &= ~(ex_stats_memory);
1767 }
1768
1769 return -1;
1770 }
1771
1772 derive_t swap_in = -1;
1773 derive_t swap_out = -1;
1774 derive_t min_flt = -1;
1775 derive_t maj_flt = -1;
1776
1777 for (int i = 0; i < mem_stats; i++) {
1778 if (minfo[i].tag == VIR_DOMAIN_MEMORY_STAT_SWAP_IN)
1779 swap_in = minfo[i].val;
1780 else if (minfo[i].tag == VIR_DOMAIN_MEMORY_STAT_SWAP_OUT)
1781 swap_out = minfo[i].val;
1782 else if (minfo[i].tag == VIR_DOMAIN_MEMORY_STAT_MINOR_FAULT)
1783 min_flt = minfo[i].val;
1784 else if (minfo[i].tag == VIR_DOMAIN_MEMORY_STAT_MAJOR_FAULT)
1785 maj_flt = minfo[i].val;
1786 #ifdef LIBVIR_CHECK_VERSION
1787 #if LIBVIR_CHECK_VERSION(2, 1, 0)
1788 else if (minfo[i].tag == VIR_DOMAIN_MEMORY_STAT_LAST_UPDATE)
1789 /* Skip 'last_update' reporting as that is not memory but timestamp */
1790 continue;
1791 #endif
1792 #endif
1793 else
1794 memory_stats_submit((gauge_t)minfo[i].val * 1024, domain, minfo[i].tag);
1795 }
1796
1797 if (swap_in > 0 || swap_out > 0) {
1798 submit(domain, "swap_io", "in", &(value_t){.gauge = swap_in}, 1);
1799 submit(domain, "swap_io", "out", &(value_t){.gauge = swap_out}, 1);
1800 }
1801
1802 if (min_flt > 0 || maj_flt > 0) {
1803 value_t values[] = {
1804 {.gauge = (gauge_t)min_flt},
1805 {.gauge = (gauge_t)maj_flt},
1806 };
1807 submit(domain, "ps_pagefaults", NULL, values, STATIC_ARRAY_SIZE(values));
1808 }
1809
1810 sfree(minfo);
1811 return 0;
1812 }
1813
1814 #ifdef HAVE_DISK_ERR
disk_err_submit(virDomainPtr domain,virDomainDiskErrorPtr disk_err)1815 static void disk_err_submit(virDomainPtr domain,
1816 virDomainDiskErrorPtr disk_err) {
1817 submit(domain, "disk_error", disk_err->disk,
1818 &(value_t){.gauge = disk_err->error}, 1);
1819 }
1820
get_disk_err(virDomainPtr domain)1821 static int get_disk_err(virDomainPtr domain) {
1822 /* Get preferred size of disk errors array */
1823 int disk_err_count = virDomainGetDiskErrors(domain, NULL, 0, 0);
1824 if (disk_err_count == -1) {
1825 ERROR(PLUGIN_NAME
1826 " plugin: failed to get preferred size of disk errors array");
1827
1828 virErrorPtr err = virGetLastError();
1829
1830 if (err->code == VIR_ERR_NO_SUPPORT) {
1831 ERROR(PLUGIN_NAME
1832 " plugin: Disabled unsupported ExtraStats selector: disk_err");
1833 extra_stats &= ~(ex_stats_disk_err);
1834 }
1835
1836 return -1;
1837 }
1838
1839 DEBUG(PLUGIN_NAME
1840 " plugin: preferred size of disk errors array: %d for domain %s",
1841 disk_err_count, virDomainGetName(domain));
1842 virDomainDiskError disk_err[disk_err_count];
1843
1844 disk_err_count = virDomainGetDiskErrors(domain, disk_err, disk_err_count, 0);
1845 if (disk_err_count == -1) {
1846 ERROR(PLUGIN_NAME " plugin: virDomainGetDiskErrors failed with status %d",
1847 disk_err_count);
1848 return -1;
1849 }
1850
1851 DEBUG(PLUGIN_NAME " plugin: detected %d disk errors in domain %s",
1852 disk_err_count, virDomainGetName(domain));
1853
1854 for (int i = 0; i < disk_err_count; ++i) {
1855 disk_err_submit(domain, &disk_err[i]);
1856 sfree(disk_err[i].disk);
1857 }
1858
1859 return 0;
1860 }
1861 #endif /* HAVE_DISK_ERR */
1862
get_block_device_stats(struct block_device * block_dev)1863 static int get_block_device_stats(struct block_device *block_dev) {
1864 if (!block_dev) {
1865 ERROR(PLUGIN_NAME " plugin: get_block_stats NULL pointer");
1866 return -1;
1867 }
1868
1869 virDomainBlockInfo binfo;
1870 init_block_info(&binfo);
1871
1872 /* Fetching block info stats only if needed*/
1873 if (extra_stats & (ex_stats_disk_allocation | ex_stats_disk_capacity |
1874 ex_stats_disk_physical)) {
1875 /* Block info statistics can be only fetched from devices with 'source'
1876 * defined */
1877 if (block_dev->has_source) {
1878 if (virDomainGetBlockInfo(block_dev->dom, block_dev->path, &binfo, 0) <
1879 0) {
1880 ERROR(PLUGIN_NAME " plugin: virDomainGetBlockInfo failed for path: %s",
1881 block_dev->path);
1882
1883 virErrorPtr err = virGetLastError();
1884 if (err->code == VIR_ERR_NO_SUPPORT) {
1885
1886 if (extra_stats & ex_stats_disk_allocation)
1887 ERROR(PLUGIN_NAME " plugin: Disabled unsupported ExtraStats "
1888 "selector: disk_allocation");
1889 if (extra_stats & ex_stats_disk_capacity)
1890 ERROR(PLUGIN_NAME " plugin: Disabled unsupported ExtraStats "
1891 "selector: disk_capacity");
1892 if (extra_stats & ex_stats_disk_physical)
1893 ERROR(PLUGIN_NAME " plugin: Disabled unsupported ExtraStats "
1894 "selector: disk_physical");
1895
1896 extra_stats &= ~(ex_stats_disk_allocation | ex_stats_disk_capacity |
1897 ex_stats_disk_physical);
1898 }
1899
1900 return -1;
1901 }
1902 }
1903 }
1904
1905 struct lv_block_stats bstats;
1906 init_block_stats(&bstats);
1907
1908 if (lv_domain_block_stats(block_dev->dom, block_dev->path, &bstats) < 0) {
1909 ERROR(PLUGIN_NAME " plugin: lv_domain_block_stats failed");
1910 return -1;
1911 }
1912
1913 disk_block_stats_submit(&bstats, block_dev->dom, block_dev->path, &binfo);
1914 return 0;
1915 }
1916
1917 #ifdef HAVE_FS_INFO
1918
1919 #define NM_ADD_ITEM(_fun, _name, _val) \
1920 do { \
1921 ret = _fun(¬if, _name, _val); \
1922 if (ret != 0) { \
1923 ERROR(PLUGIN_NAME " plugin: failed to add notification metadata"); \
1924 goto cleanup; \
1925 } \
1926 } while (0)
1927
1928 #define NM_ADD_STR_ITEMS(_items, _size) \
1929 do { \
1930 for (size_t _i = 0; _i < _size; ++_i) { \
1931 DEBUG(PLUGIN_NAME \
1932 " plugin: Adding notification metadata name=%s value=%s", \
1933 _items[_i].name, _items[_i].value); \
1934 NM_ADD_ITEM(plugin_notification_meta_add_string, _items[_i].name, \
1935 _items[_i].value); \
1936 } \
1937 } while (0)
1938
fs_info_notify(virDomainPtr domain,virDomainFSInfoPtr fs_info)1939 static int fs_info_notify(virDomainPtr domain, virDomainFSInfoPtr fs_info) {
1940 notification_t notif;
1941 int ret = 0;
1942
1943 /* Local struct, just for the purpose of this function. */
1944 typedef struct nm_str_item_s {
1945 const char *name;
1946 const char *value;
1947 } nm_str_item_t;
1948
1949 nm_str_item_t fs_dev_alias[fs_info->ndevAlias];
1950 nm_str_item_t fs_str_items[] = {
1951 {.name = "mountpoint", .value = fs_info->mountpoint},
1952 {.name = "name", .value = fs_info->name},
1953 {.name = "fstype", .value = fs_info->fstype}};
1954
1955 for (size_t i = 0; i < fs_info->ndevAlias; ++i) {
1956 fs_dev_alias[i].name = "devAlias";
1957 fs_dev_alias[i].value = fs_info->devAlias[i];
1958 }
1959
1960 init_notif(¬if, domain, NOTIF_OKAY, "File system information",
1961 "file_system", NULL);
1962 NM_ADD_STR_ITEMS(fs_str_items, STATIC_ARRAY_SIZE(fs_str_items));
1963 NM_ADD_ITEM(plugin_notification_meta_add_unsigned_int, "ndevAlias",
1964 fs_info->ndevAlias);
1965 NM_ADD_STR_ITEMS(fs_dev_alias, fs_info->ndevAlias);
1966
1967 plugin_dispatch_notification(¬if);
1968
1969 cleanup:
1970 if (notif.meta)
1971 plugin_notification_meta_free(notif.meta);
1972 return ret;
1973 }
1974
1975 #undef RETURN_ON_ERR
1976 #undef NM_ADD_STR_ITEMS
1977
get_fs_info(virDomainPtr domain)1978 static int get_fs_info(virDomainPtr domain) {
1979 virDomainFSInfoPtr *fs_info = NULL;
1980 int ret = 0;
1981
1982 int mount_points_cnt = virDomainGetFSInfo(domain, &fs_info, 0);
1983 if (mount_points_cnt == -1) {
1984 ERROR(PLUGIN_NAME " plugin: virDomainGetFSInfo failed: %d",
1985 mount_points_cnt);
1986
1987 virErrorPtr err = virGetLastError();
1988 if (err->code == VIR_ERR_NO_SUPPORT) {
1989 ERROR(PLUGIN_NAME
1990 " plugin: Disabled unsupported ExtraStats selector: fs_info");
1991 extra_stats &= ~(ex_stats_fs_info);
1992 }
1993
1994 return -1;
1995 }
1996
1997 for (int i = 0; i < mount_points_cnt; ++i) {
1998 if (fs_info_notify(domain, fs_info[i]) != 0) {
1999 ERROR(PLUGIN_NAME " plugin: failed to send file system notification "
2000 "for mount point %s",
2001 fs_info[i]->mountpoint);
2002 ret = -1;
2003 }
2004 virDomainFSInfoFree(fs_info[i]);
2005 }
2006
2007 sfree(fs_info);
2008 return ret;
2009 }
2010
2011 #endif /* HAVE_FS_INFO */
2012
2013 #ifdef HAVE_JOB_STATS
job_stats_submit(virDomainPtr domain,virTypedParameterPtr param)2014 static void job_stats_submit(virDomainPtr domain, virTypedParameterPtr param) {
2015 value_t vl = {0};
2016
2017 if (param->type == VIR_TYPED_PARAM_INT)
2018 vl.derive = param->value.i;
2019 else if (param->type == VIR_TYPED_PARAM_UINT)
2020 vl.derive = param->value.ui;
2021 else if (param->type == VIR_TYPED_PARAM_LLONG)
2022 vl.derive = param->value.l;
2023 else if (param->type == VIR_TYPED_PARAM_ULLONG)
2024 vl.derive = param->value.ul;
2025 else if (param->type == VIR_TYPED_PARAM_DOUBLE)
2026 vl.derive = param->value.d;
2027 else if (param->type == VIR_TYPED_PARAM_BOOLEAN)
2028 vl.derive = param->value.b;
2029 else if (param->type == VIR_TYPED_PARAM_STRING) {
2030 submit_notif(domain, NOTIF_OKAY, param->value.s, "job_stats", param->field);
2031 return;
2032 } else {
2033 ERROR(PLUGIN_NAME " plugin: unrecognized virTypedParameterType");
2034 return;
2035 }
2036
2037 submit(domain, "job_stats", param->field, &vl, 1);
2038 }
2039
get_job_stats(virDomainPtr domain)2040 static int get_job_stats(virDomainPtr domain) {
2041 int job_type = 0;
2042 int nparams = 0;
2043 virTypedParameterPtr params = NULL;
2044 int flags = (extra_stats & ex_stats_job_stats_completed)
2045 ? VIR_DOMAIN_JOB_STATS_COMPLETED
2046 : 0;
2047
2048 int ret = virDomainGetJobStats(domain, &job_type, ¶ms, &nparams, flags);
2049 if (ret != 0) {
2050 ERROR(PLUGIN_NAME " plugin: virDomainGetJobStats failed: %d", ret);
2051
2052 virErrorPtr err = virGetLastError();
2053 // VIR_ERR_INVALID_ARG returned when VIR_DOMAIN_JOB_STATS_COMPLETED flag is
2054 // not supported by driver
2055 if (err->code == VIR_ERR_NO_SUPPORT || err->code == VIR_ERR_INVALID_ARG) {
2056 if (extra_stats & ex_stats_job_stats_completed)
2057 ERROR(PLUGIN_NAME " plugin: Disabled unsupported ExtraStats selector: "
2058 "job_stats_completed");
2059 if (extra_stats & ex_stats_job_stats_background)
2060 ERROR(PLUGIN_NAME " plugin: Disabled unsupported ExtraStats selector: "
2061 "job_stats_background");
2062 extra_stats &=
2063 ~(ex_stats_job_stats_completed | ex_stats_job_stats_background);
2064 }
2065 return -1;
2066 }
2067
2068 DEBUG(PLUGIN_NAME " plugin: job_type=%d nparams=%d", job_type, nparams);
2069
2070 for (int i = 0; i < nparams; ++i) {
2071 DEBUG(PLUGIN_NAME " plugin: param[%d] field=%s type=%d", i, params[i].field,
2072 params[i].type);
2073 job_stats_submit(domain, ¶ms[i]);
2074 }
2075
2076 virTypedParamsFree(params, nparams);
2077 return 0;
2078 }
2079 #endif /* HAVE_JOB_STATS */
2080
get_domain_metrics(domain_t * domain)2081 static int get_domain_metrics(domain_t *domain) {
2082 if (!domain || !domain->ptr) {
2083 ERROR(PLUGIN_NAME " plugin: get_domain_metrics: NULL pointer");
2084 return -1;
2085 }
2086
2087 virDomainInfo info;
2088 int status = virDomainGetInfo(domain->ptr, &info);
2089 if (status != 0) {
2090 ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
2091 status);
2092 return -1;
2093 }
2094
2095 if (extra_stats & ex_stats_domain_state) {
2096 #ifdef HAVE_DOM_REASON
2097 /* At this point we already know domain's state from virDomainGetInfo call,
2098 * however it doesn't provide a reason for entering particular state.
2099 * We need to get it from virDomainGetState.
2100 */
2101 GET_STATS(submit_domain_state, "domain reason", domain->ptr);
2102 #endif
2103 }
2104
2105 /* Gather remaining stats only for running domains */
2106 if (info.state != VIR_DOMAIN_RUNNING)
2107 return 0;
2108
2109 #ifdef HAVE_CPU_STATS
2110 if (extra_stats & ex_stats_pcpu)
2111 get_pcpu_stats(domain->ptr);
2112 #endif
2113
2114 cpu_submit(domain, info.cpuTime);
2115
2116 memory_submit(domain->ptr, (gauge_t)info.memory * 1024);
2117
2118 if (extra_stats & (ex_stats_vcpu | ex_stats_vcpupin))
2119 GET_STATS(get_vcpu_stats, "vcpu stats", domain->ptr, info.nrVirtCpu);
2120 if (extra_stats & ex_stats_memory)
2121 GET_STATS(get_memory_stats, "memory stats", domain->ptr);
2122
2123 #ifdef HAVE_PERF_STATS
2124 if (extra_stats & ex_stats_perf)
2125 GET_STATS(get_perf_events, "performance monitoring events", domain->ptr);
2126 #endif
2127
2128 #ifdef HAVE_FS_INFO
2129 if (extra_stats & ex_stats_fs_info)
2130 GET_STATS(get_fs_info, "file system info", domain->ptr);
2131 #endif
2132
2133 #ifdef HAVE_DISK_ERR
2134 if (extra_stats & ex_stats_disk_err)
2135 GET_STATS(get_disk_err, "disk errors", domain->ptr);
2136 #endif
2137
2138 #ifdef HAVE_JOB_STATS
2139 if (extra_stats &
2140 (ex_stats_job_stats_completed | ex_stats_job_stats_background))
2141 GET_STATS(get_job_stats, "job stats", domain->ptr);
2142 #endif
2143
2144 /* Update cached virDomainInfo. It has to be done after cpu_submit */
2145 memcpy(&domain->info, &info, sizeof(domain->info));
2146
2147 return 0;
2148 }
2149
get_if_dev_stats(struct interface_device * if_dev)2150 static int get_if_dev_stats(struct interface_device *if_dev) {
2151 virDomainInterfaceStatsStruct stats = {0};
2152 char *display_name = NULL;
2153
2154 if (!if_dev) {
2155 ERROR(PLUGIN_NAME " plugin: get_if_dev_stats: NULL pointer");
2156 return -1;
2157 }
2158
2159 switch (interface_format) {
2160 case if_address:
2161 display_name = if_dev->address;
2162 break;
2163 case if_number:
2164 display_name = if_dev->number;
2165 break;
2166 case if_name:
2167 default:
2168 display_name = if_dev->path;
2169 }
2170
2171 if (virDomainInterfaceStats(if_dev->dom, if_dev->path, &stats,
2172 sizeof(stats)) != 0) {
2173 ERROR(PLUGIN_NAME " plugin: virDomainInterfaceStats failed");
2174 return -1;
2175 }
2176
2177 if ((stats.rx_bytes != -1) && (stats.tx_bytes != -1))
2178 submit_derive2("if_octets", (derive_t)stats.rx_bytes,
2179 (derive_t)stats.tx_bytes, if_dev->dom, display_name);
2180
2181 if ((stats.rx_packets != -1) && (stats.tx_packets != -1))
2182 submit_derive2("if_packets", (derive_t)stats.rx_packets,
2183 (derive_t)stats.tx_packets, if_dev->dom, display_name);
2184
2185 if ((stats.rx_errs != -1) && (stats.tx_errs != -1))
2186 submit_derive2("if_errors", (derive_t)stats.rx_errs,
2187 (derive_t)stats.tx_errs, if_dev->dom, display_name);
2188
2189 if ((stats.rx_drop != -1) && (stats.tx_drop != -1))
2190 submit_derive2("if_dropped", (derive_t)stats.rx_drop,
2191 (derive_t)stats.tx_drop, if_dev->dom, display_name);
2192 return 0;
2193 }
2194
domain_lifecycle_event_cb(virConnectPtr con_,virDomainPtr dom,int event,int detail,void * opaque)2195 static int domain_lifecycle_event_cb(__attribute__((unused)) virConnectPtr con_,
2196 virDomainPtr dom, int event, int detail,
2197 __attribute__((unused)) void *opaque) {
2198 int domain_state = map_domain_event_to_state(event);
2199 int domain_reason = 0; /* 0 means UNKNOWN reason for any state */
2200 #ifdef HAVE_DOM_REASON
2201 domain_reason = map_domain_event_detail_to_reason(event, detail);
2202 #endif
2203 domain_state_submit_notif(dom, domain_state, domain_reason);
2204
2205 return 0;
2206 }
2207
virt_eventloop_timeout_cb(int timer ATTRIBUTE_UNUSED,void * timer_info)2208 static void virt_eventloop_timeout_cb(int timer ATTRIBUTE_UNUSED,
2209 void *timer_info) {}
2210
register_event_impl(void)2211 static int register_event_impl(void) {
2212 if (virEventRegisterDefaultImpl() < 0) {
2213 virErrorPtr err = virGetLastError();
2214 ERROR(PLUGIN_NAME
2215 " plugin: error while event implementation registering: %s",
2216 err && err->message ? err->message : "Unknown error");
2217 return -1;
2218 }
2219
2220 if (virEventAddTimeout(CDTIME_T_TO_MS(plugin_get_interval()),
2221 virt_eventloop_timeout_cb, NULL, NULL) < 0) {
2222 virErrorPtr err = virGetLastError();
2223 ERROR(PLUGIN_NAME " plugin: virEventAddTimeout failed: %s",
2224 err && err->message ? err->message : "Unknown error");
2225 return -1;
2226 }
2227
2228 return 0;
2229 }
2230
virt_notif_thread_set_active(virt_notif_thread_t * thread_data,const bool active)2231 static void virt_notif_thread_set_active(virt_notif_thread_t *thread_data,
2232 const bool active) {
2233 assert(thread_data != NULL);
2234 pthread_mutex_lock(&thread_data->active_mutex);
2235 thread_data->is_active = active;
2236 pthread_mutex_unlock(&thread_data->active_mutex);
2237 }
2238
virt_notif_thread_is_active(virt_notif_thread_t * thread_data)2239 static bool virt_notif_thread_is_active(virt_notif_thread_t *thread_data) {
2240 bool active = false;
2241
2242 assert(thread_data != NULL);
2243 pthread_mutex_lock(&thread_data->active_mutex);
2244 active = thread_data->is_active;
2245 pthread_mutex_unlock(&thread_data->active_mutex);
2246
2247 return active;
2248 }
2249
2250 /* worker function running default event implementation */
event_loop_worker(void * arg)2251 static void *event_loop_worker(void *arg) {
2252 virt_notif_thread_t *thread_data = (virt_notif_thread_t *)arg;
2253
2254 while (virt_notif_thread_is_active(thread_data)) {
2255 if (virEventRunDefaultImpl() < 0) {
2256 virErrorPtr err = virGetLastError();
2257 ERROR(PLUGIN_NAME " plugin: failed to run event loop: %s\n",
2258 err && err->message ? err->message : "Unknown error");
2259 }
2260 }
2261
2262 return NULL;
2263 }
2264
virt_notif_thread_init(virt_notif_thread_t * thread_data)2265 static int virt_notif_thread_init(virt_notif_thread_t *thread_data) {
2266 assert(thread_data != NULL);
2267
2268 int ret = pthread_mutex_init(&thread_data->active_mutex, NULL);
2269 if (ret != 0) {
2270 ERROR(PLUGIN_NAME " plugin: Failed to initialize mutex, err %u", ret);
2271 return ret;
2272 }
2273
2274 /**
2275 * '0' and positive integers are meaningful ID's, therefore setting
2276 * domain_event_cb_id to '-1'
2277 */
2278 thread_data->domain_event_cb_id = -1;
2279 pthread_mutex_lock(&thread_data->active_mutex);
2280 thread_data->is_active = false;
2281 pthread_mutex_unlock(&thread_data->active_mutex);
2282
2283 return 0;
2284 }
2285
2286 /* register domain event callback and start event loop thread */
start_event_loop(virt_notif_thread_t * thread_data)2287 static int start_event_loop(virt_notif_thread_t *thread_data) {
2288 assert(thread_data != NULL);
2289 thread_data->domain_event_cb_id = virConnectDomainEventRegisterAny(
2290 conn, NULL, VIR_DOMAIN_EVENT_ID_LIFECYCLE,
2291 VIR_DOMAIN_EVENT_CALLBACK(domain_lifecycle_event_cb), NULL, NULL);
2292 if (thread_data->domain_event_cb_id == -1) {
2293 ERROR(PLUGIN_NAME " plugin: error while callback registering");
2294 return -1;
2295 }
2296
2297 DEBUG(PLUGIN_NAME " plugin: starting event loop");
2298
2299 virt_notif_thread_set_active(thread_data, 1);
2300 if (pthread_create(&thread_data->event_loop_tid, NULL, event_loop_worker,
2301 thread_data)) {
2302 ERROR(PLUGIN_NAME " plugin: failed event loop thread creation");
2303 virt_notif_thread_set_active(thread_data, 0);
2304 virConnectDomainEventDeregisterAny(conn, thread_data->domain_event_cb_id);
2305 thread_data->domain_event_cb_id = -1;
2306 return -1;
2307 }
2308
2309 return 0;
2310 }
2311
2312 /* stop event loop thread and deregister callback */
stop_event_loop(virt_notif_thread_t * thread_data)2313 static void stop_event_loop(virt_notif_thread_t *thread_data) {
2314
2315 DEBUG(PLUGIN_NAME " plugin: stopping event loop");
2316
2317 /* Stopping loop */
2318 if (virt_notif_thread_is_active(thread_data)) {
2319 virt_notif_thread_set_active(thread_data, 0);
2320 if (pthread_join(notif_thread.event_loop_tid, NULL) != 0)
2321 ERROR(PLUGIN_NAME " plugin: stopping notification thread failed");
2322 }
2323
2324 /* ... and de-registering event handler */
2325 if (conn != NULL && thread_data->domain_event_cb_id != -1) {
2326 virConnectDomainEventDeregisterAny(conn, thread_data->domain_event_cb_id);
2327 thread_data->domain_event_cb_id = -1;
2328 }
2329 }
2330
persistent_domains_state_notification(void)2331 static int persistent_domains_state_notification(void) {
2332 int status = 0;
2333 int n;
2334 #ifdef HAVE_LIST_ALL_DOMAINS
2335 virDomainPtr *domains = NULL;
2336 n = virConnectListAllDomains(conn, &domains,
2337 VIR_CONNECT_LIST_DOMAINS_PERSISTENT);
2338 if (n < 0) {
2339 VIRT_ERROR(conn, "reading list of persistent domains");
2340 status = -1;
2341 } else {
2342 DEBUG(PLUGIN_NAME " plugin: getting state of %i persistent domains", n);
2343 /* Fetch each persistent domain's state and notify it */
2344 int n_notified = n;
2345 for (int i = 0; i < n; ++i) {
2346 status = get_domain_state_notify(domains[i]);
2347 if (status != 0) {
2348 n_notified--;
2349 ERROR(PLUGIN_NAME " plugin: could not notify state of domain %s",
2350 virDomainGetName(domains[i]));
2351 }
2352 virDomainFree(domains[i]);
2353 }
2354
2355 sfree(domains);
2356 DEBUG(PLUGIN_NAME " plugin: notified state of %i persistent domains",
2357 n_notified);
2358 }
2359 #else
2360 n = virConnectNumOfDomains(conn);
2361 if (n > 0) {
2362 int *domids;
2363 /* Get list of domains. */
2364 domids = calloc(n, sizeof(*domids));
2365 if (domids == NULL) {
2366 ERROR(PLUGIN_NAME " plugin: calloc failed.");
2367 return -1;
2368 }
2369 n = virConnectListDomains(conn, domids, n);
2370 if (n < 0) {
2371 VIRT_ERROR(conn, "reading list of domains");
2372 sfree(domids);
2373 return -1;
2374 }
2375 /* Fetch info of each active domain and notify it */
2376 for (int i = 0; i < n; ++i) {
2377 virDomainInfo info;
2378 virDomainPtr dom = NULL;
2379 dom = virDomainLookupByID(conn, domids[i]);
2380 if (dom == NULL) {
2381 VIRT_ERROR(conn, "virDomainLookupByID");
2382 /* Could be that the domain went away -- ignore it anyway. */
2383 continue;
2384 }
2385 status = virDomainGetInfo(dom, &info);
2386 if (status == 0)
2387 /* virDomainGetState is not available. Submit 0, which corresponds to
2388 * unknown reason. */
2389 domain_state_submit_notif(dom, info.state, 0);
2390 else
2391 ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
2392 status);
2393
2394 virDomainFree(dom);
2395 }
2396 sfree(domids);
2397 }
2398 #endif
2399
2400 return status;
2401 }
2402
lv_read(user_data_t * ud)2403 static int lv_read(user_data_t *ud) {
2404 if (ud->data == NULL) {
2405 ERROR(PLUGIN_NAME " plugin: NULL userdata");
2406 return -1;
2407 }
2408
2409 struct lv_read_instance *inst = ud->data;
2410 struct lv_read_state *state = &inst->read_state;
2411
2412 if (inst->id == 0)
2413 if (lv_connect() < 0)
2414 return -1;
2415
2416 /* Wait until inst#0 establish connection */
2417 if (conn == NULL) {
2418 DEBUG(PLUGIN_NAME " plugin#%s: Wait until inst#0 establish connection",
2419 inst->tag);
2420 return 0;
2421 }
2422
2423 int ret = virConnectIsAlive(conn);
2424 if (ret == 0) { /* Connection lost */
2425 if (inst->id == 0) {
2426 c_complain(LOG_ERR, &conn_complain,
2427 PLUGIN_NAME " plugin: Lost connection.");
2428
2429 if (!persistent_notification)
2430 stop_event_loop(¬if_thread);
2431
2432 lv_disconnect();
2433 last_refresh = 0;
2434 }
2435 return -1;
2436 }
2437
2438 time_t t;
2439 time(&t);
2440
2441 /* Need to refresh domain or device lists? */
2442 if ((last_refresh == (time_t)0) ||
2443 ((interval > 0) && ((last_refresh + interval) <= t))) {
2444 if (refresh_lists(inst) != 0) {
2445 if (inst->id == 0) {
2446 if (!persistent_notification)
2447 stop_event_loop(¬if_thread);
2448 lv_disconnect();
2449 }
2450 return -1;
2451 }
2452 last_refresh = t;
2453 }
2454
2455 /* persistent domains state notifications are handled by instance 0 */
2456 if (inst->id == 0 && persistent_notification) {
2457 int status = persistent_domains_state_notification();
2458 if (status != 0)
2459 DEBUG(PLUGIN_NAME " plugin: persistent_domains_state_notifications "
2460 "returned with status %i",
2461 status);
2462 }
2463
2464 #if COLLECT_DEBUG
2465 for (int i = 0; i < state->nr_domains; ++i)
2466 DEBUG(PLUGIN_NAME " plugin: domain %s",
2467 virDomainGetName(state->domains[i].ptr));
2468 for (int i = 0; i < state->nr_block_devices; ++i)
2469 DEBUG(PLUGIN_NAME " plugin: block device %d %s:%s", i,
2470 virDomainGetName(state->block_devices[i].dom),
2471 state->block_devices[i].path);
2472 for (int i = 0; i < state->nr_interface_devices; ++i)
2473 DEBUG(PLUGIN_NAME " plugin: interface device %d %s:%s", i,
2474 virDomainGetName(state->interface_devices[i].dom),
2475 state->interface_devices[i].path);
2476 #endif
2477
2478 /* Get domains' metrics */
2479 for (int i = 0; i < state->nr_domains; ++i) {
2480 domain_t *dom = &state->domains[i];
2481 int status = 0;
2482 if (dom->active)
2483 status = get_domain_metrics(dom);
2484 #ifdef HAVE_DOM_REASON
2485 else if (extra_stats & ex_stats_domain_state)
2486 status = submit_domain_state(dom->ptr);
2487 #endif
2488
2489 if (status != 0)
2490 ERROR(PLUGIN_NAME " plugin: failed to get metrics for domain=%s",
2491 virDomainGetName(dom->ptr));
2492 }
2493
2494 /* Get block device stats for each domain. */
2495 for (int i = 0; i < state->nr_block_devices; ++i) {
2496 int status = get_block_device_stats(&state->block_devices[i]);
2497 if (status != 0)
2498 ERROR(PLUGIN_NAME
2499 " plugin: failed to get stats for block device (%s) in domain %s",
2500 state->block_devices[i].path,
2501 virDomainGetName(state->block_devices[i].dom));
2502 }
2503
2504 /* Get interface stats for each domain. */
2505 for (int i = 0; i < state->nr_interface_devices; ++i) {
2506 int status = get_if_dev_stats(&state->interface_devices[i]);
2507 if (status != 0)
2508 ERROR(
2509 PLUGIN_NAME
2510 " plugin: failed to get interface stats for device (%s) in domain %s",
2511 state->interface_devices[i].path,
2512 virDomainGetName(state->interface_devices[i].dom));
2513 }
2514
2515 return 0;
2516 }
2517
lv_init_instance(size_t i,plugin_read_cb callback)2518 static int lv_init_instance(size_t i, plugin_read_cb callback) {
2519 struct lv_user_data *lv_ud = &(lv_read_user_data[i]);
2520 struct lv_read_instance *inst = &(lv_ud->inst);
2521
2522 memset(lv_ud, 0, sizeof(*lv_ud));
2523
2524 ssnprintf(inst->tag, sizeof(inst->tag), "%s-%" PRIsz, PLUGIN_NAME, i);
2525 inst->id = i;
2526
2527 user_data_t *ud = &(lv_ud->ud);
2528 ud->data = inst;
2529 ud->free_func = NULL;
2530
2531 INFO(PLUGIN_NAME " plugin: reader %s initialized", inst->tag);
2532
2533 return plugin_register_complex_read(NULL, inst->tag, callback, 0, ud);
2534 }
2535
lv_clean_read_state(struct lv_read_state * state)2536 static void lv_clean_read_state(struct lv_read_state *state) {
2537 free_block_devices(state);
2538 free_interface_devices(state);
2539 free_domains(state);
2540 }
2541
lv_fini_instance(size_t i)2542 static void lv_fini_instance(size_t i) {
2543 struct lv_read_instance *inst = &(lv_read_user_data[i].inst);
2544 struct lv_read_state *state = &(inst->read_state);
2545
2546 lv_clean_read_state(state);
2547
2548 INFO(PLUGIN_NAME " plugin: reader %s finalized", inst->tag);
2549 }
2550
lv_init(void)2551 static int lv_init(void) {
2552 if (virInitialize() != 0)
2553 return -1;
2554
2555 /* Init ignorelists if there was no explicit configuration */
2556 if (lv_init_ignorelists() != 0)
2557 return -1;
2558
2559 if (!persistent_notification)
2560 if (virt_notif_thread_init(¬if_thread) != 0)
2561 return -1;
2562
2563 lv_connect();
2564
2565 DEBUG(PLUGIN_NAME " plugin: starting %i instances", nr_instances);
2566
2567 for (int i = 0; i < nr_instances; ++i)
2568 if (lv_init_instance(i, lv_read) != 0)
2569 return -1;
2570
2571 return 0;
2572 }
2573
2574 /*
2575 * returns 0 on success and <0 on error
2576 */
lv_domain_get_tag(xmlXPathContextPtr xpath_ctx,const char * dom_name,char * dom_tag)2577 static int lv_domain_get_tag(xmlXPathContextPtr xpath_ctx, const char *dom_name,
2578 char *dom_tag) {
2579 char xpath_str[BUFFER_MAX_LEN] = {'\0'};
2580 xmlXPathObjectPtr xpath_obj = NULL;
2581 xmlNodePtr xml_node = NULL;
2582 int ret = -1;
2583 int err;
2584
2585 err = xmlXPathRegisterNs(xpath_ctx,
2586 (const xmlChar *)METADATA_VM_PARTITION_PREFIX,
2587 (const xmlChar *)METADATA_VM_PARTITION_URI);
2588 if (err) {
2589 ERROR(PLUGIN_NAME " plugin: xmlXpathRegisterNs(%s, %s) failed on domain %s",
2590 METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_URI, dom_name);
2591 goto done;
2592 }
2593
2594 ssnprintf(xpath_str, sizeof(xpath_str), "/domain/metadata/%s:%s/text()",
2595 METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_ELEMENT);
2596 xpath_obj = xmlXPathEvalExpression((xmlChar *)xpath_str, xpath_ctx);
2597 if (xpath_obj == NULL) {
2598 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) failed on domain %s",
2599 xpath_str, dom_name);
2600 goto done;
2601 }
2602
2603 if (xpath_obj->type != XPATH_NODESET) {
2604 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) unexpected return type %d "
2605 "(wanted %d) on domain %s",
2606 xpath_str, xpath_obj->type, XPATH_NODESET, dom_name);
2607 goto done;
2608 }
2609
2610 /*
2611 * from now on there is no real error, it's ok if a domain
2612 * doesn't have the metadata partition tag.
2613 */
2614 ret = 0;
2615 if (xpath_obj->nodesetval == NULL || xpath_obj->nodesetval->nodeNr != 1) {
2616 DEBUG(PLUGIN_NAME " plugin: xmlXPathEval(%s) return nodeset size=%i "
2617 "expected=1 on domain %s",
2618 xpath_str,
2619 (xpath_obj->nodesetval == NULL) ? 0 : xpath_obj->nodesetval->nodeNr,
2620 dom_name);
2621 } else {
2622 xml_node = xpath_obj->nodesetval->nodeTab[0];
2623 sstrncpy(dom_tag, (const char *)xml_node->content, PARTITION_TAG_MAX_LEN);
2624 }
2625
2626 done:
2627 /* deregister to clean up */
2628 err = xmlXPathRegisterNs(xpath_ctx,
2629 (const xmlChar *)METADATA_VM_PARTITION_PREFIX, NULL);
2630 if (err) {
2631 /* we can't really recover here */
2632 ERROR(PLUGIN_NAME
2633 " plugin: deregistration of namespace %s failed for domain %s",
2634 METADATA_VM_PARTITION_PREFIX, dom_name);
2635 }
2636 if (xpath_obj)
2637 xmlXPathFreeObject(xpath_obj);
2638
2639 return ret;
2640 }
2641
is_known_tag(const char * dom_tag)2642 static int is_known_tag(const char *dom_tag) {
2643 for (int i = 0; i < nr_instances; ++i)
2644 if (!strcmp(dom_tag, lv_read_user_data[i].inst.tag))
2645 return 1;
2646 return 0;
2647 }
2648
lv_instance_include_domain(struct lv_read_instance * inst,const char * dom_name,const char * dom_tag)2649 static int lv_instance_include_domain(struct lv_read_instance *inst,
2650 const char *dom_name,
2651 const char *dom_tag) {
2652 if ((dom_tag[0] != '\0') && (strcmp(dom_tag, inst->tag) == 0))
2653 return 1;
2654
2655 /* instance#0 will always be there, so it is in charge of extra duties */
2656 if (inst->id == 0) {
2657 if (dom_tag[0] == '\0' || !is_known_tag(dom_tag)) {
2658 DEBUG(PLUGIN_NAME " plugin#%s: refreshing domain %s "
2659 "with unknown tag '%s'",
2660 inst->tag, dom_name, dom_tag);
2661 return 1;
2662 }
2663 }
2664
2665 return 0;
2666 }
2667
lv_add_block_devices(struct lv_read_state * state,virDomainPtr dom,const char * domname,xmlXPathContextPtr xpath_ctx)2668 static void lv_add_block_devices(struct lv_read_state *state, virDomainPtr dom,
2669 const char *domname,
2670 xmlXPathContextPtr xpath_ctx) {
2671 xmlXPathObjectPtr xpath_obj =
2672 xmlXPathEval((const xmlChar *)"/domain/devices/disk", xpath_ctx);
2673
2674 if (xpath_obj == NULL) {
2675 DEBUG(PLUGIN_NAME " plugin: no disk xpath-object found for domain %s",
2676 domname);
2677 return;
2678 }
2679
2680 if (xpath_obj->type != XPATH_NODESET || xpath_obj->nodesetval == NULL) {
2681 DEBUG(PLUGIN_NAME " plugin: no disk node found for domain %s", domname);
2682 goto cleanup;
2683 }
2684
2685 xmlNodeSetPtr xml_block_devices = xpath_obj->nodesetval;
2686 for (int i = 0; i < xml_block_devices->nodeNr; ++i) {
2687 xmlNodePtr xml_device = xpath_obj->nodesetval->nodeTab[i];
2688 char *path_str = NULL;
2689 char *source_str = NULL;
2690
2691 if (!xml_device)
2692 continue;
2693
2694 /* Fetching path and source for block device */
2695 for (xmlNodePtr child = xml_device->children; child; child = child->next) {
2696 if (child->type != XML_ELEMENT_NODE)
2697 continue;
2698
2699 /* we are interested only in either "target" or "source" elements */
2700 if (xmlStrEqual(child->name, (const xmlChar *)"target"))
2701 path_str = (char *)xmlGetProp(child, (const xmlChar *)"dev");
2702 else if (xmlStrEqual(child->name, (const xmlChar *)"source")) {
2703 /* name of the source is located in "dev" or "file" element (it depends
2704 * on type of source). Trying "dev" at first*/
2705 source_str = (char *)xmlGetProp(child, (const xmlChar *)"dev");
2706 if (!source_str)
2707 source_str = (char *)xmlGetProp(child, (const xmlChar *)"file");
2708 }
2709 /* ignoring any other element*/
2710 }
2711
2712 /* source_str will be interpreted as a device path if blockdevice_format
2713 * param is set to 'source'. */
2714 const char *device_path =
2715 (blockdevice_format == source) ? source_str : path_str;
2716
2717 if (!device_path) {
2718 /* no path found and we can't add block_device without it */
2719 WARNING(PLUGIN_NAME " plugin: could not generate device path for disk in "
2720 "domain %s - disk device will be ignored in reports",
2721 domname);
2722 goto cont;
2723 }
2724
2725 if (ignore_device_match(il_block_devices, domname, device_path) == 0) {
2726 /* we only have to store information whether 'source' exists or not */
2727 bool has_source = (source_str != NULL) ? true : false;
2728
2729 add_block_device(state, dom, device_path, has_source);
2730 }
2731
2732 cont:
2733 if (path_str)
2734 xmlFree(path_str);
2735
2736 if (source_str)
2737 xmlFree(source_str);
2738 }
2739
2740 cleanup:
2741 xmlXPathFreeObject(xpath_obj);
2742 }
2743
lv_add_network_interfaces(struct lv_read_state * state,virDomainPtr dom,const char * domname,xmlXPathContextPtr xpath_ctx)2744 static void lv_add_network_interfaces(struct lv_read_state *state,
2745 virDomainPtr dom, const char *domname,
2746 xmlXPathContextPtr xpath_ctx) {
2747 xmlXPathObjectPtr xpath_obj = xmlXPathEval(
2748 (xmlChar *)"/domain/devices/interface[target[@dev]]", xpath_ctx);
2749
2750 if (xpath_obj == NULL)
2751 return;
2752
2753 if (xpath_obj->type != XPATH_NODESET || xpath_obj->nodesetval == NULL) {
2754 xmlXPathFreeObject(xpath_obj);
2755 return;
2756 }
2757
2758 xmlNodeSetPtr xml_interfaces = xpath_obj->nodesetval;
2759
2760 for (int j = 0; j < xml_interfaces->nodeNr; ++j) {
2761 char *path = NULL;
2762 char *address = NULL;
2763 const int itf_number = j + 1;
2764
2765 xmlNodePtr xml_interface = xml_interfaces->nodeTab[j];
2766 if (!xml_interface)
2767 continue;
2768
2769 for (xmlNodePtr child = xml_interface->children; child;
2770 child = child->next) {
2771 if (child->type != XML_ELEMENT_NODE)
2772 continue;
2773
2774 if (xmlStrEqual(child->name, (const xmlChar *)"target")) {
2775 path = (char *)xmlGetProp(child, (const xmlChar *)"dev");
2776 if (!path)
2777 continue;
2778 } else if (xmlStrEqual(child->name, (const xmlChar *)"mac")) {
2779 address = (char *)xmlGetProp(child, (const xmlChar *)"address");
2780 if (!address)
2781 continue;
2782 }
2783 }
2784
2785 bool device_ignored = false;
2786 switch (interface_format) {
2787 case if_name:
2788 if (ignore_device_match(il_interface_devices, domname, path) != 0)
2789 device_ignored = true;
2790 break;
2791 case if_address:
2792 if (ignore_device_match(il_interface_devices, domname, address) != 0)
2793 device_ignored = true;
2794 break;
2795 case if_number: {
2796 char number_string[4];
2797 ssnprintf(number_string, sizeof(number_string), "%d", itf_number);
2798 if (ignore_device_match(il_interface_devices, domname, number_string) !=
2799 0)
2800 device_ignored = true;
2801 } break;
2802 default:
2803 ERROR(PLUGIN_NAME " plugin: Unknown interface_format option: %d",
2804 interface_format);
2805 }
2806
2807 if (!device_ignored)
2808 add_interface_device(state, dom, path, address, itf_number);
2809
2810 if (path)
2811 xmlFree(path);
2812 if (address)
2813 xmlFree(address);
2814 }
2815 xmlXPathFreeObject(xpath_obj);
2816 }
2817
is_domain_ignored(virDomainPtr dom)2818 static bool is_domain_ignored(virDomainPtr dom) {
2819 const char *domname = virDomainGetName(dom);
2820
2821 if (domname == NULL) {
2822 VIRT_ERROR(conn, "virDomainGetName failed, ignoring domain");
2823 return true;
2824 }
2825
2826 if (ignorelist_match(il_domains, domname) != 0) {
2827 DEBUG(PLUGIN_NAME
2828 " plugin: ignoring domain '%s' because of ignorelist option",
2829 domname);
2830 return true;
2831 }
2832
2833 return false;
2834 }
2835
refresh_lists(struct lv_read_instance * inst)2836 static int refresh_lists(struct lv_read_instance *inst) {
2837 struct lv_read_state *state = &inst->read_state;
2838 int n;
2839
2840 #ifndef HAVE_LIST_ALL_DOMAINS
2841 n = virConnectNumOfDomains(conn);
2842 if (n < 0) {
2843 VIRT_ERROR(conn, "reading number of domains");
2844 return -1;
2845 }
2846 #endif
2847
2848 lv_clean_read_state(state);
2849
2850 #ifndef HAVE_LIST_ALL_DOMAINS
2851 if (n == 0)
2852 goto end;
2853 #endif
2854
2855 #ifdef HAVE_LIST_ALL_DOMAINS
2856 virDomainPtr *domains, *domains_inactive;
2857 int m = virConnectListAllDomains(conn, &domains_inactive,
2858 VIR_CONNECT_LIST_DOMAINS_INACTIVE);
2859 n = virConnectListAllDomains(conn, &domains, VIR_CONNECT_LIST_DOMAINS_ACTIVE);
2860 #else
2861 /* Get list of domains. */
2862 int *domids = calloc(n, sizeof(*domids));
2863 if (domids == NULL) {
2864 ERROR(PLUGIN_NAME " plugin: calloc failed.");
2865 return -1;
2866 }
2867
2868 n = virConnectListDomains(conn, domids, n);
2869 #endif
2870
2871 if (n < 0) {
2872 VIRT_ERROR(conn, "reading list of domains");
2873 #ifndef HAVE_LIST_ALL_DOMAINS
2874 sfree(domids);
2875 #else
2876 for (int i = 0; i < m; ++i)
2877 virDomainFree(domains_inactive[i]);
2878 sfree(domains_inactive);
2879 #endif
2880 return -1;
2881 }
2882
2883 #ifdef HAVE_LIST_ALL_DOMAINS
2884 for (int i = 0; i < m; ++i)
2885 if (is_domain_ignored(domains_inactive[i]) ||
2886 add_domain(state, domains_inactive[i], 0) < 0) {
2887 /* domain ignored or failed during adding to domains list*/
2888 virDomainFree(domains_inactive[i]);
2889 domains_inactive[i] = NULL;
2890 continue;
2891 }
2892 #endif
2893
2894 /* Fetch each domain and add it to the list, unless ignore. */
2895 for (int i = 0; i < n; ++i) {
2896
2897 #ifdef HAVE_LIST_ALL_DOMAINS
2898 virDomainPtr dom = domains[i];
2899 #else
2900 virDomainPtr dom = virDomainLookupByID(conn, domids[i]);
2901 if (dom == NULL) {
2902 VIRT_ERROR(conn, "virDomainLookupByID");
2903 /* Could be that the domain went away -- ignore it anyway. */
2904 continue;
2905 }
2906 #endif
2907
2908 if (is_domain_ignored(dom) || add_domain(state, dom, 1) < 0) {
2909 /*
2910 * domain ignored or failed during adding to domains list
2911 *
2912 * When domain is already tracked, then there is
2913 * no problem with memory handling (will be freed
2914 * with the rest of domains cached data)
2915 * But in case of error like this (error occurred
2916 * before adding domain to track) we have to take
2917 * care it ourselves and call virDomainFree
2918 */
2919 virDomainFree(dom);
2920 continue;
2921 }
2922
2923 const char *domname = virDomainGetName(dom);
2924 if (domname == NULL) {
2925 VIRT_ERROR(conn, "virDomainGetName");
2926 continue;
2927 }
2928
2929 virDomainInfo info;
2930 int status = virDomainGetInfo(dom, &info);
2931 if (status != 0) {
2932 ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
2933 status);
2934 continue;
2935 }
2936
2937 if (info.state != VIR_DOMAIN_RUNNING) {
2938 DEBUG(PLUGIN_NAME " plugin: skipping inactive domain %s", domname);
2939 continue;
2940 }
2941
2942 /* Get a list of devices for this domain. */
2943 xmlDocPtr xml_doc = NULL;
2944 xmlXPathContextPtr xpath_ctx = NULL;
2945
2946 char *xml = virDomainGetXMLDesc(dom, 0);
2947 if (!xml) {
2948 VIRT_ERROR(conn, "virDomainGetXMLDesc");
2949 goto cont;
2950 }
2951
2952 /* Yuck, XML. Parse out the devices. */
2953 xml_doc = xmlReadDoc((xmlChar *)xml, NULL, NULL, XML_PARSE_NONET);
2954 if (xml_doc == NULL) {
2955 VIRT_ERROR(conn, "xmlReadDoc");
2956 goto cont;
2957 }
2958
2959 xpath_ctx = xmlXPathNewContext(xml_doc);
2960
2961 char tag[PARTITION_TAG_MAX_LEN] = {'\0'};
2962 if (lv_domain_get_tag(xpath_ctx, domname, tag) < 0) {
2963 ERROR(PLUGIN_NAME " plugin: lv_domain_get_tag failed.");
2964 goto cont;
2965 }
2966
2967 if (!lv_instance_include_domain(inst, domname, tag))
2968 goto cont;
2969
2970 /* Block devices. */
2971 if (report_block_devices)
2972 lv_add_block_devices(state, dom, domname, xpath_ctx);
2973
2974 /* Network interfaces. */
2975 if (report_network_interfaces)
2976 lv_add_network_interfaces(state, dom, domname, xpath_ctx);
2977
2978 cont:
2979 if (xpath_ctx)
2980 xmlXPathFreeContext(xpath_ctx);
2981 if (xml_doc)
2982 xmlFreeDoc(xml_doc);
2983 sfree(xml);
2984 }
2985
2986 #ifdef HAVE_LIST_ALL_DOMAINS
2987 /* NOTE: domains_active and domains_inactive data will be cleared during
2988 refresh of all domains (inside lv_clean_read_state function) so we need
2989 to free here only allocated arrays */
2990 sfree(domains);
2991 sfree(domains_inactive);
2992 #else
2993 sfree(domids);
2994
2995 end:
2996 #endif
2997
2998 DEBUG(PLUGIN_NAME " plugin#%s: refreshing"
2999 " domains=%i block_devices=%i iface_devices=%i",
3000 inst->tag, state->nr_domains, state->nr_block_devices,
3001 state->nr_interface_devices);
3002
3003 return 0;
3004 }
3005
free_domains(struct lv_read_state * state)3006 static void free_domains(struct lv_read_state *state) {
3007 if (state->domains) {
3008 for (int i = 0; i < state->nr_domains; ++i)
3009 virDomainFree(state->domains[i].ptr);
3010 sfree(state->domains);
3011 }
3012 state->domains = NULL;
3013 state->nr_domains = 0;
3014 }
3015
add_domain(struct lv_read_state * state,virDomainPtr dom,bool active)3016 static int add_domain(struct lv_read_state *state, virDomainPtr dom,
3017 bool active) {
3018 int new_size = sizeof(state->domains[0]) * (state->nr_domains + 1);
3019
3020 domain_t *new_ptr = realloc(state->domains, new_size);
3021 if (new_ptr == NULL) {
3022 ERROR(PLUGIN_NAME " plugin: realloc failed in add_domain()");
3023 return -1;
3024 }
3025
3026 state->domains = new_ptr;
3027 state->domains[state->nr_domains].ptr = dom;
3028 state->domains[state->nr_domains].active = active;
3029 memset(&state->domains[state->nr_domains].info, 0,
3030 sizeof(state->domains[state->nr_domains].info));
3031
3032 return state->nr_domains++;
3033 }
3034
free_block_devices(struct lv_read_state * state)3035 static void free_block_devices(struct lv_read_state *state) {
3036 if (state->block_devices) {
3037 for (int i = 0; i < state->nr_block_devices; ++i)
3038 sfree(state->block_devices[i].path);
3039 sfree(state->block_devices);
3040 }
3041 state->block_devices = NULL;
3042 state->nr_block_devices = 0;
3043 }
3044
add_block_device(struct lv_read_state * state,virDomainPtr dom,const char * path,bool has_source)3045 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
3046 const char *path, bool has_source) {
3047
3048 char *path_copy = strdup(path);
3049 if (!path_copy)
3050 return -1;
3051
3052 int new_size =
3053 sizeof(state->block_devices[0]) * (state->nr_block_devices + 1);
3054
3055 struct block_device *new_ptr = realloc(state->block_devices, new_size);
3056 if (new_ptr == NULL) {
3057 sfree(path_copy);
3058 return -1;
3059 }
3060 state->block_devices = new_ptr;
3061 state->block_devices[state->nr_block_devices].dom = dom;
3062 state->block_devices[state->nr_block_devices].path = path_copy;
3063 state->block_devices[state->nr_block_devices].has_source = has_source;
3064 return state->nr_block_devices++;
3065 }
3066
free_interface_devices(struct lv_read_state * state)3067 static void free_interface_devices(struct lv_read_state *state) {
3068 if (state->interface_devices) {
3069 for (int i = 0; i < state->nr_interface_devices; ++i) {
3070 sfree(state->interface_devices[i].path);
3071 sfree(state->interface_devices[i].address);
3072 sfree(state->interface_devices[i].number);
3073 }
3074 sfree(state->interface_devices);
3075 }
3076 state->interface_devices = NULL;
3077 state->nr_interface_devices = 0;
3078 }
3079
add_interface_device(struct lv_read_state * state,virDomainPtr dom,const char * path,const char * address,unsigned int number)3080 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
3081 const char *path, const char *address,
3082 unsigned int number) {
3083
3084 if ((path == NULL) || (address == NULL))
3085 return EINVAL;
3086
3087 char *path_copy = strdup(path);
3088 if (!path_copy)
3089 return -1;
3090
3091 char *address_copy = strdup(address);
3092 if (!address_copy) {
3093 sfree(path_copy);
3094 return -1;
3095 }
3096
3097 char number_string[21];
3098 ssnprintf(number_string, sizeof(number_string), "interface-%u", number);
3099 char *number_copy = strdup(number_string);
3100 if (!number_copy) {
3101 sfree(path_copy);
3102 sfree(address_copy);
3103 return -1;
3104 }
3105
3106 int new_size =
3107 sizeof(state->interface_devices[0]) * (state->nr_interface_devices + 1);
3108
3109 struct interface_device *new_ptr =
3110 realloc(state->interface_devices, new_size);
3111 if (new_ptr == NULL) {
3112 sfree(path_copy);
3113 sfree(address_copy);
3114 sfree(number_copy);
3115 return -1;
3116 }
3117
3118 state->interface_devices = new_ptr;
3119 state->interface_devices[state->nr_interface_devices].dom = dom;
3120 state->interface_devices[state->nr_interface_devices].path = path_copy;
3121 state->interface_devices[state->nr_interface_devices].address = address_copy;
3122 state->interface_devices[state->nr_interface_devices].number = number_copy;
3123 return state->nr_interface_devices++;
3124 }
3125
ignore_device_match(ignorelist_t * il,const char * domname,const char * devpath)3126 static int ignore_device_match(ignorelist_t *il, const char *domname,
3127 const char *devpath) {
3128 if ((domname == NULL) || (devpath == NULL))
3129 return 0;
3130
3131 size_t n = strlen(domname) + strlen(devpath) + 2;
3132 char *name = malloc(n);
3133 if (name == NULL) {
3134 ERROR(PLUGIN_NAME " plugin: malloc failed.");
3135 return 0;
3136 }
3137 ssnprintf(name, n, "%s:%s", domname, devpath);
3138 int r = ignorelist_match(il, name);
3139 sfree(name);
3140 return r;
3141 }
3142
lv_shutdown(void)3143 static int lv_shutdown(void) {
3144 for (int i = 0; i < nr_instances; ++i) {
3145 lv_fini_instance(i);
3146 }
3147
3148 if (!persistent_notification)
3149 stop_event_loop(¬if_thread);
3150
3151 lv_disconnect();
3152
3153 ignorelist_free(il_domains);
3154 il_domains = NULL;
3155 ignorelist_free(il_block_devices);
3156 il_block_devices = NULL;
3157 ignorelist_free(il_interface_devices);
3158 il_interface_devices = NULL;
3159
3160 return 0;
3161 }
3162
module_register(void)3163 void module_register(void) {
3164 plugin_register_complex_config("virt", lv_config);
3165 plugin_register_init(PLUGIN_NAME, lv_init);
3166 plugin_register_shutdown(PLUGIN_NAME, lv_shutdown);
3167 }
3168