2 * collectd - src/virt.c
3 * Copyright (C) 2006-2008 Red Hat Inc.
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.
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.
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
19 * Richard W.M. Jones <rjones@redhat.com>
20 * Przemyslaw Szczerbik <przemyslawx.szczerbik@intel.com>
26 #include "utils/common/common.h"
27 #include "utils/ignorelist/ignorelist.h"
28 #include "utils_complain.h"
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>
40 #define PLUGIN_NAME "virt"
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) \
46 size_t _l = strlen(d); \
47 sstrncpy((d) + _l, (s), (n)-_l); \
50 #ifdef LIBVIR_CHECK_VERSION
52 #if LIBVIR_CHECK_VERSION(0, 9, 2)
53 #define HAVE_DOM_REASON 1
56 #if LIBVIR_CHECK_VERSION(0, 9, 5)
57 #define HAVE_BLOCK_STATS_FLAGS 1
58 #define HAVE_DOM_REASON_PAUSED_SHUTTING_DOWN 1
61 #if LIBVIR_CHECK_VERSION(0, 9, 10)
62 #define HAVE_DISK_ERR 1
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
72 virConnectListAllDomains() appeared in 0.10.2 (Sep 2012)
73 Note that LIBVIR_CHECK_VERSION appeared a year later (Dec 2013,
75 so in some systems which actually have virConnectListAllDomains()
78 #if LIBVIR_CHECK_VERSION(0, 10, 2)
79 #define HAVE_LIST_ALL_DOMAINS 1
82 #if LIBVIR_CHECK_VERSION(1, 0, 1)
83 #define HAVE_DOM_REASON_PAUSED_SNAPSHOT 1
86 #if LIBVIR_CHECK_VERSION(1, 1, 1)
87 #define HAVE_DOM_REASON_PAUSED_CRASHED 1
90 #if LIBVIR_CHECK_VERSION(1, 2, 9)
91 #define HAVE_JOB_STATS 1
94 #if LIBVIR_CHECK_VERSION(1, 2, 10)
95 #define HAVE_DOM_REASON_CRASHED 1
98 #if LIBVIR_CHECK_VERSION(1, 2, 11)
99 #define HAVE_FS_INFO 1
102 #if LIBVIR_CHECK_VERSION(1, 2, 15)
103 #define HAVE_DOM_REASON_PAUSED_STARTING_UP 1
106 #if LIBVIR_CHECK_VERSION(1, 3, 3)
107 #define HAVE_PERF_STATS 1
108 #define HAVE_DOM_REASON_POSTCOPY 1
111 #if LIBVIR_CHECK_VERSION(4, 10, 0)
112 #define HAVE_DOM_REASON_SHUTOFF_DAEMON 1
114 #endif /* LIBVIR_CHECK_VERSION */
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*/
122 } virt_notif_thread_t;
124 /* PersistentNotification is false by default */
125 static bool persistent_notification = false;
127 static bool report_block_devices = true;
128 static bool report_network_interfaces = true;
130 /* Thread used for handling libvirt notifications events */
131 static virt_notif_thread_t notif_thread;
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",
147 static int map_domain_event_to_state(int event) {
150 case VIR_DOMAIN_EVENT_STARTED:
151 ret = VIR_DOMAIN_RUNNING;
153 case VIR_DOMAIN_EVENT_SUSPENDED:
154 ret = VIR_DOMAIN_PAUSED;
156 case VIR_DOMAIN_EVENT_RESUMED:
157 ret = VIR_DOMAIN_RUNNING;
159 case VIR_DOMAIN_EVENT_STOPPED:
160 ret = VIR_DOMAIN_SHUTOFF;
162 case VIR_DOMAIN_EVENT_SHUTDOWN:
163 ret = VIR_DOMAIN_SHUTDOWN;
165 #ifdef HAVE_DOM_STATE_PMSUSPENDED
166 case VIR_DOMAIN_EVENT_PMSUSPENDED:
167 ret = VIR_DOMAIN_PMSUSPENDED;
170 #ifdef HAVE_DOM_REASON_CRASHED
171 case VIR_DOMAIN_EVENT_CRASHED:
172 ret = VIR_DOMAIN_CRASHED;
176 ret = VIR_DOMAIN_NOSTATE;
181 #ifdef HAVE_DOM_REASON
182 static int map_domain_event_detail_to_reason(int event, int detail) {
185 case VIR_DOMAIN_EVENT_STARTED:
187 case VIR_DOMAIN_EVENT_STARTED_BOOTED: /* Normal startup from boot */
188 ret = VIR_DOMAIN_RUNNING_BOOTED;
190 case VIR_DOMAIN_EVENT_STARTED_MIGRATED: /* Incoming migration from another
192 ret = VIR_DOMAIN_RUNNING_MIGRATED;
194 case VIR_DOMAIN_EVENT_STARTED_RESTORED: /* Restored from a state file */
195 ret = VIR_DOMAIN_RUNNING_RESTORED;
197 case VIR_DOMAIN_EVENT_STARTED_FROM_SNAPSHOT: /* Restored from snapshot */
198 ret = VIR_DOMAIN_RUNNING_FROM_SNAPSHOT;
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;
206 ret = VIR_DOMAIN_RUNNING_UNKNOWN;
209 case VIR_DOMAIN_EVENT_SUSPENDED:
211 case VIR_DOMAIN_EVENT_SUSPENDED_PAUSED: /* Normal suspend due to admin
213 ret = VIR_DOMAIN_PAUSED_USER;
215 case VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED: /* Suspended for offline
217 ret = VIR_DOMAIN_PAUSED_MIGRATION;
219 case VIR_DOMAIN_EVENT_SUSPENDED_IOERROR: /* Suspended due to a disk I/O
221 ret = VIR_DOMAIN_PAUSED_IOERROR;
223 case VIR_DOMAIN_EVENT_SUSPENDED_WATCHDOG: /* Suspended due to a watchdog
225 ret = VIR_DOMAIN_PAUSED_WATCHDOG;
227 case VIR_DOMAIN_EVENT_SUSPENDED_RESTORED: /* Restored from paused state
229 ret = VIR_DOMAIN_PAUSED_UNKNOWN;
231 case VIR_DOMAIN_EVENT_SUSPENDED_FROM_SNAPSHOT: /* Restored from paused
233 ret = VIR_DOMAIN_PAUSED_FROM_SNAPSHOT;
235 case VIR_DOMAIN_EVENT_SUSPENDED_API_ERROR: /* Suspended after failure during
237 ret = VIR_DOMAIN_PAUSED_UNKNOWN;
239 #ifdef HAVE_DOM_REASON_POSTCOPY
240 case VIR_DOMAIN_EVENT_SUSPENDED_POSTCOPY: /* Suspended for post-copy
242 ret = VIR_DOMAIN_PAUSED_POSTCOPY;
244 case VIR_DOMAIN_EVENT_SUSPENDED_POSTCOPY_FAILED: /* Suspended after failed
246 ret = VIR_DOMAIN_PAUSED_POSTCOPY_FAILED;
250 ret = VIR_DOMAIN_PAUSED_UNKNOWN;
253 case VIR_DOMAIN_EVENT_RESUMED:
255 case VIR_DOMAIN_EVENT_RESUMED_UNPAUSED: /* Normal resume due to admin
257 ret = VIR_DOMAIN_RUNNING_UNPAUSED;
259 case VIR_DOMAIN_EVENT_RESUMED_MIGRATED: /* Resumed for completion of
261 ret = VIR_DOMAIN_RUNNING_MIGRATED;
263 case VIR_DOMAIN_EVENT_RESUMED_FROM_SNAPSHOT: /* Resumed from snapshot */
264 ret = VIR_DOMAIN_RUNNING_FROM_SNAPSHOT;
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;
273 ret = VIR_DOMAIN_RUNNING_UNKNOWN;
276 case VIR_DOMAIN_EVENT_STOPPED:
278 case VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN: /* Normal shutdown */
279 ret = VIR_DOMAIN_SHUTOFF_SHUTDOWN;
281 case VIR_DOMAIN_EVENT_STOPPED_DESTROYED: /* Forced poweroff from host */
282 ret = VIR_DOMAIN_SHUTOFF_DESTROYED;
284 case VIR_DOMAIN_EVENT_STOPPED_CRASHED: /* Guest crashed */
285 ret = VIR_DOMAIN_SHUTOFF_CRASHED;
287 case VIR_DOMAIN_EVENT_STOPPED_MIGRATED: /* Migrated off to another host */
288 ret = VIR_DOMAIN_SHUTOFF_MIGRATED;
290 case VIR_DOMAIN_EVENT_STOPPED_SAVED: /* Saved to a state file */
291 ret = VIR_DOMAIN_SHUTOFF_SAVED;
293 case VIR_DOMAIN_EVENT_STOPPED_FAILED: /* Host emulator/mgmt failed */
294 ret = VIR_DOMAIN_SHUTOFF_FAILED;
296 case VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT: /* Offline snapshot loaded */
297 ret = VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT;
300 ret = VIR_DOMAIN_SHUTOFF_UNKNOWN;
303 case VIR_DOMAIN_EVENT_SHUTDOWN:
305 case VIR_DOMAIN_EVENT_SHUTDOWN_FINISHED: /* Guest finished shutdown
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
317 ret = VIR_DOMAIN_SHUTDOWN_USER;
320 ret = VIR_DOMAIN_SHUTDOWN_UNKNOWN;
323 #ifdef HAVE_DOM_STATE_PMSUSPENDED
324 case VIR_DOMAIN_EVENT_PMSUSPENDED:
326 case VIR_DOMAIN_EVENT_PMSUSPENDED_MEMORY: /* Guest was PM suspended to
328 ret = VIR_DOMAIN_PMSUSPENDED_UNKNOWN;
330 case VIR_DOMAIN_EVENT_PMSUSPENDED_DISK: /* Guest was PM suspended to disk */
331 ret = VIR_DOMAIN_PMSUSPENDED_DISK_UNKNOWN;
334 ret = VIR_DOMAIN_PMSUSPENDED_UNKNOWN;
338 case VIR_DOMAIN_EVENT_CRASHED:
340 case VIR_DOMAIN_EVENT_CRASHED_PANICKED: /* Guest was panicked */
341 ret = VIR_DOMAIN_CRASHED_PANICKED;
344 ret = VIR_DOMAIN_CRASHED_UNKNOWN;
348 ret = VIR_DOMAIN_NOSTATE_UNKNOWN;
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] =
356 "the reason is unknown",
358 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_UNKNOWN] =
359 "the reason is unknown",
360 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_BOOTED] =
361 "normal startup from boot",
362 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_MIGRATED] =
363 "migrated from another host",
364 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_RESTORED] =
365 "restored from a state file",
366 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_FROM_SNAPSHOT] =
367 "restored from snapshot",
368 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_UNPAUSED] =
369 "returned from paused state",
370 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_MIGRATION_CANCELED] =
371 "returned from migration",
372 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_SAVE_CANCELED] =
373 "returned from failed save process",
374 #ifdef HAVE_DOM_REASON_RUNNING_WAKEUP
375 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_WAKEUP] =
376 "returned from pmsuspended due to wakeup event",
378 #ifdef HAVE_DOM_REASON_CRASHED
379 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_CRASHED] =
380 "resumed from crashed",
382 #ifdef HAVE_DOM_REASON_POSTCOPY
383 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_POSTCOPY] =
384 "running in post-copy migration mode",
386 [VIR_DOMAIN_BLOCKED][VIR_DOMAIN_BLOCKED_UNKNOWN] =
387 "the reason is unknown",
389 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_UNKNOWN] =
390 "the reason is unknown",
391 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_USER] = "paused on user request",
392 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_MIGRATION] =
393 "paused for offline migration",
394 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_SAVE] = "paused for save",
395 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_DUMP] =
396 "paused for offline core dump",
397 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_IOERROR] =
398 "paused due to a disk I/O error",
399 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_WATCHDOG] =
400 "paused due to a watchdog event",
401 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_FROM_SNAPSHOT] =
402 "paused after restoring from snapshot",
403 #ifdef HAVE_DOM_REASON_PAUSED_SHUTTING_DOWN
404 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_SHUTTING_DOWN] =
405 "paused during shutdown process",
407 #ifdef HAVE_DOM_REASON_PAUSED_SNAPSHOT
408 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_SNAPSHOT] =
409 "paused while creating a snapshot",
411 #ifdef HAVE_DOM_REASON_PAUSED_CRASHED
412 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_CRASHED] =
413 "paused due to a guest crash",
415 #ifdef HAVE_DOM_REASON_PAUSED_STARTING_UP
416 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_STARTING_UP] =
417 "the domain is being started",
419 #ifdef HAVE_DOM_REASON_POSTCOPY
420 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_POSTCOPY] =
421 "paused for post-copy migration",
422 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_POSTCOPY_FAILED] =
423 "paused after failed post-copy",
425 [VIR_DOMAIN_SHUTDOWN][VIR_DOMAIN_SHUTDOWN_UNKNOWN] =
426 "the reason is unknown",
427 [VIR_DOMAIN_SHUTDOWN][VIR_DOMAIN_SHUTDOWN_USER] =
428 "shutting down on user request",
430 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_UNKNOWN] =
431 "the reason is unknown",
432 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_SHUTDOWN] = "normal shutdown",
433 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_DESTROYED] = "forced poweroff",
434 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_CRASHED] = "domain crashed",
435 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_MIGRATED] =
436 "migrated to another host",
437 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_SAVED] = "saved to a file",
438 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_FAILED] =
439 "domain failed to start",
440 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT] =
441 "restored from a snapshot which was taken while domain was shutoff",
442 #ifdef HAVE_DOM_REASON_SHUTOFF_DAEMON
443 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_DAEMON] =
444 "daemon decides to kill domain during reconnection processing",
447 [VIR_DOMAIN_CRASHED][VIR_DOMAIN_CRASHED_UNKNOWN] =
448 "the reason is unknown",
449 #ifdef VIR_DOMAIN_CRASHED_PANICKED
450 [VIR_DOMAIN_CRASHED][VIR_DOMAIN_CRASHED_PANICKED] = "domain panicked",
453 #ifdef HAVE_DOM_STATE_PMSUSPENDED
454 [VIR_DOMAIN_PMSUSPENDED][VIR_DOMAIN_PMSUSPENDED_UNKNOWN] =
455 "the reason is unknown",
458 #endif /* HAVE_DOM_REASON */
460 #define NANOSEC_IN_SEC 1e9
462 #define GET_STATS(_f, _name, ...) \
464 status = _f(__VA_ARGS__); \
466 ERROR(PLUGIN_NAME " plugin: Failed to get " _name); \
470 static virConnectPtr conn;
471 static char *conn_string;
472 static c_complain_t conn_complain = C_COMPLAIN_INIT_STATIC;
474 /* Node information required for %CPU */
475 static virNodeInfo nodeinfo;
477 /* Seconds between list refreshes, 0 disables completely. */
478 static int interval = 60;
480 /* List of domains, if specified. */
481 static ignorelist_t *il_domains;
482 /* List of block devices, if specified. */
483 static ignorelist_t *il_block_devices;
484 /* List of network interface devices, if specified. */
485 static ignorelist_t *il_interface_devices;
487 static int ignore_device_match(ignorelist_t *, const char *domname,
488 const char *devpath);
490 /* Actual list of block devices found on last refresh. */
491 struct block_device {
492 virDomainPtr dom; /* domain */
493 char *path; /* name of block device */
494 bool has_source; /* information whether source is defined or not */
497 /* Actual list of network interfaces found on last refresh. */
498 struct interface_device {
499 virDomainPtr dom; /* domain */
500 char *path; /* name of interface device */
501 char *address; /* mac address of interface device */
502 char *number; /* interface device number */
505 typedef struct domain_s {
511 struct lv_read_state {
512 /* Actual list of domains found on last refresh. */
516 struct block_device *block_devices;
517 int nr_block_devices;
519 struct interface_device *interface_devices;
520 int nr_interface_devices;
523 static void free_domains(struct lv_read_state *state);
524 static int add_domain(struct lv_read_state *state, virDomainPtr dom,
527 static void free_block_devices(struct lv_read_state *state);
528 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
529 const char *path, bool has_source);
531 static void free_interface_devices(struct lv_read_state *state);
532 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
533 const char *path, const char *address,
534 unsigned int number);
536 #define METADATA_VM_PARTITION_URI "http://ovirt.org/ovirtmap/tag/1.0"
537 #define METADATA_VM_PARTITION_ELEMENT "tag"
538 #define METADATA_VM_PARTITION_PREFIX "ovirtmap"
540 #define BUFFER_MAX_LEN 256
541 #define PARTITION_TAG_MAX_LEN 32
543 struct lv_read_instance {
544 struct lv_read_state read_state;
545 char tag[PARTITION_TAG_MAX_LEN];
549 struct lv_user_data {
550 struct lv_read_instance inst;
554 #define NR_INSTANCES_DEFAULT 1
555 #define NR_INSTANCES_MAX 128
556 static int nr_instances = NR_INSTANCES_DEFAULT;
557 static struct lv_user_data lv_read_user_data[NR_INSTANCES_MAX];
559 /* HostnameFormat. */
560 #define HF_MAX_FIELDS 4
562 enum hf_field { hf_none = 0, hf_hostname, hf_name, hf_uuid, hf_metadata };
564 static enum hf_field hostname_format[HF_MAX_FIELDS] = {hf_name};
566 /* PluginInstanceFormat */
567 #define PLGINST_MAX_FIELDS 3
576 static enum plginst_field plugin_instance_format[PLGINST_MAX_FIELDS] = {
579 /* HostnameMetadataNS && HostnameMetadataXPath */
580 static char *hm_xpath;
583 /* BlockDeviceFormat */
584 enum bd_field { target, source };
586 /* InterfaceFormat. */
587 enum if_field { if_address, if_name, if_number };
590 #define EX_STATS_MAX_FIELDS 15
593 ex_stats_disk = 1 << 0,
594 ex_stats_pcpu = 1 << 1,
595 ex_stats_cpu_util = 1 << 2,
596 ex_stats_domain_state = 1 << 3,
597 #ifdef HAVE_PERF_STATS
598 ex_stats_perf = 1 << 4,
600 ex_stats_vcpupin = 1 << 5,
602 ex_stats_disk_err = 1 << 6,
605 ex_stats_fs_info = 1 << 7,
607 #ifdef HAVE_JOB_STATS
608 ex_stats_job_stats_completed = 1 << 8,
609 ex_stats_job_stats_background = 1 << 9,
611 ex_stats_disk_allocation = 1 << 10,
612 ex_stats_disk_capacity = 1 << 11,
613 ex_stats_disk_physical = 1 << 12
616 static unsigned int extra_stats = ex_stats_none;
618 struct ex_stats_item {
622 static const struct ex_stats_item ex_stats_table[] = {
623 {"disk", ex_stats_disk},
624 {"pcpu", ex_stats_pcpu},
625 {"cpu_util", ex_stats_cpu_util},
626 {"domain_state", ex_stats_domain_state},
627 #ifdef HAVE_PERF_STATS
628 {"perf", ex_stats_perf},
630 {"vcpupin", ex_stats_vcpupin},
632 {"disk_err", ex_stats_disk_err},
635 {"fs_info", ex_stats_fs_info},
637 #ifdef HAVE_JOB_STATS
638 {"job_stats_completed", ex_stats_job_stats_completed},
639 {"job_stats_background", ex_stats_job_stats_background},
641 {"disk_allocation", ex_stats_disk_allocation},
642 {"disk_capacity", ex_stats_disk_capacity},
643 {"disk_physical", ex_stats_disk_physical},
644 {NULL, ex_stats_none},
647 /* BlockDeviceFormatBasename */
648 static bool blockdevice_format_basename;
649 static enum bd_field blockdevice_format = target;
650 static enum if_field interface_format = if_name;
652 /* Time that we last refreshed. */
653 static time_t last_refresh = (time_t)0;
655 static int refresh_lists(struct lv_read_instance *inst);
656 static int register_event_impl(void);
657 static int start_event_loop(virt_notif_thread_t *thread_data);
659 struct lv_block_stats {
660 virDomainBlockStatsStruct bi;
662 long long rd_total_times;
663 long long wr_total_times;
666 long long fl_total_times;
669 static void init_block_stats(struct lv_block_stats *bstats) {
673 bstats->bi.rd_req = -1;
674 bstats->bi.wr_req = -1;
675 bstats->bi.rd_bytes = -1;
676 bstats->bi.wr_bytes = -1;
678 bstats->rd_total_times = -1;
679 bstats->wr_total_times = -1;
681 bstats->fl_total_times = -1;
684 static void init_block_info(virDomainBlockInfoPtr binfo) {
685 binfo->allocation = -1;
686 binfo->capacity = -1;
687 binfo->physical = -1;
690 #ifdef HAVE_BLOCK_STATS_FLAGS
692 #define GET_BLOCK_STATS_VALUE(NAME, FIELD) \
693 if (!strcmp(param[i].field, NAME)) { \
694 bstats->FIELD = param[i].value.l; \
698 static int get_block_stats(struct lv_block_stats *bstats,
699 virTypedParameterPtr param, int nparams) {
700 if (bstats == NULL || param == NULL)
703 for (int i = 0; i < nparams; ++i) {
704 /* ignore type. Everything must be LLONG anyway. */
705 GET_BLOCK_STATS_VALUE("rd_operations", bi.rd_req);
706 GET_BLOCK_STATS_VALUE("wr_operations", bi.wr_req);
707 GET_BLOCK_STATS_VALUE("rd_bytes", bi.rd_bytes);
708 GET_BLOCK_STATS_VALUE("wr_bytes", bi.wr_bytes);
709 GET_BLOCK_STATS_VALUE("rd_total_times", rd_total_times);
710 GET_BLOCK_STATS_VALUE("wr_total_times", wr_total_times);
711 GET_BLOCK_STATS_VALUE("flush_operations", fl_req);
712 GET_BLOCK_STATS_VALUE("flush_total_times", fl_total_times);
718 #undef GET_BLOCK_STATS_VALUE
720 #endif /* HAVE_BLOCK_STATS_FLAGS */
722 /* ERROR(...) macro for virterrors. */
723 #define VIRT_ERROR(conn, s) \
726 err = (conn) ? virConnGetLastError((conn)) : virGetLastError(); \
728 ERROR(PLUGIN_NAME " plugin: %s failed: %s", (s), err->message); \
731 static char *metadata_get_hostname(virDomainPtr dom) {
732 const char *xpath_str = NULL;
733 if (hm_xpath == NULL)
734 xpath_str = "/instance/name/text()";
736 xpath_str = hm_xpath;
738 const char *namespace = NULL;
740 namespace = "http://openstack.org/xmlns/libvirt/nova/1.0";
745 char *metadata_str = virDomainGetMetadata(
746 dom, VIR_DOMAIN_METADATA_ELEMENT, namespace, VIR_DOMAIN_AFFECT_CURRENT);
747 if (metadata_str == NULL) {
751 char *hostname = NULL;
752 xmlXPathContextPtr xpath_ctx = NULL;
753 xmlXPathObjectPtr xpath_obj = NULL;
754 xmlNodePtr xml_node = NULL;
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");
763 xpath_ctx = xmlXPathNewContext(xml_doc);
764 if (xpath_ctx == NULL) {
765 ERROR(PLUGIN_NAME " plugin: xmlXPathNewContext(%s) failed for metadata",
769 xpath_obj = xmlXPathEval((xmlChar *)xpath_str, xpath_ctx);
770 if (xpath_obj == NULL) {
771 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) failed for metadata",
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);
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",
788 (xpath_obj->nodesetval == NULL) ? 0
789 : xpath_obj->nodesetval->nodeNr);
793 xml_node = xpath_obj->nodesetval->nodeTab[0];
794 if (xml_node->type == XML_TEXT_NODE) {
795 hostname = strdup((const char *)xml_node->content);
796 } else if (xml_node->type == XML_ATTRIBUTE_NODE) {
797 hostname = strdup((const char *)xml_node->children->content);
799 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) unsupported node type %d",
800 xpath_str, xml_node->type);
804 if (hostname == NULL) {
805 ERROR(PLUGIN_NAME " plugin: strdup(%s) hostname failed", xpath_str);
811 xmlXPathFreeObject(xpath_obj);
813 xmlXPathFreeContext(xpath_ctx);
820 static void init_value_list(value_list_t *vl, virDomainPtr dom) {
822 char uuid[VIR_UUID_STRING_BUFLEN];
824 sstrncpy(vl->plugin, PLUGIN_NAME, sizeof(vl->plugin));
828 /* Construct the hostname field according to HostnameFormat. */
829 for (int i = 0; i < HF_MAX_FIELDS; ++i) {
830 if (hostname_format[i] == hf_none)
834 SSTRNCAT(vl->host, ":", sizeof(vl->host));
836 switch (hostname_format[i]) {
840 SSTRNCAT(vl->host, hostname_g, sizeof(vl->host));
843 name = virDomainGetName(dom);
845 SSTRNCAT(vl->host, name, sizeof(vl->host));
848 if (virDomainGetUUIDString(dom, uuid) == 0)
849 SSTRNCAT(vl->host, uuid, sizeof(vl->host));
852 name = metadata_get_hostname(dom);
854 SSTRNCAT(vl->host, name, sizeof(vl->host));
859 /* Construct the plugin instance field according to PluginInstanceFormat. */
860 for (int i = 0; i < PLGINST_MAX_FIELDS; ++i) {
861 if (plugin_instance_format[i] == plginst_none)
865 SSTRNCAT(vl->plugin_instance, ":", sizeof(vl->plugin_instance));
867 switch (plugin_instance_format[i]) {
871 name = virDomainGetName(dom);
873 SSTRNCAT(vl->plugin_instance, name, sizeof(vl->plugin_instance));
876 if (virDomainGetUUIDString(dom, uuid) == 0)
877 SSTRNCAT(vl->plugin_instance, uuid, sizeof(vl->plugin_instance));
879 case plginst_metadata:
880 name = metadata_get_hostname(dom);
882 SSTRNCAT(vl->plugin_instance, name, sizeof(vl->plugin_instance));
887 } /* void init_value_list */
889 static int init_notif(notification_t *notif, const virDomainPtr domain,
890 int severity, const char *msg, const char *type,
891 const char *type_instance) {
892 value_list_t vl = VALUE_LIST_INIT;
895 ERROR(PLUGIN_NAME " plugin: init_notif: NULL pointer");
899 init_value_list(&vl, domain);
900 notification_init(notif, severity, msg, vl.host, vl.plugin,
901 vl.plugin_instance, type, type_instance);
902 notif->time = cdtime();
906 static void submit_notif(const virDomainPtr domain, int severity,
907 const char *msg, const char *type,
908 const char *type_instance) {
909 notification_t notif;
911 init_notif(¬if, domain, severity, msg, type, type_instance);
912 plugin_dispatch_notification(¬if);
914 plugin_notification_meta_free(notif.meta);
917 static void submit(virDomainPtr dom, char const *type,
918 char const *type_instance, value_t *values,
920 value_list_t vl = VALUE_LIST_INIT;
921 init_value_list(&vl, dom);
924 vl.values_len = values_len;
926 sstrncpy(vl.type, type, sizeof(vl.type));
927 if (type_instance != NULL)
928 sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
930 plugin_dispatch_values(&vl);
933 static void memory_submit(virDomainPtr dom, gauge_t value) {
934 submit(dom, "memory", "total", &(value_t){.gauge = value}, 1);
937 static void memory_stats_submit(gauge_t value, virDomainPtr dom,
939 static const char *tags[] = {"swap_in", "swap_out", "major_fault",
940 "minor_fault", "unused", "available",
941 "actual_balloon", "rss", "usable",
942 "last_update", "disk_caches"};
944 if ((tag_index < 0) || (tag_index >= (int)STATIC_ARRAY_SIZE(tags))) {
945 ERROR("virt plugin: Array index out of bounds: tag_index = %d", tag_index);
949 submit(dom, "memory", tags[tag_index], &(value_t){.gauge = value}, 1);
952 static void submit_derive2(const char *type, derive_t v0, derive_t v1,
953 virDomainPtr dom, const char *devname) {
955 {.derive = v0}, {.derive = v1},
958 submit(dom, type, devname, values, STATIC_ARRAY_SIZE(values));
959 } /* void submit_derive2 */
961 static double cpu_ns_to_percent(unsigned int node_cpus,
962 unsigned long long cpu_time_old,
963 unsigned long long cpu_time_new) {
964 double percent = 0.0;
965 unsigned long long cpu_time_diff = 0;
966 double time_diff_sec = CDTIME_T_TO_DOUBLE(plugin_get_interval());
968 if (node_cpus != 0 && time_diff_sec != 0 && cpu_time_old != 0) {
969 cpu_time_diff = cpu_time_new - cpu_time_old;
970 percent = ((double)(100 * cpu_time_diff)) /
971 (time_diff_sec * node_cpus * NANOSEC_IN_SEC);
974 DEBUG(PLUGIN_NAME " plugin: node_cpus=%u cpu_time_old=%" PRIu64
975 " cpu_time_new=%" PRIu64 "cpu_time_diff=%" PRIu64
976 " time_diff_sec=%f percent=%f",
977 node_cpus, (uint64_t)cpu_time_old, (uint64_t)cpu_time_new,
978 (uint64_t)cpu_time_diff, time_diff_sec, percent);
983 static void cpu_submit(const domain_t *dom, unsigned long long cpuTime_new) {
988 if (extra_stats & ex_stats_cpu_util) {
989 /* Computing %CPU requires 2 samples of cpuTime */
990 if (dom->info.cpuTime != 0 && cpuTime_new != 0) {
992 submit(dom->ptr, "percent", "virt_cpu_total",
993 &(value_t){.gauge = cpu_ns_to_percent(
994 nodeinfo.cpus, dom->info.cpuTime, cpuTime_new)},
999 submit(dom->ptr, "virt_cpu_total", NULL, &(value_t){.derive = cpuTime_new},
1003 static void vcpu_submit(derive_t value, virDomainPtr dom, int vcpu_nr,
1005 char type_instance[DATA_MAX_NAME_LEN];
1007 snprintf(type_instance, sizeof(type_instance), "%d", vcpu_nr);
1008 submit(dom, type, type_instance, &(value_t){.derive = value}, 1);
1011 static void disk_block_stats_submit(struct lv_block_stats *bstats,
1012 virDomainPtr dom, const char *dev,
1013 virDomainBlockInfoPtr binfo) {
1014 char *dev_copy = strdup(dev);
1015 const char *type_instance = dev_copy;
1020 if (blockdevice_format_basename && blockdevice_format == source)
1021 type_instance = basename(dev_copy);
1023 if (!type_instance) {
1028 char flush_type_instance[DATA_MAX_NAME_LEN];
1029 snprintf(flush_type_instance, sizeof(flush_type_instance), "flush-%s",
1032 if ((bstats->bi.rd_req != -1) && (bstats->bi.wr_req != -1))
1033 submit_derive2("disk_ops", (derive_t)bstats->bi.rd_req,
1034 (derive_t)bstats->bi.wr_req, dom, type_instance);
1036 if ((bstats->bi.rd_bytes != -1) && (bstats->bi.wr_bytes != -1))
1037 submit_derive2("disk_octets", (derive_t)bstats->bi.rd_bytes,
1038 (derive_t)bstats->bi.wr_bytes, dom, type_instance);
1040 if (extra_stats & ex_stats_disk) {
1041 if ((bstats->rd_total_times != -1) && (bstats->wr_total_times != -1))
1042 submit_derive2("disk_time", (derive_t)bstats->rd_total_times,
1043 (derive_t)bstats->wr_total_times, dom, type_instance);
1045 if (bstats->fl_req != -1)
1046 submit(dom, "total_requests", flush_type_instance,
1047 &(value_t){.derive = (derive_t)bstats->fl_req}, 1);
1048 if (bstats->fl_total_times != -1) {
1049 derive_t value = bstats->fl_total_times / 1000; // ns -> ms
1050 submit(dom, "total_time_in_ms", flush_type_instance,
1051 &(value_t){.derive = value}, 1);
1055 /* disk_allocation, disk_capacity and disk_physical are stored only
1056 * if corresponding extrastats are set in collectd configuration file */
1057 if ((extra_stats & ex_stats_disk_allocation) && binfo->allocation != -1)
1058 submit(dom, "disk_allocation", type_instance,
1059 &(value_t){.gauge = (gauge_t)binfo->allocation}, 1);
1061 if ((extra_stats & ex_stats_disk_capacity) && binfo->capacity != -1)
1062 submit(dom, "disk_capacity", type_instance,
1063 &(value_t){.gauge = (gauge_t)binfo->capacity}, 1);
1065 if ((extra_stats & ex_stats_disk_physical) && binfo->physical != -1)
1066 submit(dom, "disk_physical", type_instance,
1067 &(value_t){.gauge = (gauge_t)binfo->physical}, 1);
1073 * Function for parsing ExtraStats configuration options.
1074 * Result of parsing is stored under 'out_parsed_flags' pointer.
1076 * Returns 0 in case of success and 1 in case of parsing error
1078 static int parse_ex_stats_flags(unsigned int *out_parsed_flags, char **exstats,
1080 unsigned int ex_stats_flags = ex_stats_none;
1082 assert(out_parsed_flags != NULL);
1084 for (int i = 0; i < numexstats; i++) {
1085 for (int j = 0; ex_stats_table[j].name != NULL; j++) {
1086 if (strcasecmp(exstats[i], ex_stats_table[j].name) == 0) {
1087 DEBUG(PLUGIN_NAME " plugin: enabling extra stats for '%s'",
1088 ex_stats_table[j].name);
1089 ex_stats_flags |= ex_stats_table[j].flag;
1093 if (ex_stats_table[j + 1].name == NULL) {
1094 ERROR(PLUGIN_NAME " plugin: Unmatched ExtraStats option: %s",
1101 *out_parsed_flags = ex_stats_flags;
1105 static void domain_state_submit_notif(virDomainPtr dom, int state, int reason) {
1106 if ((state < 0) || ((size_t)state >= STATIC_ARRAY_SIZE(domain_states))) {
1107 ERROR(PLUGIN_NAME " plugin: Array index out of bounds: state=%d", state);
1111 char msg[DATA_MAX_NAME_LEN];
1112 const char *state_str = domain_states[state];
1113 #ifdef HAVE_DOM_REASON
1115 ((size_t)reason >= STATIC_ARRAY_SIZE(domain_reasons[0]))) {
1116 ERROR(PLUGIN_NAME " plugin: Array index out of bounds: reason=%d", reason);
1120 const char *reason_str = domain_reasons[state][reason];
1121 /* Array size for domain reasons is fixed, but different domain states can
1122 * have different number of reasons. We need to check if reason was
1123 * successfully parsed */
1125 ERROR(PLUGIN_NAME " plugin: Invalid reason (%d) for domain state: %s",
1130 const char *reason_str = "N/A";
1133 snprintf(msg, sizeof(msg), "Domain state: %s. Reason: %s", state_str,
1138 case VIR_DOMAIN_NOSTATE:
1139 case VIR_DOMAIN_RUNNING:
1140 case VIR_DOMAIN_SHUTDOWN:
1141 case VIR_DOMAIN_SHUTOFF:
1142 severity = NOTIF_OKAY;
1144 case VIR_DOMAIN_BLOCKED:
1145 case VIR_DOMAIN_PAUSED:
1146 #ifdef DOM_STATE_PMSUSPENDED
1147 case VIR_DOMAIN_PMSUSPENDED:
1149 severity = NOTIF_WARNING;
1151 case VIR_DOMAIN_CRASHED:
1152 severity = NOTIF_FAILURE;
1155 ERROR(PLUGIN_NAME " plugin: Unrecognized domain state (%d)", state);
1158 submit_notif(dom, severity, msg, "domain_state", NULL);
1161 static int lv_init_ignorelists() {
1162 if (il_domains == NULL)
1163 il_domains = ignorelist_create(1);
1164 if (il_block_devices == NULL)
1165 il_block_devices = ignorelist_create(1);
1166 if (il_interface_devices == NULL)
1167 il_interface_devices = ignorelist_create(1);
1169 if (!il_domains || !il_block_devices || !il_interface_devices)
1175 /* Validates config option that may take multiple strings arguments.
1176 * Returns 0 on success, -1 otherwise */
1177 static int check_config_multiple_string_entry(const oconfig_item_t *ci) {
1179 ERROR(PLUGIN_NAME " plugin: ci oconfig_item can't be NULL");
1183 if (ci->values_num < 1) {
1185 " plugin: the '%s' option requires at least one string argument",
1190 for (int i = 0; i < ci->values_num; ++i) {
1191 if (ci->values[i].type != OCONFIG_TYPE_STRING) {
1193 " plugin: one of the '%s' options is not a valid string",
1202 static int lv_config(oconfig_item_t *ci) {
1203 if (lv_init_ignorelists() != 0) {
1204 ERROR(PLUGIN_NAME " plugin: lv_init_ignorelist failed.");
1208 for (int i = 0; i < ci->children_num; ++i) {
1209 oconfig_item_t *c = ci->children + i;
1211 if (strcasecmp(c->key, "Connection") == 0) {
1212 if (cf_util_get_string(c, &conn_string) != 0 || conn_string == NULL)
1216 } else if (strcasecmp(c->key, "RefreshInterval") == 0) {
1217 if (cf_util_get_int(c, &interval) != 0)
1221 } else if (strcasecmp(c->key, "Domain") == 0) {
1222 char *domain_name = NULL;
1223 if (cf_util_get_string(c, &domain_name) != 0)
1226 if (ignorelist_add(il_domains, domain_name)) {
1227 ERROR(PLUGIN_NAME " plugin: Adding '%s' to domain-ignorelist failed",
1235 } else if (strcasecmp(c->key, "BlockDevice") == 0) {
1236 char *device_name = NULL;
1237 if (cf_util_get_string(c, &device_name) != 0)
1240 if (ignorelist_add(il_block_devices, device_name) != 0) {
1242 " plugin: Adding '%s' to block-device-ignorelist failed",
1250 } else if (strcasecmp(c->key, "BlockDeviceFormat") == 0) {
1251 char *device_format = NULL;
1252 if (cf_util_get_string(c, &device_format) != 0)
1255 if (strcasecmp(device_format, "target") == 0)
1256 blockdevice_format = target;
1257 else if (strcasecmp(device_format, "source") == 0)
1258 blockdevice_format = source;
1260 ERROR(PLUGIN_NAME " plugin: unknown BlockDeviceFormat: %s",
1262 sfree(device_format);
1266 sfree(device_format);
1268 } else if (strcasecmp(c->key, "BlockDeviceFormatBasename") == 0) {
1269 if (cf_util_get_boolean(c, &blockdevice_format_basename) != 0)
1273 } else if (strcasecmp(c->key, "InterfaceDevice") == 0) {
1274 char *interface_name = NULL;
1275 if (cf_util_get_string(c, &interface_name) != 0)
1278 if (ignorelist_add(il_interface_devices, interface_name)) {
1279 ERROR(PLUGIN_NAME " plugin: Adding '%s' to interface-ignorelist failed",
1281 sfree(interface_name);
1285 sfree(interface_name);
1287 } else if (strcasecmp(c->key, "IgnoreSelected") == 0) {
1288 bool ignore_selected = false;
1289 if (cf_util_get_boolean(c, &ignore_selected) != 0)
1292 if (ignore_selected) {
1293 ignorelist_set_invert(il_domains, 0);
1294 ignorelist_set_invert(il_block_devices, 0);
1295 ignorelist_set_invert(il_interface_devices, 0);
1297 ignorelist_set_invert(il_domains, 1);
1298 ignorelist_set_invert(il_block_devices, 1);
1299 ignorelist_set_invert(il_interface_devices, 1);
1303 } else if (strcasecmp(c->key, "HostnameMetadataNS") == 0) {
1304 if (cf_util_get_string(c, &hm_ns) != 0)
1308 } else if (strcasecmp(c->key, "HostnameMetadataXPath") == 0) {
1309 if (cf_util_get_string(c, &hm_xpath) != 0)
1313 } else if (strcasecmp(c->key, "HostnameFormat") == 0) {
1314 /* this option can take multiple strings arguments in one config line*/
1315 if (check_config_multiple_string_entry(c) != 0) {
1316 ERROR(PLUGIN_NAME " plugin: Could not get 'HostnameFormat' parameter");
1320 const int params_num = c->values_num;
1321 for (int i = 0; i < params_num; ++i) {
1322 const char *param_name = c->values[i].value.string;
1323 if (strcasecmp(param_name, "hostname") == 0)
1324 hostname_format[i] = hf_hostname;
1325 else if (strcasecmp(param_name, "name") == 0)
1326 hostname_format[i] = hf_name;
1327 else if (strcasecmp(param_name, "uuid") == 0)
1328 hostname_format[i] = hf_uuid;
1329 else if (strcasecmp(param_name, "metadata") == 0)
1330 hostname_format[i] = hf_metadata;
1332 ERROR(PLUGIN_NAME " plugin: unknown HostnameFormat field: %s",
1338 for (int i = params_num; i < HF_MAX_FIELDS; ++i)
1339 hostname_format[i] = hf_none;
1342 } else if (strcasecmp(c->key, "PluginInstanceFormat") == 0) {
1343 /* this option can handle list of string parameters in one line*/
1344 if (check_config_multiple_string_entry(c) != 0) {
1346 " plugin: Could not get 'PluginInstanceFormat' parameter");
1350 const int params_num = c->values_num;
1351 for (int i = 0; i < params_num; ++i) {
1352 const char *param_name = c->values[i].value.string;
1353 if (strcasecmp(param_name, "none") == 0) {
1354 plugin_instance_format[i] = plginst_none;
1356 } else if (strcasecmp(param_name, "name") == 0)
1357 plugin_instance_format[i] = plginst_name;
1358 else if (strcasecmp(param_name, "uuid") == 0)
1359 plugin_instance_format[i] = plginst_uuid;
1360 else if (strcasecmp(param_name, "metadata") == 0)
1361 plugin_instance_format[i] = plginst_metadata;
1363 ERROR(PLUGIN_NAME " plugin: unknown PluginInstanceFormat field: %s",
1370 for (int i = params_num; i < PLGINST_MAX_FIELDS; ++i)
1371 plugin_instance_format[i] = plginst_none;
1374 } else if (strcasecmp(c->key, "InterfaceFormat") == 0) {
1375 char *format = NULL;
1376 if (cf_util_get_string(c, &format) != 0)
1379 if (strcasecmp(format, "name") == 0)
1380 interface_format = if_name;
1381 else if (strcasecmp(format, "address") == 0)
1382 interface_format = if_address;
1383 else if (strcasecmp(format, "number") == 0)
1384 interface_format = if_number;
1386 ERROR(PLUGIN_NAME " plugin: unknown InterfaceFormat: %s", format);
1393 } else if (strcasecmp(c->key, "Instances") == 0) {
1394 if (cf_util_get_int(c, &nr_instances) != 0)
1397 if (nr_instances <= 0) {
1398 ERROR(PLUGIN_NAME " plugin: Instances <= 0 makes no sense.");
1401 if (nr_instances > NR_INSTANCES_MAX) {
1402 ERROR(PLUGIN_NAME " plugin: Instances=%i > NR_INSTANCES_MAX=%i"
1403 " use a lower setting or recompile the plugin.",
1404 nr_instances, NR_INSTANCES_MAX);
1408 DEBUG(PLUGIN_NAME " plugin: configured %i instances", nr_instances);
1410 } else if (strcasecmp(c->key, "ExtraStats") == 0) {
1411 char *ex_str = NULL;
1413 if (cf_util_get_string(c, &ex_str) != 0)
1416 char *exstats[EX_STATS_MAX_FIELDS];
1417 int numexstats = strsplit(ex_str, exstats, STATIC_ARRAY_SIZE(exstats));
1418 int status = parse_ex_stats_flags(&extra_stats, exstats, numexstats);
1421 ERROR(PLUGIN_NAME " plugin: parsing 'ExtraStats' option failed");
1425 #ifdef HAVE_JOB_STATS
1426 if ((extra_stats & ex_stats_job_stats_completed) &&
1427 (extra_stats & ex_stats_job_stats_background)) {
1428 ERROR(PLUGIN_NAME " plugin: Invalid job stats configuration. Only one "
1429 "type of job statistics can be collected at the same "
1435 /* ExtraStats parsed successfully */
1437 } else if (strcasecmp(c->key, "PersistentNotification") == 0) {
1438 if (cf_util_get_boolean(c, &persistent_notification) != 0)
1442 } else if (strcasecmp(c->key, "ReportBlockDevices") == 0) {
1443 if (cf_util_get_boolean(c, &report_block_devices) != 0)
1447 } else if (strcasecmp(c->key, "ReportNetworkInterfaces") == 0) {
1448 if (cf_util_get_boolean(c, &report_network_interfaces) != 0)
1453 /* Unrecognised option. */
1454 ERROR(PLUGIN_NAME " plugin: Unrecognized option: '%s'", c->key);
1462 static int lv_connect(void) {
1464 /* event implementation must be registered before connection is opened */
1465 if (!persistent_notification)
1466 if (register_event_impl() != 0)
1469 /* `conn_string == NULL' is acceptable */
1471 /* virDomainGetFSInfo requires full read-write access connection */
1472 if (extra_stats & ex_stats_fs_info)
1473 conn = virConnectOpen(conn_string);
1476 conn = virConnectOpenReadOnly(conn_string);
1478 c_complain(LOG_ERR, &conn_complain,
1479 PLUGIN_NAME " plugin: Unable to connect: "
1480 "virConnectOpen failed.");
1483 int status = virNodeGetInfo(conn, &nodeinfo);
1485 ERROR(PLUGIN_NAME " plugin: virNodeGetInfo failed");
1486 virConnectClose(conn);
1491 if (!persistent_notification)
1492 if (start_event_loop(¬if_thread) != 0) {
1493 virConnectClose(conn);
1498 c_release(LOG_NOTICE, &conn_complain,
1499 PLUGIN_NAME " plugin: Connection established.");
1503 static void lv_disconnect(void) {
1505 virConnectClose(conn);
1507 WARNING(PLUGIN_NAME " plugin: closed connection to libvirt");
1510 static int lv_domain_block_stats(virDomainPtr dom, const char *path,
1511 struct lv_block_stats *bstats) {
1512 #ifdef HAVE_BLOCK_STATS_FLAGS
1514 if (virDomainBlockStatsFlags(dom, path, NULL, &nparams, 0) < 0 ||
1516 VIRT_ERROR(conn, "getting the disk params count");
1520 virTypedParameterPtr params = calloc(nparams, sizeof(*params));
1521 if (params == NULL) {
1522 ERROR("virt plugin: alloc(%i) for block=%s parameters failed.", nparams,
1528 if (virDomainBlockStatsFlags(dom, path, params, &nparams, 0) < 0) {
1529 VIRT_ERROR(conn, "getting the disk params values");
1531 rc = get_block_stats(bstats, params, nparams);
1534 virTypedParamsClear(params, nparams);
1538 return virDomainBlockStats(dom, path, &(bstats->bi), sizeof(bstats->bi));
1539 #endif /* HAVE_BLOCK_STATS_FLAGS */
1542 #ifdef HAVE_PERF_STATS
1543 static void perf_submit(virDomainStatsRecordPtr stats) {
1544 for (int i = 0; i < stats->nparams; ++i) {
1545 /* Replace '.' with '_' in event field to match other metrics' naming
1547 char *c = strchr(stats->params[i].field, '.');
1550 submit(stats->dom, "perf", stats->params[i].field,
1551 &(value_t){.derive = stats->params[i].value.ul}, 1);
1555 static int get_perf_events(virDomainPtr domain) {
1556 virDomainStatsRecordPtr *stats = NULL;
1557 /* virDomainListGetStats requires a NULL terminated list of domains */
1558 virDomainPtr domain_array[] = {domain, NULL};
1561 virDomainListGetStats(domain_array, VIR_DOMAIN_STATS_PERF, &stats, 0);
1563 ERROR("virt plugin: virDomainListGetStats failed with status %i.", status);
1567 for (int i = 0; i < status; ++i)
1568 perf_submit(stats[i]);
1570 virDomainStatsRecordListFree(stats);
1573 #endif /* HAVE_PERF_STATS */
1575 static void vcpu_pin_submit(virDomainPtr dom, int max_cpus, int vcpu,
1576 unsigned char *cpu_maps, int cpu_map_len) {
1577 for (int cpu = 0; cpu < max_cpus; ++cpu) {
1578 char type_instance[DATA_MAX_NAME_LEN];
1579 bool is_set = VIR_CPU_USABLE(cpu_maps, cpu_map_len, vcpu, cpu);
1581 snprintf(type_instance, sizeof(type_instance), "vcpu_%d-cpu_%d", vcpu, cpu);
1582 submit(dom, "cpu_affinity", type_instance, &(value_t){.gauge = is_set}, 1);
1586 static int get_vcpu_stats(virDomainPtr domain, unsigned short nr_virt_cpu) {
1587 int max_cpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
1588 int cpu_map_len = VIR_CPU_MAPLEN(max_cpus);
1590 virVcpuInfoPtr vinfo = calloc(nr_virt_cpu, sizeof(*vinfo));
1591 if (vinfo == NULL) {
1592 ERROR(PLUGIN_NAME " plugin: calloc failed.");
1596 unsigned char *cpumaps = calloc(nr_virt_cpu, cpu_map_len);
1597 if (cpumaps == NULL) {
1598 ERROR(PLUGIN_NAME " plugin: calloc failed.");
1604 virDomainGetVcpus(domain, vinfo, nr_virt_cpu, cpumaps, cpu_map_len);
1606 ERROR(PLUGIN_NAME " plugin: virDomainGetVcpus failed with status %i.",
1613 for (int i = 0; i < nr_virt_cpu; ++i) {
1614 vcpu_submit(vinfo[i].cpuTime, domain, vinfo[i].number, "virt_vcpu");
1615 if (extra_stats & ex_stats_vcpupin)
1616 vcpu_pin_submit(domain, max_cpus, i, cpumaps, cpu_map_len);
1624 #ifdef HAVE_CPU_STATS
1625 static int get_pcpu_stats(virDomainPtr dom) {
1626 int nparams = virDomainGetCPUStats(dom, NULL, 0, -1, 1, 0);
1628 VIRT_ERROR(conn, "getting the CPU params count");
1632 virTypedParameterPtr param = calloc(nparams, sizeof(*param));
1633 if (param == NULL) {
1634 ERROR(PLUGIN_NAME " plugin: alloc(%i) for cpu parameters failed.", nparams);
1638 int ret = virDomainGetCPUStats(dom, param, nparams, -1, 1, 0); // total stats.
1640 virTypedParamsClear(param, nparams);
1642 VIRT_ERROR(conn, "getting the CPU params values");
1646 unsigned long long total_user_cpu_time = 0;
1647 unsigned long long total_syst_cpu_time = 0;
1649 for (int i = 0; i < nparams; ++i) {
1650 if (!strcmp(param[i].field, "user_time"))
1651 total_user_cpu_time = param[i].value.ul;
1652 else if (!strcmp(param[i].field, "system_time"))
1653 total_syst_cpu_time = param[i].value.ul;
1656 if (total_user_cpu_time > 0 || total_syst_cpu_time > 0)
1657 submit_derive2("ps_cputime", total_user_cpu_time, total_syst_cpu_time, dom,
1660 virTypedParamsClear(param, nparams);
1665 #endif /* HAVE_CPU_STATS */
1667 #ifdef HAVE_DOM_REASON
1669 static void domain_state_submit(virDomainPtr dom, int state, int reason) {
1670 value_t values[] = {
1671 {.gauge = (gauge_t)state}, {.gauge = (gauge_t)reason},
1674 submit(dom, "domain_state", NULL, values, STATIC_ARRAY_SIZE(values));
1677 static int get_domain_state(virDomainPtr domain) {
1678 int domain_state = 0;
1679 int domain_reason = 0;
1681 int status = virDomainGetState(domain, &domain_state, &domain_reason, 0);
1683 ERROR(PLUGIN_NAME " plugin: virDomainGetState failed with status %i.",
1688 domain_state_submit(domain, domain_state, domain_reason);
1693 #ifdef HAVE_LIST_ALL_DOMAINS
1694 static int get_domain_state_notify(virDomainPtr domain) {
1695 int domain_state = 0;
1696 int domain_reason = 0;
1698 int status = virDomainGetState(domain, &domain_state, &domain_reason, 0);
1700 ERROR(PLUGIN_NAME " plugin: virDomainGetState failed with status %i.",
1705 if (persistent_notification)
1706 domain_state_submit_notif(domain, domain_state, domain_reason);
1710 #endif /* HAVE_LIST_ALL_DOMAINS */
1711 #endif /* HAVE_DOM_REASON */
1713 static int get_memory_stats(virDomainPtr domain) {
1714 virDomainMemoryStatPtr minfo =
1715 calloc(VIR_DOMAIN_MEMORY_STAT_NR, sizeof(*minfo));
1716 if (minfo == NULL) {
1717 ERROR("virt plugin: calloc failed.");
1722 virDomainMemoryStats(domain, minfo, VIR_DOMAIN_MEMORY_STAT_NR, 0);
1723 if (mem_stats < 0) {
1724 ERROR("virt plugin: virDomainMemoryStats failed with mem_stats %i.",
1730 derive_t swap_in = -1;
1731 derive_t swap_out = -1;
1732 derive_t min_flt = -1;
1733 derive_t maj_flt = -1;
1735 for (int i = 0; i < mem_stats; i++) {
1736 if (minfo[i].tag == VIR_DOMAIN_MEMORY_STAT_SWAP_IN)
1737 swap_in = minfo[i].val;
1738 else if (minfo[i].tag == VIR_DOMAIN_MEMORY_STAT_SWAP_OUT)
1739 swap_out = minfo[i].val;
1740 else if (minfo[i].tag == VIR_DOMAIN_MEMORY_STAT_MAJOR_FAULT)
1741 min_flt = minfo[i].val;
1742 else if (minfo[i].tag == VIR_DOMAIN_MEMORY_STAT_MINOR_FAULT)
1743 maj_flt = minfo[i].val;
1744 #ifdef LIBVIR_CHECK_VERSION
1745 #if LIBVIR_CHECK_VERSION(2, 1, 0)
1746 else if (minfo[i].tag == VIR_DOMAIN_MEMORY_STAT_LAST_UPDATE)
1747 /* Skip 'last_update' reporting as that is not memory but timestamp */
1752 memory_stats_submit((gauge_t)minfo[i].val * 1024, domain, minfo[i].tag);
1755 if (swap_in > 0 || swap_out > 0) {
1756 submit(domain, "swap_io", "in", &(value_t){.gauge = swap_in}, 1);
1757 submit(domain, "swap_io", "out", &(value_t){.gauge = swap_out}, 1);
1760 if (min_flt > 0 || maj_flt > 0) {
1761 value_t values[] = {
1762 {.gauge = (gauge_t)min_flt}, {.gauge = (gauge_t)maj_flt},
1764 submit(domain, "ps_pagefaults", NULL, values, STATIC_ARRAY_SIZE(values));
1771 #ifdef HAVE_DISK_ERR
1772 static void disk_err_submit(virDomainPtr domain,
1773 virDomainDiskErrorPtr disk_err) {
1774 submit(domain, "disk_error", disk_err->disk,
1775 &(value_t){.gauge = disk_err->error}, 1);
1778 static int get_disk_err(virDomainPtr domain) {
1779 /* Get preferred size of disk errors array */
1780 int disk_err_count = virDomainGetDiskErrors(domain, NULL, 0, 0);
1781 if (disk_err_count == -1) {
1783 " plugin: failed to get preferred size of disk errors array");
1788 " plugin: preferred size of disk errors array: %d for domain %s",
1789 disk_err_count, virDomainGetName(domain));
1790 virDomainDiskError disk_err[disk_err_count];
1792 disk_err_count = virDomainGetDiskErrors(domain, disk_err, disk_err_count, 0);
1793 if (disk_err_count == -1) {
1794 ERROR(PLUGIN_NAME " plugin: virDomainGetDiskErrors failed with status %d",
1799 DEBUG(PLUGIN_NAME " plugin: detected %d disk errors in domain %s",
1800 disk_err_count, virDomainGetName(domain));
1802 for (int i = 0; i < disk_err_count; ++i) {
1803 disk_err_submit(domain, &disk_err[i]);
1804 sfree(disk_err[i].disk);
1809 #endif /* HAVE_DISK_ERR */
1811 static int get_block_device_stats(struct block_device *block_dev) {
1813 ERROR(PLUGIN_NAME " plugin: get_block_stats NULL pointer");
1817 virDomainBlockInfo binfo;
1818 init_block_info(&binfo);
1820 /* Fetching block info stats only if needed*/
1821 if (extra_stats & (ex_stats_disk_allocation | ex_stats_disk_capacity |
1822 ex_stats_disk_physical)) {
1823 /* Block info statistics can be only fetched from devices with 'source'
1825 if (block_dev->has_source) {
1826 if (virDomainGetBlockInfo(block_dev->dom, block_dev->path, &binfo, 0) <
1828 ERROR(PLUGIN_NAME " plugin: virDomainGetBlockInfo failed for path: %s",
1835 struct lv_block_stats bstats;
1836 init_block_stats(&bstats);
1838 if (lv_domain_block_stats(block_dev->dom, block_dev->path, &bstats) < 0) {
1839 ERROR(PLUGIN_NAME " plugin: lv_domain_block_stats failed");
1843 disk_block_stats_submit(&bstats, block_dev->dom, block_dev->path, &binfo);
1849 #define NM_ADD_ITEM(_fun, _name, _val) \
1851 ret = _fun(¬if, _name, _val); \
1853 ERROR(PLUGIN_NAME " plugin: failed to add notification metadata"); \
1858 #define NM_ADD_STR_ITEMS(_items, _size) \
1860 for (size_t _i = 0; _i < _size; ++_i) { \
1862 " plugin: Adding notification metadata name=%s value=%s", \
1863 _items[_i].name, _items[_i].value); \
1864 NM_ADD_ITEM(plugin_notification_meta_add_string, _items[_i].name, \
1865 _items[_i].value); \
1869 static int fs_info_notify(virDomainPtr domain, virDomainFSInfoPtr fs_info) {
1870 notification_t notif;
1873 /* Local struct, just for the purpose of this function. */
1874 typedef struct nm_str_item_s {
1879 nm_str_item_t fs_dev_alias[fs_info->ndevAlias];
1880 nm_str_item_t fs_str_items[] = {
1881 {.name = "mountpoint", .value = fs_info->mountpoint},
1882 {.name = "name", .value = fs_info->name},
1883 {.name = "fstype", .value = fs_info->fstype}};
1885 for (size_t i = 0; i < fs_info->ndevAlias; ++i) {
1886 fs_dev_alias[i].name = "devAlias";
1887 fs_dev_alias[i].value = fs_info->devAlias[i];
1890 init_notif(¬if, domain, NOTIF_OKAY, "File system information",
1891 "file_system", NULL);
1892 NM_ADD_STR_ITEMS(fs_str_items, STATIC_ARRAY_SIZE(fs_str_items));
1893 NM_ADD_ITEM(plugin_notification_meta_add_unsigned_int, "ndevAlias",
1894 fs_info->ndevAlias);
1895 NM_ADD_STR_ITEMS(fs_dev_alias, fs_info->ndevAlias);
1897 plugin_dispatch_notification(¬if);
1901 plugin_notification_meta_free(notif.meta);
1905 #undef RETURN_ON_ERR
1906 #undef NM_ADD_STR_ITEMS
1908 static int get_fs_info(virDomainPtr domain) {
1909 virDomainFSInfoPtr *fs_info = NULL;
1912 int mount_points_cnt = virDomainGetFSInfo(domain, &fs_info, 0);
1913 if (mount_points_cnt == -1) {
1914 ERROR(PLUGIN_NAME " plugin: virDomainGetFSInfo failed: %d",
1916 return mount_points_cnt;
1919 for (int i = 0; i < mount_points_cnt; ++i) {
1920 if (fs_info_notify(domain, fs_info[i]) != 0) {
1921 ERROR(PLUGIN_NAME " plugin: failed to send file system notification "
1922 "for mount point %s",
1923 fs_info[i]->mountpoint);
1926 virDomainFSInfoFree(fs_info[i]);
1933 #endif /* HAVE_FS_INFO */
1935 #ifdef HAVE_JOB_STATS
1936 static void job_stats_submit(virDomainPtr domain, virTypedParameterPtr param) {
1939 if (param->type == VIR_TYPED_PARAM_INT)
1940 vl.derive = param->value.i;
1941 else if (param->type == VIR_TYPED_PARAM_UINT)
1942 vl.derive = param->value.ui;
1943 else if (param->type == VIR_TYPED_PARAM_LLONG)
1944 vl.derive = param->value.l;
1945 else if (param->type == VIR_TYPED_PARAM_ULLONG)
1946 vl.derive = param->value.ul;
1947 else if (param->type == VIR_TYPED_PARAM_DOUBLE)
1948 vl.derive = param->value.d;
1949 else if (param->type == VIR_TYPED_PARAM_BOOLEAN)
1950 vl.derive = param->value.b;
1951 else if (param->type == VIR_TYPED_PARAM_STRING) {
1952 submit_notif(domain, NOTIF_OKAY, param->value.s, "job_stats", param->field);
1955 ERROR(PLUGIN_NAME " plugin: unrecognized virTypedParameterType");
1959 submit(domain, "job_stats", param->field, &vl, 1);
1962 static int get_job_stats(virDomainPtr domain) {
1966 virTypedParameterPtr params = NULL;
1967 int flags = (extra_stats & ex_stats_job_stats_completed)
1968 ? VIR_DOMAIN_JOB_STATS_COMPLETED
1971 ret = virDomainGetJobStats(domain, &job_type, ¶ms, &nparams, flags);
1973 ERROR(PLUGIN_NAME " plugin: virDomainGetJobStats failed: %d", ret);
1977 DEBUG(PLUGIN_NAME " plugin: job_type=%d nparams=%d", job_type, nparams);
1979 for (int i = 0; i < nparams; ++i) {
1980 DEBUG(PLUGIN_NAME " plugin: param[%d] field=%s type=%d", i, params[i].field,
1982 job_stats_submit(domain, ¶ms[i]);
1985 virTypedParamsFree(params, nparams);
1988 #endif /* HAVE_JOB_STATS */
1990 static int get_domain_metrics(domain_t *domain) {
1991 if (!domain || !domain->ptr) {
1992 ERROR(PLUGIN_NAME " plugin: get_domain_metrics: NULL pointer");
1997 int status = virDomainGetInfo(domain->ptr, &info);
1999 ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
2004 if (extra_stats & ex_stats_domain_state) {
2005 #ifdef HAVE_DOM_REASON
2006 /* At this point we already know domain's state from virDomainGetInfo call,
2007 * however it doesn't provide a reason for entering particular state.
2008 * We need to get it from virDomainGetState.
2010 GET_STATS(get_domain_state, "domain reason", domain->ptr);
2014 /* Gather remaining stats only for running domains */
2015 if (info.state != VIR_DOMAIN_RUNNING)
2018 #ifdef HAVE_CPU_STATS
2019 if (extra_stats & ex_stats_pcpu)
2020 get_pcpu_stats(domain->ptr);
2023 cpu_submit(domain, info.cpuTime);
2025 memory_submit(domain->ptr, (gauge_t)info.memory * 1024);
2027 GET_STATS(get_vcpu_stats, "vcpu stats", domain->ptr, info.nrVirtCpu);
2028 GET_STATS(get_memory_stats, "memory stats", domain->ptr);
2030 #ifdef HAVE_PERF_STATS
2031 if (extra_stats & ex_stats_perf)
2032 GET_STATS(get_perf_events, "performance monitoring events", domain->ptr);
2036 if (extra_stats & ex_stats_fs_info)
2037 GET_STATS(get_fs_info, "file system info", domain->ptr);
2040 #ifdef HAVE_DISK_ERR
2041 if (extra_stats & ex_stats_disk_err)
2042 GET_STATS(get_disk_err, "disk errors", domain->ptr);
2045 #ifdef HAVE_JOB_STATS
2047 (ex_stats_job_stats_completed | ex_stats_job_stats_background))
2048 GET_STATS(get_job_stats, "job stats", domain->ptr);
2051 /* Update cached virDomainInfo. It has to be done after cpu_submit */
2052 memcpy(&domain->info, &info, sizeof(domain->info));
2057 static int get_if_dev_stats(struct interface_device *if_dev) {
2058 virDomainInterfaceStatsStruct stats = {0};
2059 char *display_name = NULL;
2062 ERROR(PLUGIN_NAME " plugin: get_if_dev_stats: NULL pointer");
2066 switch (interface_format) {
2068 display_name = if_dev->address;
2071 display_name = if_dev->number;
2075 display_name = if_dev->path;
2078 if (virDomainInterfaceStats(if_dev->dom, if_dev->path, &stats,
2079 sizeof(stats)) != 0) {
2080 ERROR(PLUGIN_NAME " plugin: virDomainInterfaceStats failed");
2084 if ((stats.rx_bytes != -1) && (stats.tx_bytes != -1))
2085 submit_derive2("if_octets", (derive_t)stats.rx_bytes,
2086 (derive_t)stats.tx_bytes, if_dev->dom, display_name);
2088 if ((stats.rx_packets != -1) && (stats.tx_packets != -1))
2089 submit_derive2("if_packets", (derive_t)stats.rx_packets,
2090 (derive_t)stats.tx_packets, if_dev->dom, display_name);
2092 if ((stats.rx_errs != -1) && (stats.tx_errs != -1))
2093 submit_derive2("if_errors", (derive_t)stats.rx_errs,
2094 (derive_t)stats.tx_errs, if_dev->dom, display_name);
2096 if ((stats.rx_drop != -1) && (stats.tx_drop != -1))
2097 submit_derive2("if_dropped", (derive_t)stats.rx_drop,
2098 (derive_t)stats.tx_drop, if_dev->dom, display_name);
2102 static int domain_lifecycle_event_cb(__attribute__((unused)) virConnectPtr con_,
2103 virDomainPtr dom, int event, int detail,
2104 __attribute__((unused)) void *opaque) {
2105 int domain_state = map_domain_event_to_state(event);
2106 int domain_reason = 0; /* 0 means UNKNOWN reason for any state */
2107 #ifdef HAVE_DOM_REASON
2108 domain_reason = map_domain_event_detail_to_reason(event, detail);
2110 domain_state_submit_notif(dom, domain_state, domain_reason);
2115 static int register_event_impl(void) {
2116 if (virEventRegisterDefaultImpl() < 0) {
2117 virErrorPtr err = virGetLastError();
2119 " plugin: error while event implementation registering: %s",
2120 err && err->message ? err->message : "Unknown error");
2127 static void virt_notif_thread_set_active(virt_notif_thread_t *thread_data,
2128 const bool active) {
2129 assert(thread_data != NULL);
2130 pthread_mutex_lock(&thread_data->active_mutex);
2131 thread_data->is_active = active;
2132 pthread_mutex_unlock(&thread_data->active_mutex);
2135 static bool virt_notif_thread_is_active(virt_notif_thread_t *thread_data) {
2136 bool active = false;
2138 assert(thread_data != NULL);
2139 pthread_mutex_lock(&thread_data->active_mutex);
2140 active = thread_data->is_active;
2141 pthread_mutex_unlock(&thread_data->active_mutex);
2146 /* worker function running default event implementation */
2147 static void *event_loop_worker(void *arg) {
2148 virt_notif_thread_t *thread_data = (virt_notif_thread_t *)arg;
2150 while (virt_notif_thread_is_active(thread_data)) {
2151 if (virEventRunDefaultImpl() < 0) {
2152 virErrorPtr err = virGetLastError();
2153 ERROR(PLUGIN_NAME " plugin: failed to run event loop: %s\n",
2154 err && err->message ? err->message : "Unknown error");
2161 static int virt_notif_thread_init(virt_notif_thread_t *thread_data) {
2162 assert(thread_data != NULL);
2164 int ret = pthread_mutex_init(&thread_data->active_mutex, NULL);
2166 ERROR(PLUGIN_NAME " plugin: Failed to initialize mutex, err %u", ret);
2171 * '0' and positive integers are meaningful ID's, therefore setting
2172 * domain_event_cb_id to '-1'
2174 thread_data->domain_event_cb_id = -1;
2175 pthread_mutex_lock(&thread_data->active_mutex);
2176 thread_data->is_active = false;
2177 pthread_mutex_unlock(&thread_data->active_mutex);
2182 /* register domain event callback and start event loop thread */
2183 static int start_event_loop(virt_notif_thread_t *thread_data) {
2184 assert(thread_data != NULL);
2185 thread_data->domain_event_cb_id = virConnectDomainEventRegisterAny(
2186 conn, NULL, VIR_DOMAIN_EVENT_ID_LIFECYCLE,
2187 VIR_DOMAIN_EVENT_CALLBACK(domain_lifecycle_event_cb), NULL, NULL);
2188 if (thread_data->domain_event_cb_id == -1) {
2189 ERROR(PLUGIN_NAME " plugin: error while callback registering");
2193 DEBUG(PLUGIN_NAME " plugin: starting event loop");
2195 virt_notif_thread_set_active(thread_data, 1);
2196 if (pthread_create(&thread_data->event_loop_tid, NULL, event_loop_worker,
2198 ERROR(PLUGIN_NAME " plugin: failed event loop thread creation");
2199 virt_notif_thread_set_active(thread_data, 0);
2200 virConnectDomainEventDeregisterAny(conn, thread_data->domain_event_cb_id);
2201 thread_data->domain_event_cb_id = -1;
2208 /* stop event loop thread and deregister callback */
2209 static void stop_event_loop(virt_notif_thread_t *thread_data) {
2211 DEBUG(PLUGIN_NAME " plugin: stopping event loop");
2214 if (virt_notif_thread_is_active(thread_data)) {
2215 virt_notif_thread_set_active(thread_data, 0);
2216 if (pthread_join(notif_thread.event_loop_tid, NULL) != 0)
2217 ERROR(PLUGIN_NAME " plugin: stopping notification thread failed");
2220 /* ... and de-registering event handler */
2221 if (conn != NULL && thread_data->domain_event_cb_id != -1) {
2222 virConnectDomainEventDeregisterAny(conn, thread_data->domain_event_cb_id);
2223 thread_data->domain_event_cb_id = -1;
2227 static int persistent_domains_state_notification(void) {
2230 #ifdef HAVE_LIST_ALL_DOMAINS
2231 virDomainPtr *domains = NULL;
2232 n = virConnectListAllDomains(conn, &domains,
2233 VIR_CONNECT_LIST_DOMAINS_PERSISTENT);
2235 VIRT_ERROR(conn, "reading list of persistent domains");
2238 DEBUG(PLUGIN_NAME " plugin: getting state of %i persistent domains", n);
2239 /* Fetch each persistent domain's state and notify it */
2241 for (int i = 0; i < n; ++i) {
2242 status = get_domain_state_notify(domains[i]);
2245 ERROR(PLUGIN_NAME " plugin: could not notify state of domain %s",
2246 virDomainGetName(domains[i]));
2248 virDomainFree(domains[i]);
2252 DEBUG(PLUGIN_NAME " plugin: notified state of %i persistent domains",
2256 n = virConnectNumOfDomains(conn);
2259 /* Get list of domains. */
2260 domids = calloc(n, sizeof(*domids));
2261 if (domids == NULL) {
2262 ERROR(PLUGIN_NAME " plugin: calloc failed.");
2265 n = virConnectListDomains(conn, domids, n);
2267 VIRT_ERROR(conn, "reading list of domains");
2271 /* Fetch info of each active domain and notify it */
2272 for (int i = 0; i < n; ++i) {
2274 virDomainPtr dom = NULL;
2275 dom = virDomainLookupByID(conn, domids[i]);
2277 VIRT_ERROR(conn, "virDomainLookupByID");
2278 /* Could be that the domain went away -- ignore it anyway. */
2281 status = virDomainGetInfo(dom, &info);
2283 /* virDomainGetState is not available. Submit 0, which corresponds to
2284 * unknown reason. */
2285 domain_state_submit_notif(dom, info.state, 0);
2287 ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
2299 static int lv_read(user_data_t *ud) {
2300 if (ud->data == NULL) {
2301 ERROR(PLUGIN_NAME " plugin: NULL userdata");
2305 struct lv_read_instance *inst = ud->data;
2306 struct lv_read_state *state = &inst->read_state;
2309 if (lv_connect() < 0)
2312 /* Wait until inst#0 establish connection */
2314 DEBUG(PLUGIN_NAME " plugin#%s: Wait until inst#0 establish connection",
2322 /* Need to refresh domain or device lists? */
2323 if ((last_refresh == (time_t)0) ||
2324 ((interval > 0) && ((last_refresh + interval) <= t))) {
2325 if (refresh_lists(inst) != 0) {
2326 if (inst->id == 0) {
2327 if (!persistent_notification)
2328 stop_event_loop(¬if_thread);
2336 /* persistent domains state notifications are handled by instance 0 */
2337 if (inst->id == 0 && persistent_notification) {
2338 int status = persistent_domains_state_notification();
2340 DEBUG(PLUGIN_NAME " plugin: persistent_domains_state_notifications "
2341 "returned with status %i",
2346 for (int i = 0; i < state->nr_domains; ++i)
2347 DEBUG(PLUGIN_NAME " plugin: domain %s",
2348 virDomainGetName(state->domains[i].ptr));
2349 for (int i = 0; i < state->nr_block_devices; ++i)
2350 DEBUG(PLUGIN_NAME " plugin: block device %d %s:%s", i,
2351 virDomainGetName(state->block_devices[i].dom),
2352 state->block_devices[i].path);
2353 for (int i = 0; i < state->nr_interface_devices; ++i)
2354 DEBUG(PLUGIN_NAME " plugin: interface device %d %s:%s", i,
2355 virDomainGetName(state->interface_devices[i].dom),
2356 state->interface_devices[i].path);
2359 /* Get domains' metrics */
2360 for (int i = 0; i < state->nr_domains; ++i) {
2361 domain_t *dom = &state->domains[i];
2364 status = get_domain_metrics(dom);
2365 #ifdef HAVE_DOM_REASON
2367 status = get_domain_state(dom->ptr);
2371 ERROR(PLUGIN_NAME " plugin: failed to get metrics for domain=%s",
2372 virDomainGetName(dom->ptr));
2375 /* Get block device stats for each domain. */
2376 for (int i = 0; i < state->nr_block_devices; ++i) {
2377 int status = get_block_device_stats(&state->block_devices[i]);
2380 " plugin: failed to get stats for block device (%s) in domain %s",
2381 state->block_devices[i].path,
2382 virDomainGetName(state->block_devices[i].dom));
2385 /* Get interface stats for each domain. */
2386 for (int i = 0; i < state->nr_interface_devices; ++i) {
2387 int status = get_if_dev_stats(&state->interface_devices[i]);
2391 " plugin: failed to get interface stats for device (%s) in domain %s",
2392 state->interface_devices[i].path,
2393 virDomainGetName(state->interface_devices[i].dom));
2399 static int lv_init_instance(size_t i, plugin_read_cb callback) {
2400 struct lv_user_data *lv_ud = &(lv_read_user_data[i]);
2401 struct lv_read_instance *inst = &(lv_ud->inst);
2403 memset(lv_ud, 0, sizeof(*lv_ud));
2405 snprintf(inst->tag, sizeof(inst->tag), "%s-%" PRIsz, PLUGIN_NAME, i);
2408 user_data_t *ud = &(lv_ud->ud);
2410 ud->free_func = NULL;
2412 INFO(PLUGIN_NAME " plugin: reader %s initialized", inst->tag);
2414 return plugin_register_complex_read(NULL, inst->tag, callback, 0, ud);
2417 static void lv_clean_read_state(struct lv_read_state *state) {
2418 free_block_devices(state);
2419 free_interface_devices(state);
2420 free_domains(state);
2423 static void lv_fini_instance(size_t i) {
2424 struct lv_read_instance *inst = &(lv_read_user_data[i].inst);
2425 struct lv_read_state *state = &(inst->read_state);
2427 lv_clean_read_state(state);
2429 INFO(PLUGIN_NAME " plugin: reader %s finalized", inst->tag);
2432 static int lv_init(void) {
2433 if (virInitialize() != 0)
2436 /* Init ignorelists if there was no explicit configuration */
2437 if (lv_init_ignorelists() != 0)
2440 if (!persistent_notification)
2441 if (virt_notif_thread_init(¬if_thread) != 0)
2446 DEBUG(PLUGIN_NAME " plugin: starting %i instances", nr_instances);
2448 for (int i = 0; i < nr_instances; ++i)
2449 if (lv_init_instance(i, lv_read) != 0)
2456 * returns 0 on success and <0 on error
2458 static int lv_domain_get_tag(xmlXPathContextPtr xpath_ctx, const char *dom_name,
2460 char xpath_str[BUFFER_MAX_LEN] = {'\0'};
2461 xmlXPathObjectPtr xpath_obj = NULL;
2462 xmlNodePtr xml_node = NULL;
2466 err = xmlXPathRegisterNs(xpath_ctx,
2467 (const xmlChar *)METADATA_VM_PARTITION_PREFIX,
2468 (const xmlChar *)METADATA_VM_PARTITION_URI);
2470 ERROR(PLUGIN_NAME " plugin: xmlXpathRegisterNs(%s, %s) failed on domain %s",
2471 METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_URI, dom_name);
2475 snprintf(xpath_str, sizeof(xpath_str), "/domain/metadata/%s:%s/text()",
2476 METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_ELEMENT);
2477 xpath_obj = xmlXPathEvalExpression((xmlChar *)xpath_str, xpath_ctx);
2478 if (xpath_obj == NULL) {
2479 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) failed on domain %s",
2480 xpath_str, dom_name);
2484 if (xpath_obj->type != XPATH_NODESET) {
2485 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) unexpected return type %d "
2486 "(wanted %d) on domain %s",
2487 xpath_str, xpath_obj->type, XPATH_NODESET, dom_name);
2492 * from now on there is no real error, it's ok if a domain
2493 * doesn't have the metadata partition tag.
2496 if (xpath_obj->nodesetval == NULL || xpath_obj->nodesetval->nodeNr != 1) {
2497 DEBUG(PLUGIN_NAME " plugin: xmlXPathEval(%s) return nodeset size=%i "
2498 "expected=1 on domain %s",
2500 (xpath_obj->nodesetval == NULL) ? 0 : xpath_obj->nodesetval->nodeNr,
2503 xml_node = xpath_obj->nodesetval->nodeTab[0];
2504 sstrncpy(dom_tag, (const char *)xml_node->content, PARTITION_TAG_MAX_LEN);
2508 /* deregister to clean up */
2509 err = xmlXPathRegisterNs(xpath_ctx,
2510 (const xmlChar *)METADATA_VM_PARTITION_PREFIX, NULL);
2512 /* we can't really recover here */
2514 " plugin: deregistration of namespace %s failed for domain %s",
2515 METADATA_VM_PARTITION_PREFIX, dom_name);
2518 xmlXPathFreeObject(xpath_obj);
2523 static int is_known_tag(const char *dom_tag) {
2524 for (int i = 0; i < nr_instances; ++i)
2525 if (!strcmp(dom_tag, lv_read_user_data[i].inst.tag))
2530 static int lv_instance_include_domain(struct lv_read_instance *inst,
2531 const char *dom_name,
2532 const char *dom_tag) {
2533 if ((dom_tag[0] != '\0') && (strcmp(dom_tag, inst->tag) == 0))
2536 /* instance#0 will always be there, so it is in charge of extra duties */
2537 if (inst->id == 0) {
2538 if (dom_tag[0] == '\0' || !is_known_tag(dom_tag)) {
2539 DEBUG(PLUGIN_NAME " plugin#%s: refreshing domain %s "
2540 "with unknown tag '%s'",
2541 inst->tag, dom_name, dom_tag);
2549 static void lv_add_block_devices(struct lv_read_state *state, virDomainPtr dom,
2550 const char *domname,
2551 xmlXPathContextPtr xpath_ctx) {
2552 xmlXPathObjectPtr xpath_obj =
2553 xmlXPathEval((const xmlChar *)"/domain/devices/disk", xpath_ctx);
2555 if (xpath_obj == NULL) {
2556 DEBUG(PLUGIN_NAME " plugin: no disk xpath-object found for domain %s",
2561 if (xpath_obj->type != XPATH_NODESET || xpath_obj->nodesetval == NULL) {
2562 DEBUG(PLUGIN_NAME " plugin: no disk node found for domain %s", domname);
2566 xmlNodeSetPtr xml_block_devices = xpath_obj->nodesetval;
2567 for (int i = 0; i < xml_block_devices->nodeNr; ++i) {
2568 xmlNodePtr xml_device = xpath_obj->nodesetval->nodeTab[i];
2569 char *path_str = NULL;
2570 char *source_str = NULL;
2575 /* Fetching path and source for block device */
2576 for (xmlNodePtr child = xml_device->children; child; child = child->next) {
2577 if (child->type != XML_ELEMENT_NODE)
2580 /* we are interested only in either "target" or "source" elements */
2581 if (xmlStrEqual(child->name, (const xmlChar *)"target"))
2582 path_str = (char *)xmlGetProp(child, (const xmlChar *)"dev");
2583 else if (xmlStrEqual(child->name, (const xmlChar *)"source")) {
2584 /* name of the source is located in "dev" or "file" element (it depends
2585 * on type of source). Trying "dev" at first*/
2586 source_str = (char *)xmlGetProp(child, (const xmlChar *)"dev");
2588 source_str = (char *)xmlGetProp(child, (const xmlChar *)"file");
2590 /* ignoring any other element*/
2593 /* source_str will be interpreted as a device path if blockdevice_format
2594 * param is set to 'source'. */
2595 const char *device_path =
2596 (blockdevice_format == source) ? source_str : path_str;
2599 /* no path found and we can't add block_device without it */
2600 WARNING(PLUGIN_NAME " plugin: could not generate device path for disk in "
2601 "domain %s - disk device will be ignored in reports",
2606 if (ignore_device_match(il_block_devices, domname, device_path) == 0) {
2607 /* we only have to store information whether 'source' exists or not */
2608 bool has_source = (source_str != NULL) ? true : false;
2610 add_block_device(state, dom, device_path, has_source);
2618 xmlFree(source_str);
2622 xmlXPathFreeObject(xpath_obj);
2625 static void lv_add_network_interfaces(struct lv_read_state *state,
2626 virDomainPtr dom, const char *domname,
2627 xmlXPathContextPtr xpath_ctx) {
2628 xmlXPathObjectPtr xpath_obj = xmlXPathEval(
2629 (xmlChar *)"/domain/devices/interface[target[@dev]]", xpath_ctx);
2631 if (xpath_obj == NULL)
2634 if (xpath_obj->type != XPATH_NODESET || xpath_obj->nodesetval == NULL) {
2635 xmlXPathFreeObject(xpath_obj);
2639 xmlNodeSetPtr xml_interfaces = xpath_obj->nodesetval;
2641 for (int j = 0; j < xml_interfaces->nodeNr; ++j) {
2643 char *address = NULL;
2644 const int itf_number = j + 1;
2646 xmlNodePtr xml_interface = xml_interfaces->nodeTab[j];
2650 for (xmlNodePtr child = xml_interface->children; child;
2651 child = child->next) {
2652 if (child->type != XML_ELEMENT_NODE)
2655 if (xmlStrEqual(child->name, (const xmlChar *)"target")) {
2656 path = (char *)xmlGetProp(child, (const xmlChar *)"dev");
2659 } else if (xmlStrEqual(child->name, (const xmlChar *)"mac")) {
2660 address = (char *)xmlGetProp(child, (const xmlChar *)"address");
2666 bool device_ignored = false;
2667 switch (interface_format) {
2669 if (ignore_device_match(il_interface_devices, domname, path) != 0)
2670 device_ignored = true;
2673 if (ignore_device_match(il_interface_devices, domname, address) != 0)
2674 device_ignored = true;
2677 char number_string[4];
2678 snprintf(number_string, sizeof(number_string), "%d", itf_number);
2679 if (ignore_device_match(il_interface_devices, domname, number_string) !=
2681 device_ignored = true;
2684 ERROR(PLUGIN_NAME " plugin: Unknown interface_format option: %d",
2688 if (!device_ignored)
2689 add_interface_device(state, dom, path, address, itf_number);
2696 xmlXPathFreeObject(xpath_obj);
2699 static bool is_domain_ignored(virDomainPtr dom) {
2700 const char *domname = virDomainGetName(dom);
2702 if (domname == NULL) {
2703 VIRT_ERROR(conn, "virDomainGetName failed, ignoring domain");
2707 if (ignorelist_match(il_domains, domname) != 0) {
2709 " plugin: ignoring domain '%s' because of ignorelist option",
2717 static int refresh_lists(struct lv_read_instance *inst) {
2718 struct lv_read_state *state = &inst->read_state;
2721 #ifndef HAVE_LIST_ALL_DOMAINS
2722 n = virConnectNumOfDomains(conn);
2724 VIRT_ERROR(conn, "reading number of domains");
2729 lv_clean_read_state(state);
2731 #ifndef HAVE_LIST_ALL_DOMAINS
2736 #ifdef HAVE_LIST_ALL_DOMAINS
2737 virDomainPtr *domains, *domains_inactive;
2738 int m = virConnectListAllDomains(conn, &domains_inactive,
2739 VIR_CONNECT_LIST_DOMAINS_INACTIVE);
2740 n = virConnectListAllDomains(conn, &domains, VIR_CONNECT_LIST_DOMAINS_ACTIVE);
2742 /* Get list of domains. */
2743 int *domids = calloc(n, sizeof(*domids));
2744 if (domids == NULL) {
2745 ERROR(PLUGIN_NAME " plugin: calloc failed.");
2749 n = virConnectListDomains(conn, domids, n);
2753 VIRT_ERROR(conn, "reading list of domains");
2754 #ifndef HAVE_LIST_ALL_DOMAINS
2757 for (int i = 0; i < m; ++i)
2758 virDomainFree(domains_inactive[i]);
2759 sfree(domains_inactive);
2764 #ifdef HAVE_LIST_ALL_DOMAINS
2765 for (int i = 0; i < m; ++i)
2766 if (is_domain_ignored(domains_inactive[i]) ||
2767 add_domain(state, domains_inactive[i], 0) < 0) {
2768 /* domain ignored or failed during adding to domains list*/
2769 virDomainFree(domains_inactive[i]);
2770 domains_inactive[i] = NULL;
2775 /* Fetch each domain and add it to the list, unless ignore. */
2776 for (int i = 0; i < n; ++i) {
2778 #ifdef HAVE_LIST_ALL_DOMAINS
2779 virDomainPtr dom = domains[i];
2781 virDomainPtr dom = virDomainLookupByID(conn, domids[i]);
2783 VIRT_ERROR(conn, "virDomainLookupByID");
2784 /* Could be that the domain went away -- ignore it anyway. */
2789 if (is_domain_ignored(dom) || add_domain(state, dom, 1) < 0) {
2791 * domain ignored or failed during adding to domains list
2793 * When domain is already tracked, then there is
2794 * no problem with memory handling (will be freed
2795 * with the rest of domains cached data)
2796 * But in case of error like this (error occurred
2797 * before adding domain to track) we have to take
2798 * care it ourselves and call virDomainFree
2804 const char *domname = virDomainGetName(dom);
2805 if (domname == NULL) {
2806 VIRT_ERROR(conn, "virDomainGetName");
2811 int status = virDomainGetInfo(dom, &info);
2813 ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
2818 if (info.state != VIR_DOMAIN_RUNNING) {
2819 DEBUG(PLUGIN_NAME " plugin: skipping inactive domain %s", domname);
2823 /* Get a list of devices for this domain. */
2824 xmlDocPtr xml_doc = NULL;
2825 xmlXPathContextPtr xpath_ctx = NULL;
2827 char *xml = virDomainGetXMLDesc(dom, 0);
2829 VIRT_ERROR(conn, "virDomainGetXMLDesc");
2833 /* Yuck, XML. Parse out the devices. */
2834 xml_doc = xmlReadDoc((xmlChar *)xml, NULL, NULL, XML_PARSE_NONET);
2835 if (xml_doc == NULL) {
2836 VIRT_ERROR(conn, "xmlReadDoc");
2840 xpath_ctx = xmlXPathNewContext(xml_doc);
2842 char tag[PARTITION_TAG_MAX_LEN] = {'\0'};
2843 if (lv_domain_get_tag(xpath_ctx, domname, tag) < 0) {
2844 ERROR(PLUGIN_NAME " plugin: lv_domain_get_tag failed.");
2848 if (!lv_instance_include_domain(inst, domname, tag))
2851 /* Block devices. */
2852 if (report_block_devices)
2853 lv_add_block_devices(state, dom, domname, xpath_ctx);
2855 /* Network interfaces. */
2856 if (report_network_interfaces)
2857 lv_add_network_interfaces(state, dom, domname, xpath_ctx);
2861 xmlXPathFreeContext(xpath_ctx);
2863 xmlFreeDoc(xml_doc);
2867 #ifdef HAVE_LIST_ALL_DOMAINS
2868 /* NOTE: domains_active and domains_inactive data will be cleared during
2869 refresh of all domains (inside lv_clean_read_state function) so we need
2870 to free here only allocated arrays */
2872 sfree(domains_inactive);
2879 DEBUG(PLUGIN_NAME " plugin#%s: refreshing"
2880 " domains=%i block_devices=%i iface_devices=%i",
2881 inst->tag, state->nr_domains, state->nr_block_devices,
2882 state->nr_interface_devices);
2887 static void free_domains(struct lv_read_state *state) {
2888 if (state->domains) {
2889 for (int i = 0; i < state->nr_domains; ++i)
2890 virDomainFree(state->domains[i].ptr);
2891 sfree(state->domains);
2893 state->domains = NULL;
2894 state->nr_domains = 0;
2897 static int add_domain(struct lv_read_state *state, virDomainPtr dom,
2899 int new_size = sizeof(state->domains[0]) * (state->nr_domains + 1);
2901 domain_t *new_ptr = realloc(state->domains, new_size);
2902 if (new_ptr == NULL) {
2903 ERROR(PLUGIN_NAME " plugin: realloc failed in add_domain()");
2907 state->domains = new_ptr;
2908 state->domains[state->nr_domains].ptr = dom;
2909 state->domains[state->nr_domains].active = active;
2910 memset(&state->domains[state->nr_domains].info, 0,
2911 sizeof(state->domains[state->nr_domains].info));
2913 return state->nr_domains++;
2916 static void free_block_devices(struct lv_read_state *state) {
2917 if (state->block_devices) {
2918 for (int i = 0; i < state->nr_block_devices; ++i)
2919 sfree(state->block_devices[i].path);
2920 sfree(state->block_devices);
2922 state->block_devices = NULL;
2923 state->nr_block_devices = 0;
2926 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
2927 const char *path, bool has_source) {
2929 char *path_copy = strdup(path);
2934 sizeof(state->block_devices[0]) * (state->nr_block_devices + 1);
2936 struct block_device *new_ptr = realloc(state->block_devices, new_size);
2937 if (new_ptr == NULL) {
2941 state->block_devices = new_ptr;
2942 state->block_devices[state->nr_block_devices].dom = dom;
2943 state->block_devices[state->nr_block_devices].path = path_copy;
2944 state->block_devices[state->nr_block_devices].has_source = has_source;
2945 return state->nr_block_devices++;
2948 static void free_interface_devices(struct lv_read_state *state) {
2949 if (state->interface_devices) {
2950 for (int i = 0; i < state->nr_interface_devices; ++i) {
2951 sfree(state->interface_devices[i].path);
2952 sfree(state->interface_devices[i].address);
2953 sfree(state->interface_devices[i].number);
2955 sfree(state->interface_devices);
2957 state->interface_devices = NULL;
2958 state->nr_interface_devices = 0;
2961 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
2962 const char *path, const char *address,
2963 unsigned int number) {
2965 if ((path == NULL) || (address == NULL))
2968 char *path_copy = strdup(path);
2972 char *address_copy = strdup(address);
2973 if (!address_copy) {
2978 char number_string[21];
2979 snprintf(number_string, sizeof(number_string), "interface-%u", number);
2980 char *number_copy = strdup(number_string);
2983 sfree(address_copy);
2988 sizeof(state->interface_devices[0]) * (state->nr_interface_devices + 1);
2990 struct interface_device *new_ptr =
2991 realloc(state->interface_devices, new_size);
2992 if (new_ptr == NULL) {
2994 sfree(address_copy);
2999 state->interface_devices = new_ptr;
3000 state->interface_devices[state->nr_interface_devices].dom = dom;
3001 state->interface_devices[state->nr_interface_devices].path = path_copy;
3002 state->interface_devices[state->nr_interface_devices].address = address_copy;
3003 state->interface_devices[state->nr_interface_devices].number = number_copy;
3004 return state->nr_interface_devices++;
3007 static int ignore_device_match(ignorelist_t *il, const char *domname,
3008 const char *devpath) {
3009 if ((domname == NULL) || (devpath == NULL))
3012 size_t n = strlen(domname) + strlen(devpath) + 2;
3013 char *name = malloc(n);
3015 ERROR(PLUGIN_NAME " plugin: malloc failed.");
3018 snprintf(name, n, "%s:%s", domname, devpath);
3019 int r = ignorelist_match(il, name);
3024 static int lv_shutdown(void) {
3025 for (int i = 0; i < nr_instances; ++i) {
3026 lv_fini_instance(i);
3029 if (!persistent_notification)
3030 stop_event_loop(¬if_thread);
3034 ignorelist_free(il_domains);
3036 ignorelist_free(il_block_devices);
3037 il_block_devices = NULL;
3038 ignorelist_free(il_interface_devices);
3039 il_interface_devices = NULL;
3044 void module_register(void) {
3045 plugin_register_complex_config("virt", lv_config);
3046 plugin_register_init(PLUGIN_NAME, lv_init);
3047 plugin_register_shutdown(PLUGIN_NAME, lv_shutdown);