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>
27 #include "utils_complain.h"
28 #include "utils_ignorelist.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>
39 #define PLUGIN_NAME "virt"
41 #ifdef LIBVIR_CHECK_VERSION
43 #if LIBVIR_CHECK_VERSION(0, 9, 2)
44 #define HAVE_DOM_REASON 1
47 #if LIBVIR_CHECK_VERSION(0, 9, 5)
48 #define HAVE_BLOCK_STATS_FLAGS 1
49 #define HAVE_DOM_REASON_PAUSED_SHUTTING_DOWN 1
52 #if LIBVIR_CHECK_VERSION(0, 9, 10)
53 #define HAVE_DISK_ERR 1
56 #if LIBVIR_CHECK_VERSION(0, 9, 11)
57 #define HAVE_CPU_STATS 1
58 #define HAVE_DOM_STATE_PMSUSPENDED 1
59 #define HAVE_DOM_REASON_RUNNING_WAKEUP 1
62 #if LIBVIR_CHECK_VERSION(1, 0, 1)
63 #define HAVE_DOM_REASON_PAUSED_SNAPSHOT 1
66 #if LIBVIR_CHECK_VERSION(1, 1, 1)
67 #define HAVE_DOM_REASON_PAUSED_CRASHED 1
70 #if LIBVIR_CHECK_VERSION(1, 2, 9)
71 #define HAVE_JOB_STATS 1
74 #if LIBVIR_CHECK_VERSION(1, 2, 10)
75 #define HAVE_DOM_REASON_CRASHED 1
78 #if LIBVIR_CHECK_VERSION(1, 2, 11)
79 #define HAVE_FS_INFO 1
82 #if LIBVIR_CHECK_VERSION(1, 2, 15)
83 #define HAVE_DOM_REASON_PAUSED_STARTING_UP 1
86 #if LIBVIR_CHECK_VERSION(1, 3, 3)
87 #define HAVE_PERF_STATS 1
88 #define HAVE_DOM_REASON_POSTCOPY 1
91 #endif /* LIBVIR_CHECK_VERSION */
93 static const char *config_keys[] = {"Connection",
100 "BlockDeviceFormatBasename",
107 "PluginInstanceFormat",
111 "PersistentNotification",
114 /* PersistentNotification is false by default */
115 static _Bool persistent_notification = 0;
117 /* libvirt event loop */
118 static pthread_t event_loop_tid;
120 static int domain_event_cb_id;
122 const char *domain_states[] = {
123 [VIR_DOMAIN_NOSTATE] = "no state",
124 [VIR_DOMAIN_RUNNING] = "the domain is running",
125 [VIR_DOMAIN_BLOCKED] = "the domain is blocked on resource",
126 [VIR_DOMAIN_PAUSED] = "the domain is paused by user",
127 [VIR_DOMAIN_SHUTDOWN] = "the domain is being shut down",
128 [VIR_DOMAIN_SHUTOFF] = "the domain is shut off",
129 [VIR_DOMAIN_CRASHED] = "the domain is crashed",
130 #ifdef HAVE_DOM_STATE_PMSUSPENDED
131 [VIR_DOMAIN_PMSUSPENDED] =
132 "the domain is suspended by guest power management",
136 static int map_domain_event_to_state(int event) {
139 case VIR_DOMAIN_EVENT_STARTED:
140 ret = VIR_DOMAIN_RUNNING;
142 case VIR_DOMAIN_EVENT_SUSPENDED:
143 ret = VIR_DOMAIN_PAUSED;
145 case VIR_DOMAIN_EVENT_RESUMED:
146 ret = VIR_DOMAIN_RUNNING;
148 case VIR_DOMAIN_EVENT_STOPPED:
149 ret = VIR_DOMAIN_SHUTOFF;
151 case VIR_DOMAIN_EVENT_SHUTDOWN:
152 ret = VIR_DOMAIN_SHUTDOWN;
154 case VIR_DOMAIN_EVENT_PMSUSPENDED:
155 ret = VIR_DOMAIN_PMSUSPENDED;
157 case VIR_DOMAIN_EVENT_CRASHED:
158 ret = VIR_DOMAIN_CRASHED;
161 ret = VIR_DOMAIN_NOSTATE;
166 static int map_domain_event_detail_to_reason(int event, int detail) {
169 case VIR_DOMAIN_EVENT_STARTED:
171 case VIR_DOMAIN_EVENT_STARTED_BOOTED: /* Normal startup from boot */
172 ret = VIR_DOMAIN_RUNNING_BOOTED;
174 case VIR_DOMAIN_EVENT_STARTED_MIGRATED: /* Incoming migration from another host */
175 ret = VIR_DOMAIN_RUNNING_MIGRATED;
177 case VIR_DOMAIN_EVENT_STARTED_RESTORED: /* Restored from a state file */
178 ret = VIR_DOMAIN_RUNNING_RESTORED;
180 case VIR_DOMAIN_EVENT_STARTED_FROM_SNAPSHOT: /* Restored from snapshot */
181 ret = VIR_DOMAIN_RUNNING_FROM_SNAPSHOT;
183 case VIR_DOMAIN_EVENT_STARTED_WAKEUP: /* Started due to wakeup event */
184 ret = VIR_DOMAIN_RUNNING_WAKEUP;
187 ret = VIR_DOMAIN_RUNNING_UNKNOWN;
190 case VIR_DOMAIN_EVENT_SUSPENDED:
192 case VIR_DOMAIN_EVENT_SUSPENDED_PAUSED: /* Normal suspend due to admin pause */
193 ret = VIR_DOMAIN_PAUSED_USER;
195 case VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED: /* Suspended for offline migration */
196 ret = VIR_DOMAIN_PAUSED_MIGRATION;
198 case VIR_DOMAIN_EVENT_SUSPENDED_IOERROR: /* Suspended due to a disk I/O error */
199 ret = VIR_DOMAIN_PAUSED_IOERROR;
201 case VIR_DOMAIN_EVENT_SUSPENDED_WATCHDOG: /* Suspended due to a watchdog firing */
202 ret = VIR_DOMAIN_PAUSED_WATCHDOG;
204 case VIR_DOMAIN_EVENT_SUSPENDED_RESTORED: /* Restored from paused state file */
205 ret = VIR_DOMAIN_PAUSED_UNKNOWN;
207 case VIR_DOMAIN_EVENT_SUSPENDED_FROM_SNAPSHOT: /* Restored from paused snapshot */
208 ret = VIR_DOMAIN_PAUSED_FROM_SNAPSHOT;
210 case VIR_DOMAIN_EVENT_SUSPENDED_API_ERROR: /* Suspended after failure during libvirt API call */
211 ret = VIR_DOMAIN_PAUSED_UNKNOWN;
213 case VIR_DOMAIN_EVENT_SUSPENDED_POSTCOPY: /* Suspended for post-copy migration */
214 ret = VIR_DOMAIN_PAUSED_POSTCOPY;
216 case VIR_DOMAIN_EVENT_SUSPENDED_POSTCOPY_FAILED: /* Suspended after failed post-copy */
217 ret = VIR_DOMAIN_PAUSED_POSTCOPY_FAILED;
220 ret = VIR_DOMAIN_PAUSED_UNKNOWN;
223 case VIR_DOMAIN_EVENT_RESUMED:
225 case VIR_DOMAIN_EVENT_RESUMED_UNPAUSED: /* Normal resume due to admin unpause */
226 ret = VIR_DOMAIN_RUNNING_UNPAUSED;
228 case VIR_DOMAIN_EVENT_RESUMED_MIGRATED: /* Resumed for completion of migration */
229 ret = VIR_DOMAIN_RUNNING_MIGRATED;
231 case VIR_DOMAIN_EVENT_RESUMED_FROM_SNAPSHOT: /* Resumed from snapshot */
232 ret = VIR_DOMAIN_RUNNING_FROM_SNAPSHOT;
234 case VIR_DOMAIN_EVENT_RESUMED_POSTCOPY: /* Resumed, but migration is still running in post-copy mode */
235 ret = VIR_DOMAIN_RUNNING_POSTCOPY;
238 ret = VIR_DOMAIN_RUNNING_UNKNOWN;
241 case VIR_DOMAIN_EVENT_STOPPED:
243 case VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN: /* Normal shutdown */
244 ret = VIR_DOMAIN_SHUTOFF_SHUTDOWN;
246 case VIR_DOMAIN_EVENT_STOPPED_DESTROYED: /* Forced poweroff from host */
247 ret = VIR_DOMAIN_SHUTOFF_DESTROYED;
249 case VIR_DOMAIN_EVENT_STOPPED_CRASHED: /* Guest crashed */
250 ret = VIR_DOMAIN_SHUTOFF_CRASHED;
252 case VIR_DOMAIN_EVENT_STOPPED_MIGRATED: /* Migrated off to another host */
253 ret = VIR_DOMAIN_SHUTOFF_MIGRATED;
255 case VIR_DOMAIN_EVENT_STOPPED_SAVED: /* Saved to a state file */
256 ret = VIR_DOMAIN_SHUTOFF_SAVED;
258 case VIR_DOMAIN_EVENT_STOPPED_FAILED: /* Host emulator/mgmt failed */
259 ret = VIR_DOMAIN_SHUTOFF_FAILED;
261 case VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT: /* Offline snapshot loaded */
262 ret = VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT;
265 ret = VIR_DOMAIN_SHUTOFF_UNKNOWN;
268 case VIR_DOMAIN_EVENT_SHUTDOWN:
270 case VIR_DOMAIN_EVENT_SHUTDOWN_FINISHED: /* Guest finished shutdown sequence */
271 ret = VIR_DOMAIN_SHUTDOWN_USER;
274 ret = VIR_DOMAIN_SHUTDOWN_UNKNOWN;
277 case VIR_DOMAIN_EVENT_PMSUSPENDED:
279 case VIR_DOMAIN_EVENT_PMSUSPENDED_MEMORY: /* Guest was PM suspended to memory */
280 ret = VIR_DOMAIN_PMSUSPENDED_UNKNOWN;
282 case VIR_DOMAIN_EVENT_PMSUSPENDED_DISK: /* Guest was PM suspended to disk */
283 ret = VIR_DOMAIN_PMSUSPENDED_DISK_UNKNOWN;
286 ret = VIR_DOMAIN_PMSUSPENDED_UNKNOWN;
289 case VIR_DOMAIN_EVENT_CRASHED:
291 case VIR_DOMAIN_EVENT_CRASHED_PANICKED: /* Guest was panicked */
292 ret = VIR_DOMAIN_CRASHED_PANICKED;
295 ret = VIR_DOMAIN_CRASHED_UNKNOWN;
299 ret = VIR_DOMAIN_NOSTATE_UNKNOWN;
304 #ifdef HAVE_DOM_REASON
305 #define DOMAIN_STATE_REASON_MAX_SIZE 20
306 const char *domain_reasons[][DOMAIN_STATE_REASON_MAX_SIZE] = {
307 [VIR_DOMAIN_NOSTATE][VIR_DOMAIN_NOSTATE_UNKNOWN] =
308 "the reason is unknown",
310 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_UNKNOWN] =
311 "the reason is unknown",
312 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_BOOTED] =
313 "normal startup from boot",
314 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_MIGRATED] =
315 "migrated from another host",
316 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_RESTORED] =
317 "restored from a state file",
318 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_FROM_SNAPSHOT] =
319 "restored from snapshot",
320 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_UNPAUSED] =
321 "returned from paused state",
322 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_MIGRATION_CANCELED] =
323 "returned from migration",
324 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_SAVE_CANCELED] =
325 "returned from failed save process",
326 #ifdef HAVE_DOM_REASON_RUNNING_WAKEUP
327 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_WAKEUP] =
328 "returned from pmsuspended due to wakeup event",
330 #ifdef HAVE_DOM_REASON_CRASHED
331 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_CRASHED] =
332 "resumed from crashed",
334 #ifdef HAVE_DOM_REASON_POSTCOPY
335 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_POSTCOPY] =
336 "running in post-copy migration mode",
339 [VIR_DOMAIN_BLOCKED][VIR_DOMAIN_BLOCKED_UNKNOWN] =
340 "the reason is unknown",
342 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_UNKNOWN] =
343 "the reason is unknown",
344 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_USER] = "paused on user request",
345 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_MIGRATION] =
346 "paused for offline migration",
347 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_SAVE] = "paused for save",
348 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_DUMP] =
349 "paused for offline core dump",
350 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_IOERROR] =
351 "paused due to a disk I/O error",
352 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_WATCHDOG] =
353 "paused due to a watchdog event",
354 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_FROM_SNAPSHOT] =
355 "paused after restoring from snapshot",
356 #ifdef HAVE_DOM_REASON_PAUSED_SHUTTING_DOWN
357 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_SHUTTING_DOWN] =
358 "paused during shutdown process",
360 #ifdef HAVE_DOM_REASON_PAUSED_SNAPSHOT
361 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_SNAPSHOT] =
362 "paused while creating a snapshot",
364 #ifdef HAVE_DOM_REASON_PAUSED_CRASHED
365 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_CRASHED] =
366 "paused due to a guest crash",
368 #ifdef HAVE_DOM_REASON_PAUSED_STARTING_UP
369 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_STARTING_UP] =
370 "the domain is being started",
372 #ifdef HAVE_DOM_REASON_POSTCOPY
373 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_POSTCOPY] =
374 "paused for post-copy migration",
375 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_POSTCOPY_FAILED] =
376 "paused after failed post-copy",
379 [VIR_DOMAIN_SHUTDOWN][VIR_DOMAIN_SHUTDOWN_UNKNOWN] =
380 "the reason is unknown",
381 [VIR_DOMAIN_SHUTDOWN][VIR_DOMAIN_SHUTDOWN_USER] =
382 "shutting down on user request",
384 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_UNKNOWN] =
385 "the reason is unknown",
386 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_SHUTDOWN] = "normal shutdown",
387 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_DESTROYED] = "forced poweroff",
388 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_CRASHED] = "domain crashed",
389 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_MIGRATED] =
390 "migrated to another host",
391 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_SAVED] = "saved to a file",
392 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_FAILED] =
393 "domain failed to start",
394 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT] =
395 "restored from a snapshot which was taken while domain was shutoff",
397 [VIR_DOMAIN_CRASHED][VIR_DOMAIN_CRASHED_UNKNOWN] =
398 "the reason is unknown",
399 #ifdef VIR_DOMAIN_CRASHED_PANICKED
400 [VIR_DOMAIN_CRASHED][VIR_DOMAIN_CRASHED_PANICKED] = "domain panicked",
403 #ifdef HAVE_DOM_STATE_PMSUSPENDED
404 [VIR_DOMAIN_PMSUSPENDED][VIR_DOMAIN_PMSUSPENDED_UNKNOWN] =
405 "the reason is unknown",
408 #endif /* HAVE_DOM_REASON */
410 #define NR_CONFIG_KEYS ((sizeof config_keys / sizeof config_keys[0]) - 1)
411 #define NANOSEC_IN_SEC 1e9
413 #define GET_STATS(_f, _name, ...) \
415 status = _f(__VA_ARGS__); \
417 ERROR(PLUGIN_NAME ": Failed to get " _name); \
421 static virConnectPtr conn = 0;
422 static char *conn_string = NULL;
423 static c_complain_t conn_complain = C_COMPLAIN_INIT_STATIC;
425 /* Node information required for %CPU */
426 static virNodeInfo nodeinfo;
428 /* Seconds between list refreshes, 0 disables completely. */
429 static int interval = 60;
431 /* List of domains, if specified. */
432 static ignorelist_t *il_domains = NULL;
433 /* List of block devices, if specified. */
434 static ignorelist_t *il_block_devices = NULL;
435 /* List of network interface devices, if specified. */
436 static ignorelist_t *il_interface_devices = NULL;
438 static int ignore_device_match(ignorelist_t *, const char *domname,
439 const char *devpath);
441 /* Actual list of block devices found on last refresh. */
442 struct block_device {
443 virDomainPtr dom; /* domain */
444 char *path; /* name of block device */
447 /* Actual list of network interfaces found on last refresh. */
448 struct interface_device {
449 virDomainPtr dom; /* domain */
450 char *path; /* name of interface device */
451 char *address; /* mac address of interface device */
452 char *number; /* interface device number */
455 typedef struct domain_s {
460 struct lv_read_state {
461 /* Actual list of domains found on last refresh. */
465 struct block_device *block_devices;
466 int nr_block_devices;
468 struct interface_device *interface_devices;
469 int nr_interface_devices;
472 static void free_domains(struct lv_read_state *state);
473 static int add_domain(struct lv_read_state *state, virDomainPtr dom);
475 static void free_block_devices(struct lv_read_state *state);
476 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
479 static void free_interface_devices(struct lv_read_state *state);
480 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
481 const char *path, const char *address,
482 unsigned int number);
484 #define METADATA_VM_PARTITION_URI "http://ovirt.org/ovirtmap/tag/1.0"
485 #define METADATA_VM_PARTITION_ELEMENT "tag"
486 #define METADATA_VM_PARTITION_PREFIX "ovirtmap"
488 #define BUFFER_MAX_LEN 256
489 #define PARTITION_TAG_MAX_LEN 32
491 struct lv_read_instance {
492 struct lv_read_state read_state;
493 char tag[PARTITION_TAG_MAX_LEN];
497 struct lv_user_data {
498 struct lv_read_instance inst;
502 #define NR_INSTANCES_DEFAULT 1
503 #define NR_INSTANCES_MAX 128
504 static int nr_instances = NR_INSTANCES_DEFAULT;
505 static struct lv_user_data lv_read_user_data[NR_INSTANCES_MAX];
507 /* HostnameFormat. */
508 #define HF_MAX_FIELDS 3
510 enum hf_field { hf_none = 0, hf_hostname, hf_name, hf_uuid };
512 static enum hf_field hostname_format[HF_MAX_FIELDS] = {hf_name};
514 /* PluginInstanceFormat */
515 #define PLGINST_MAX_FIELDS 2
517 enum plginst_field { plginst_none = 0, plginst_name, plginst_uuid };
519 static enum plginst_field plugin_instance_format[PLGINST_MAX_FIELDS] = {
522 /* BlockDeviceFormat */
523 enum bd_field { target, source };
525 /* InterfaceFormat. */
526 enum if_field { if_address, if_name, if_number };
529 #define EX_STATS_MAX_FIELDS 15
532 ex_stats_disk = 1 << 0,
533 ex_stats_pcpu = 1 << 1,
534 ex_stats_cpu_util = 1 << 2,
535 ex_stats_domain_state = 1 << 3,
536 #ifdef HAVE_PERF_STATS
537 ex_stats_perf = 1 << 4,
539 ex_stats_vcpupin = 1 << 5,
541 ex_stats_disk_err = 1 << 6,
544 ex_stats_fs_info = 1 << 7,
546 #ifdef HAVE_JOB_STATS
547 ex_stats_job_stats_completed = 1 << 8,
548 ex_stats_job_stats_background = 1 << 9,
552 static unsigned int extra_stats = ex_stats_none;
554 struct ex_stats_item {
558 static const struct ex_stats_item ex_stats_table[] = {
559 {"disk", ex_stats_disk},
560 {"pcpu", ex_stats_pcpu},
561 {"cpu_util", ex_stats_cpu_util},
562 {"domain_state", ex_stats_domain_state},
563 #ifdef HAVE_PERF_STATS
564 {"perf", ex_stats_perf},
566 {"vcpupin", ex_stats_vcpupin},
568 {"disk_err", ex_stats_disk_err},
571 {"fs_info", ex_stats_fs_info},
573 #ifdef HAVE_JOB_STATS
574 {"job_stats_completed", ex_stats_job_stats_completed},
575 {"job_stats_background", ex_stats_job_stats_background},
577 {NULL, ex_stats_none},
580 /* BlockDeviceFormatBasename */
581 _Bool blockdevice_format_basename = 0;
582 static enum bd_field blockdevice_format = target;
583 static enum if_field interface_format = if_name;
585 /* Time that we last refreshed. */
586 static time_t last_refresh = (time_t)0;
588 static int refresh_lists(struct lv_read_instance *inst);
592 unsigned long long total_user_cpu_time;
593 unsigned long long total_syst_cpu_time;
596 struct lv_block_info {
597 virDomainBlockStatsStruct bi;
599 long long rd_total_times;
600 long long wr_total_times;
603 long long fl_total_times;
606 static void init_block_info(struct lv_block_info *binfo) {
610 binfo->bi.rd_req = -1;
611 binfo->bi.wr_req = -1;
612 binfo->bi.rd_bytes = -1;
613 binfo->bi.wr_bytes = -1;
615 binfo->rd_total_times = -1;
616 binfo->wr_total_times = -1;
618 binfo->fl_total_times = -1;
621 #ifdef HAVE_BLOCK_STATS_FLAGS
623 #define GET_BLOCK_INFO_VALUE(NAME, FIELD) \
624 if (!strcmp(param[i].field, NAME)) { \
625 binfo->FIELD = param[i].value.l; \
629 static int get_block_info(struct lv_block_info *binfo,
630 virTypedParameterPtr param, int nparams) {
631 if (binfo == NULL || param == NULL)
634 for (int i = 0; i < nparams; ++i) {
635 /* ignore type. Everything must be LLONG anyway. */
636 GET_BLOCK_INFO_VALUE("rd_operations", bi.rd_req);
637 GET_BLOCK_INFO_VALUE("wr_operations", bi.wr_req);
638 GET_BLOCK_INFO_VALUE("rd_bytes", bi.rd_bytes);
639 GET_BLOCK_INFO_VALUE("wr_bytes", bi.wr_bytes);
640 GET_BLOCK_INFO_VALUE("rd_total_times", rd_total_times);
641 GET_BLOCK_INFO_VALUE("wr_total_times", wr_total_times);
642 GET_BLOCK_INFO_VALUE("flush_operations", fl_req);
643 GET_BLOCK_INFO_VALUE("flush_total_times", fl_total_times);
649 #undef GET_BLOCK_INFO_VALUE
651 #endif /* HAVE_BLOCK_STATS_FLAGS */
653 /* ERROR(...) macro for virterrors. */
654 #define VIRT_ERROR(conn, s) \
657 err = (conn) ? virConnGetLastError((conn)) : virGetLastError(); \
659 ERROR("%s: %s", (s), err->message); \
662 static void init_lv_info(struct lv_info *info) {
664 memset(info, 0, sizeof(*info));
667 static int lv_domain_info(virDomainPtr dom, struct lv_info *info) {
668 #ifdef HAVE_CPU_STATS
669 virTypedParameterPtr param = NULL;
671 #endif /* HAVE_CPU_STATS */
672 int ret = virDomainGetInfo(dom, &(info->di));
677 #ifdef HAVE_CPU_STATS
678 nparams = virDomainGetCPUStats(dom, NULL, 0, -1, 1, 0);
680 VIRT_ERROR(conn, "getting the CPU params count");
684 param = calloc(nparams, sizeof(virTypedParameter));
686 ERROR("virt plugin: alloc(%i) for cpu parameters failed.", nparams);
690 ret = virDomainGetCPUStats(dom, param, nparams, -1, 1, 0); // total stats.
692 virTypedParamsClear(param, nparams);
694 VIRT_ERROR(conn, "getting the disk params values");
698 for (int i = 0; i < nparams; ++i) {
699 if (!strcmp(param[i].field, "user_time"))
700 info->total_user_cpu_time = param[i].value.ul;
701 else if (!strcmp(param[i].field, "system_time"))
702 info->total_syst_cpu_time = param[i].value.ul;
705 virTypedParamsClear(param, nparams);
707 #endif /* HAVE_CPU_STATS */
712 static void init_value_list(value_list_t *vl, virDomainPtr dom) {
715 char uuid[VIR_UUID_STRING_BUFLEN];
717 sstrncpy(vl->plugin, PLUGIN_NAME, sizeof(vl->plugin));
721 /* Construct the hostname field according to HostnameFormat. */
722 for (int i = 0; i < HF_MAX_FIELDS; ++i) {
723 if (hostname_format[i] == hf_none)
726 n = DATA_MAX_NAME_LEN - strlen(vl->host) - 2;
728 if (i > 0 && n >= 1) {
729 strncat(vl->host, ":", 1);
733 switch (hostname_format[i]) {
737 strncat(vl->host, hostname_g, n);
740 name = virDomainGetName(dom);
742 strncat(vl->host, name, n);
745 if (virDomainGetUUIDString(dom, uuid) == 0)
746 strncat(vl->host, uuid, n);
751 vl->host[sizeof(vl->host) - 1] = '\0';
753 /* Construct the plugin instance field according to PluginInstanceFormat. */
754 for (int i = 0; i < PLGINST_MAX_FIELDS; ++i) {
755 if (plugin_instance_format[i] == plginst_none)
758 n = sizeof(vl->plugin_instance) - strlen(vl->plugin_instance) - 2;
760 if (i > 0 && n >= 1) {
761 strncat(vl->plugin_instance, ":", 1);
765 switch (plugin_instance_format[i]) {
769 name = virDomainGetName(dom);
771 strncat(vl->plugin_instance, name, n);
774 if (virDomainGetUUIDString(dom, uuid) == 0)
775 strncat(vl->plugin_instance, uuid, n);
780 vl->plugin_instance[sizeof(vl->plugin_instance) - 1] = '\0';
782 } /* void init_value_list */
784 static int init_notif(notification_t *notif, const virDomainPtr domain,
785 int severity, const char *msg, const char *type,
786 const char *type_instance) {
787 value_list_t vl = VALUE_LIST_INIT;
790 ERROR(PLUGIN_NAME ": init_notif: NULL pointer");
794 init_value_list(&vl, domain);
795 notification_init(notif, severity, msg, vl.host, vl.plugin,
796 vl.plugin_instance, type, type_instance);
797 notif->time = cdtime();
801 static void submit_notif(const virDomainPtr domain, int severity,
802 const char *msg, const char *type,
803 const char *type_instance) {
804 notification_t notif;
806 init_notif(¬if, domain, severity, msg, type, type_instance);
807 plugin_dispatch_notification(¬if);
809 plugin_notification_meta_free(notif.meta);
812 static void submit(virDomainPtr dom, char const *type,
813 char const *type_instance, value_t *values,
815 value_list_t vl = VALUE_LIST_INIT;
816 init_value_list(&vl, dom);
819 vl.values_len = values_len;
821 sstrncpy(vl.type, type, sizeof(vl.type));
822 if (type_instance != NULL)
823 sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
825 plugin_dispatch_values(&vl);
828 static void memory_submit(virDomainPtr dom, gauge_t value) {
829 submit(dom, "memory", "total", &(value_t){.gauge = value}, 1);
832 static void memory_stats_submit(gauge_t value, virDomainPtr dom,
834 static const char *tags[] = {"swap_in", "swap_out", "major_fault",
835 "minor_fault", "unused", "available",
836 "actual_balloon", "rss", "usable",
839 if ((tag_index < 0) || (tag_index >= (int)STATIC_ARRAY_SIZE(tags))) {
840 ERROR("virt plugin: Array index out of bounds: tag_index = %d", tag_index);
844 submit(dom, "memory", tags[tag_index], &(value_t){.gauge = value}, 1);
847 static void submit_derive2(const char *type, derive_t v0, derive_t v1,
848 virDomainPtr dom, const char *devname) {
850 {.derive = v0}, {.derive = v1},
853 submit(dom, type, devname, values, STATIC_ARRAY_SIZE(values));
854 } /* void submit_derive2 */
856 static void pcpu_submit(virDomainPtr dom, struct lv_info *info) {
857 #ifdef HAVE_CPU_STATS
858 if (extra_stats & ex_stats_pcpu)
859 submit_derive2("ps_cputime", info->total_user_cpu_time,
860 info->total_syst_cpu_time, dom, NULL);
861 #endif /* HAVE_CPU_STATS */
864 static double cpu_ns_to_percent(unsigned int node_cpus,
865 unsigned long long cpu_time_old,
866 unsigned long long cpu_time_new) {
867 double percent = 0.0;
868 unsigned long long cpu_time_diff = 0;
869 double time_diff_sec = CDTIME_T_TO_DOUBLE(plugin_get_interval());
871 if (node_cpus != 0 && time_diff_sec != 0 && cpu_time_old != 0) {
872 cpu_time_diff = cpu_time_new - cpu_time_old;
873 percent = ((double)(100 * cpu_time_diff)) /
874 (time_diff_sec * node_cpus * NANOSEC_IN_SEC);
877 DEBUG(PLUGIN_NAME ": node_cpus=%u cpu_time_old=%" PRIu64
878 " cpu_time_new=%" PRIu64 "cpu_time_diff=%" PRIu64
879 " time_diff_sec=%f percent=%f",
880 node_cpus, (uint64_t)cpu_time_old, (uint64_t)cpu_time_new,
881 (uint64_t)cpu_time_diff, time_diff_sec, percent);
886 static void cpu_submit(const domain_t *dom, unsigned long long cpuTime_new) {
891 if (extra_stats & ex_stats_cpu_util) {
892 /* Computing %CPU requires 2 samples of cpuTime */
893 if (dom->info.cpuTime != 0 && cpuTime_new != 0) {
895 submit(dom->ptr, "percent", "virt_cpu_total",
896 &(value_t){.gauge = cpu_ns_to_percent(
897 nodeinfo.cpus, dom->info.cpuTime, cpuTime_new)},
902 submit(dom->ptr, "virt_cpu_total", NULL, &(value_t){.derive = cpuTime_new},
906 static void vcpu_submit(derive_t value, virDomainPtr dom, int vcpu_nr,
908 char type_instance[DATA_MAX_NAME_LEN];
910 snprintf(type_instance, sizeof(type_instance), "%d", vcpu_nr);
911 submit(dom, type, type_instance, &(value_t){.derive = value}, 1);
914 static void disk_submit(struct lv_block_info *binfo, virDomainPtr dom,
916 char *dev_copy = strdup(dev);
917 const char *type_instance = dev_copy;
922 if (blockdevice_format_basename && blockdevice_format == source)
923 type_instance = basename(dev_copy);
925 if (!type_instance) {
930 char flush_type_instance[DATA_MAX_NAME_LEN];
931 snprintf(flush_type_instance, sizeof(flush_type_instance), "flush-%s",
934 if ((binfo->bi.rd_req != -1) && (binfo->bi.wr_req != -1))
935 submit_derive2("disk_ops", (derive_t)binfo->bi.rd_req,
936 (derive_t)binfo->bi.wr_req, dom, type_instance);
938 if ((binfo->bi.rd_bytes != -1) && (binfo->bi.wr_bytes != -1))
939 submit_derive2("disk_octets", (derive_t)binfo->bi.rd_bytes,
940 (derive_t)binfo->bi.wr_bytes, dom, type_instance);
942 if (extra_stats & ex_stats_disk) {
943 if ((binfo->rd_total_times != -1) && (binfo->wr_total_times != -1))
944 submit_derive2("disk_time", (derive_t)binfo->rd_total_times,
945 (derive_t)binfo->wr_total_times, dom, type_instance);
947 if (binfo->fl_req != -1)
948 submit(dom, "total_requests", flush_type_instance,
949 &(value_t){.derive = (derive_t)binfo->fl_req}, 1);
950 if (binfo->fl_total_times != -1) {
951 derive_t value = binfo->fl_total_times / 1000; // ns -> ms
952 submit(dom, "total_time_in_ms", flush_type_instance,
953 &(value_t){.derive = value}, 1);
960 static unsigned int parse_ex_stats_flags(char **exstats, int numexstats) {
961 unsigned int ex_stats_flags = ex_stats_none;
962 for (int i = 0; i < numexstats; i++) {
963 for (int j = 0; ex_stats_table[j].name != NULL; j++) {
964 if (strcasecmp(exstats[i], ex_stats_table[j].name) == 0) {
965 DEBUG(PLUGIN_NAME " plugin: enabling extra stats for '%s'",
966 ex_stats_table[j].name);
967 ex_stats_flags |= ex_stats_table[j].flag;
971 if (ex_stats_table[j + 1].name == NULL) {
972 ERROR(PLUGIN_NAME ": Unmatched ExtraStats option: %s", exstats[i]);
976 return ex_stats_flags;
979 static void domain_state_submit(virDomainPtr dom, int state, int reason) {
980 if ((state < 0) || (state >= STATIC_ARRAY_SIZE(domain_states))) {
981 ERROR(PLUGIN_NAME ": Array index out of bounds: state=%d", state);
985 char msg[DATA_MAX_NAME_LEN];
986 const char *state_str = domain_states[state];
987 #ifdef HAVE_DOM_REASON
988 if ((reason < 0) || (reason >= STATIC_ARRAY_SIZE(domain_reasons[0]))) {
989 ERROR(PLUGIN_NAME ": Array index out of bounds: reason=%d", reason);
993 const char *reason_str = domain_reasons[state][reason];
994 /* Array size for domain reasons is fixed, but different domain states can
995 * have different number of reasons. We need to check if reason was
996 * successfully parsed */
998 ERROR(PLUGIN_NAME ": Invalid reason (%d) for domain state: %s", reason,
1003 const char *reason_str = "N/A";
1006 snprintf(msg, sizeof(msg), "Domain state: %s. Reason: %s", state_str,
1011 case VIR_DOMAIN_NOSTATE:
1012 case VIR_DOMAIN_RUNNING:
1013 case VIR_DOMAIN_SHUTDOWN:
1014 case VIR_DOMAIN_SHUTOFF:
1015 severity = NOTIF_OKAY;
1017 case VIR_DOMAIN_BLOCKED:
1018 case VIR_DOMAIN_PAUSED:
1019 #ifdef DOM_STATE_PMSUSPENDED
1020 case VIR_DOMAIN_PMSUSPENDED:
1022 severity = NOTIF_WARNING;
1024 case VIR_DOMAIN_CRASHED:
1025 severity = NOTIF_FAILURE;
1028 ERROR(PLUGIN_NAME ": Unrecognized domain state (%d)", state);
1031 submit_notif(dom, severity, msg, "domain_state", NULL);
1034 static int lv_config(const char *key, const char *value) {
1035 if (virInitialize() != 0)
1038 if (il_domains == NULL)
1039 il_domains = ignorelist_create(1);
1040 if (il_block_devices == NULL)
1041 il_block_devices = ignorelist_create(1);
1042 if (il_interface_devices == NULL)
1043 il_interface_devices = ignorelist_create(1);
1045 if (strcasecmp(key, "Connection") == 0) {
1046 char *tmp = strdup(value);
1048 ERROR(PLUGIN_NAME " plugin: Connection strdup failed.");
1056 if (strcasecmp(key, "RefreshInterval") == 0) {
1058 interval = strtol(value, &eptr, 10);
1059 if (eptr == NULL || *eptr != '\0')
1064 if (strcasecmp(key, "Domain") == 0) {
1065 if (ignorelist_add(il_domains, value))
1069 if (strcasecmp(key, "BlockDevice") == 0) {
1070 if (ignorelist_add(il_block_devices, value))
1075 if (strcasecmp(key, "BlockDeviceFormat") == 0) {
1076 if (strcasecmp(value, "target") == 0)
1077 blockdevice_format = target;
1078 else if (strcasecmp(value, "source") == 0)
1079 blockdevice_format = source;
1081 ERROR(PLUGIN_NAME " plugin: unknown BlockDeviceFormat: %s", value);
1086 if (strcasecmp(key, "BlockDeviceFormatBasename") == 0) {
1087 blockdevice_format_basename = IS_TRUE(value);
1090 if (strcasecmp(key, "InterfaceDevice") == 0) {
1091 if (ignorelist_add(il_interface_devices, value))
1096 if (strcasecmp(key, "IgnoreSelected") == 0) {
1097 if (IS_TRUE(value)) {
1098 ignorelist_set_invert(il_domains, 0);
1099 ignorelist_set_invert(il_block_devices, 0);
1100 ignorelist_set_invert(il_interface_devices, 0);
1102 ignorelist_set_invert(il_domains, 1);
1103 ignorelist_set_invert(il_block_devices, 1);
1104 ignorelist_set_invert(il_interface_devices, 1);
1109 if (strcasecmp(key, "HostnameFormat") == 0) {
1111 char *fields[HF_MAX_FIELDS];
1114 value_copy = strdup(value);
1115 if (value_copy == NULL) {
1116 ERROR(PLUGIN_NAME " plugin: strdup failed.");
1120 n = strsplit(value_copy, fields, HF_MAX_FIELDS);
1123 ERROR(PLUGIN_NAME " plugin: HostnameFormat: no fields");
1127 for (int i = 0; i < n; ++i) {
1128 if (strcasecmp(fields[i], "hostname") == 0)
1129 hostname_format[i] = hf_hostname;
1130 else if (strcasecmp(fields[i], "name") == 0)
1131 hostname_format[i] = hf_name;
1132 else if (strcasecmp(fields[i], "uuid") == 0)
1133 hostname_format[i] = hf_uuid;
1135 ERROR(PLUGIN_NAME " plugin: unknown HostnameFormat field: %s",
1143 for (int i = n; i < HF_MAX_FIELDS; ++i)
1144 hostname_format[i] = hf_none;
1149 if (strcasecmp(key, "PluginInstanceFormat") == 0) {
1151 char *fields[PLGINST_MAX_FIELDS];
1154 value_copy = strdup(value);
1155 if (value_copy == NULL) {
1156 ERROR(PLUGIN_NAME " plugin: strdup failed.");
1160 n = strsplit(value_copy, fields, PLGINST_MAX_FIELDS);
1163 ERROR(PLUGIN_NAME " plugin: PluginInstanceFormat: no fields");
1167 for (int i = 0; i < n; ++i) {
1168 if (strcasecmp(fields[i], "none") == 0) {
1169 plugin_instance_format[i] = plginst_none;
1171 } else if (strcasecmp(fields[i], "name") == 0)
1172 plugin_instance_format[i] = plginst_name;
1173 else if (strcasecmp(fields[i], "uuid") == 0)
1174 plugin_instance_format[i] = plginst_uuid;
1176 ERROR(PLUGIN_NAME " plugin: unknown PluginInstanceFormat field: %s",
1184 for (int i = n; i < PLGINST_MAX_FIELDS; ++i)
1185 plugin_instance_format[i] = plginst_none;
1190 if (strcasecmp(key, "InterfaceFormat") == 0) {
1191 if (strcasecmp(value, "name") == 0)
1192 interface_format = if_name;
1193 else if (strcasecmp(value, "address") == 0)
1194 interface_format = if_address;
1195 else if (strcasecmp(value, "number") == 0)
1196 interface_format = if_number;
1198 ERROR(PLUGIN_NAME " plugin: unknown InterfaceFormat: %s", value);
1204 if (strcasecmp(key, "Instances") == 0) {
1206 double val = strtod(value, &eptr);
1208 if (*eptr != '\0') {
1209 ERROR(PLUGIN_NAME " plugin: Invalid value for Instances = '%s'", value);
1213 ERROR(PLUGIN_NAME " plugin: Instances <= 0 makes no sense.");
1216 if (val > NR_INSTANCES_MAX) {
1217 ERROR(PLUGIN_NAME " plugin: Instances=%f > NR_INSTANCES_MAX=%i"
1218 " use a lower setting or recompile the plugin.",
1219 val, NR_INSTANCES_MAX);
1223 nr_instances = (int)val;
1224 DEBUG(PLUGIN_NAME " plugin: configured %i instances", nr_instances);
1228 if (strcasecmp(key, "ExtraStats") == 0) {
1229 char *localvalue = strdup(value);
1230 if (localvalue != NULL) {
1231 char *exstats[EX_STATS_MAX_FIELDS];
1233 strsplit(localvalue, exstats, STATIC_ARRAY_SIZE(exstats));
1234 extra_stats = parse_ex_stats_flags(exstats, numexstats);
1237 #ifdef HAVE_JOB_STATS
1238 if ((extra_stats & ex_stats_job_stats_completed) &&
1239 (extra_stats & ex_stats_job_stats_background)) {
1240 ERROR(PLUGIN_NAME " plugin: Invalid job stats configuration. Only one "
1241 "type of job statistics can be collected at the same "
1249 if (strcasecmp(key, "PersistentNotification") == 0) {
1250 persistent_notification = IS_TRUE(value);
1254 /* Unrecognised option. */
1258 static int lv_connect(void) {
1260 /* `conn_string == NULL' is acceptable */
1262 /* virDomainGetFSInfo requires full read-write access connection */
1263 if (extra_stats & ex_stats_fs_info)
1264 conn = virConnectOpen(conn_string);
1267 conn = virConnectOpenReadOnly(conn_string);
1269 c_complain(LOG_ERR, &conn_complain,
1270 PLUGIN_NAME " plugin: Unable to connect: "
1271 "virConnectOpen failed.");
1274 int status = virNodeGetInfo(conn, &nodeinfo);
1276 ERROR(PLUGIN_NAME ": virNodeGetInfo failed");
1280 c_release(LOG_NOTICE, &conn_complain,
1281 PLUGIN_NAME " plugin: Connection established.");
1285 static void lv_disconnect(void) {
1287 virConnectClose(conn);
1289 WARNING(PLUGIN_NAME " plugin: closed connection to libvirt");
1292 static int lv_domain_block_info(virDomainPtr dom, const char *path,
1293 struct lv_block_info *binfo) {
1294 #ifdef HAVE_BLOCK_STATS_FLAGS
1296 if (virDomainBlockStatsFlags(dom, path, NULL, &nparams, 0) < 0 ||
1298 VIRT_ERROR(conn, "getting the disk params count");
1302 virTypedParameterPtr params = calloc((size_t)nparams, sizeof(*params));
1303 if (params == NULL) {
1304 ERROR("virt plugin: alloc(%i) for block=%s parameters failed.", nparams,
1310 if (virDomainBlockStatsFlags(dom, path, params, &nparams, 0) < 0) {
1311 VIRT_ERROR(conn, "getting the disk params values");
1313 rc = get_block_info(binfo, params, nparams);
1316 virTypedParamsClear(params, nparams);
1320 return virDomainBlockStats(dom, path, &(binfo->bi), sizeof(binfo->bi));
1321 #endif /* HAVE_BLOCK_STATS_FLAGS */
1324 #ifdef HAVE_PERF_STATS
1325 static void perf_submit(virDomainStatsRecordPtr stats) {
1326 for (int i = 0; i < stats->nparams; ++i) {
1327 /* Replace '.' with '_' in event field to match other metrics' naming
1329 char *c = strchr(stats->params[i].field, '.');
1332 submit(stats->dom, "perf", stats->params[i].field,
1333 &(value_t){.derive = stats->params[i].value.ul}, 1);
1337 static int get_perf_events(virDomainPtr domain) {
1338 virDomainStatsRecordPtr *stats = NULL;
1339 /* virDomainListGetStats requires a NULL terminated list of domains */
1340 virDomainPtr domain_array[] = {domain, NULL};
1343 virDomainListGetStats(domain_array, VIR_DOMAIN_STATS_PERF, &stats, 0);
1345 ERROR("virt plugin: virDomainListGetStats failed with status %i.", status);
1349 for (int i = 0; i < status; ++i)
1350 perf_submit(stats[i]);
1352 virDomainStatsRecordListFree(stats);
1355 #endif /* HAVE_PERF_STATS */
1357 static void vcpu_pin_submit(virDomainPtr dom, int max_cpus, int vcpu,
1358 unsigned char *cpu_maps, int cpu_map_len) {
1359 for (int cpu = 0; cpu < max_cpus; ++cpu) {
1360 char type_instance[DATA_MAX_NAME_LEN];
1361 _Bool is_set = VIR_CPU_USABLE(cpu_maps, cpu_map_len, vcpu, cpu) ? 1 : 0;
1363 snprintf(type_instance, sizeof(type_instance), "vcpu_%d-cpu_%d", vcpu, cpu);
1364 submit(dom, "cpu_affinity", type_instance, &(value_t){.gauge = is_set}, 1);
1368 static int get_vcpu_stats(virDomainPtr domain, unsigned short nr_virt_cpu) {
1369 int max_cpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
1370 int cpu_map_len = VIR_CPU_MAPLEN(max_cpus);
1372 virVcpuInfoPtr vinfo = calloc(nr_virt_cpu, sizeof(vinfo[0]));
1373 if (vinfo == NULL) {
1374 ERROR(PLUGIN_NAME " plugin: malloc failed.");
1378 unsigned char *cpumaps = calloc(nr_virt_cpu, cpu_map_len);
1379 if (cpumaps == NULL) {
1380 ERROR(PLUGIN_NAME " plugin: malloc failed.");
1386 virDomainGetVcpus(domain, vinfo, nr_virt_cpu, cpumaps, cpu_map_len);
1388 ERROR(PLUGIN_NAME " plugin: virDomainGetVcpus failed with status %i.",
1395 for (int i = 0; i < nr_virt_cpu; ++i) {
1396 vcpu_submit(vinfo[i].cpuTime, domain, vinfo[i].number, "virt_vcpu");
1397 if (extra_stats & ex_stats_vcpupin)
1398 vcpu_pin_submit(domain, max_cpus, i, cpumaps, cpu_map_len);
1406 #ifdef HAVE_DOM_REASON
1407 static int get_domain_state(virDomainPtr domain) {
1408 int domain_state = 0;
1409 int domain_reason = 0;
1411 int status = virDomainGetState(domain, &domain_state, &domain_reason, 0);
1413 ERROR(PLUGIN_NAME " plugin: virDomainGetState failed with status %i.",
1418 if (persistent_notification)
1419 domain_state_submit(domain, domain_state, domain_reason);
1423 #endif /* HAVE_DOM_REASON */
1425 static int get_memory_stats(virDomainPtr domain) {
1426 virDomainMemoryStatPtr minfo =
1427 calloc(VIR_DOMAIN_MEMORY_STAT_NR, sizeof(virDomainMemoryStatStruct));
1428 if (minfo == NULL) {
1429 ERROR("virt plugin: malloc failed.");
1434 virDomainMemoryStats(domain, minfo, VIR_DOMAIN_MEMORY_STAT_NR, 0);
1435 if (mem_stats < 0) {
1436 ERROR("virt plugin: virDomainMemoryStats failed with mem_stats %i.",
1442 for (int i = 0; i < mem_stats; i++)
1443 memory_stats_submit((gauge_t)minfo[i].val * 1024, domain, minfo[i].tag);
1449 #ifdef HAVE_DISK_ERR
1450 static void disk_err_submit(virDomainPtr domain,
1451 virDomainDiskErrorPtr disk_err) {
1452 submit(domain, "disk_error", disk_err->disk,
1453 &(value_t){.gauge = disk_err->error}, 1);
1456 static int get_disk_err(virDomainPtr domain) {
1457 /* Get preferred size of disk errors array */
1458 int disk_err_count = virDomainGetDiskErrors(domain, NULL, 0, 0);
1459 if (disk_err_count == -1) {
1461 " plugin: failed to get preferred size of disk errors array");
1466 " plugin: preferred size of disk errors array: %d for domain %s",
1467 disk_err_count, virDomainGetName(domain));
1468 virDomainDiskError disk_err[disk_err_count];
1470 disk_err_count = virDomainGetDiskErrors(domain, disk_err, disk_err_count, 0);
1471 if (disk_err_count == -1) {
1472 ERROR(PLUGIN_NAME " plugin: virDomainGetDiskErrors failed with status %d",
1477 DEBUG(PLUGIN_NAME " plugin: detected %d disk errors in domain %s",
1478 disk_err_count, virDomainGetName(domain));
1480 for (int i = 0; i < disk_err_count; ++i) {
1481 disk_err_submit(domain, &disk_err[i]);
1482 sfree(disk_err[i].disk);
1487 #endif /* HAVE_DISK_ERR */
1489 static int get_block_stats(struct block_device *block_dev) {
1492 ERROR(PLUGIN_NAME " plugin: get_block_stats NULL pointer");
1496 struct lv_block_info binfo;
1497 init_block_info(&binfo);
1499 if (lv_domain_block_info(block_dev->dom, block_dev->path, &binfo) < 0) {
1500 ERROR(PLUGIN_NAME " plugin: lv_domain_block_info failed");
1504 disk_submit(&binfo, block_dev->dom, block_dev->path);
1510 #define NM_ADD_ITEM(_fun, _name, _val) \
1512 ret = _fun(¬if, _name, _val); \
1514 ERROR(PLUGIN_NAME " plugin: failed to add notification metadata"); \
1519 #define NM_ADD_STR_ITEMS(_items, _size) \
1521 for (int _i = 0; _i < _size; ++_i) { \
1523 " plugin: Adding notification metadata name=%s value=%s", \
1524 _items[_i].name, _items[_i].value); \
1525 NM_ADD_ITEM(plugin_notification_meta_add_string, _items[_i].name, \
1526 _items[_i].value); \
1530 static int fs_info_notify(virDomainPtr domain, virDomainFSInfoPtr fs_info) {
1531 notification_t notif;
1534 /* Local struct, just for the purpose of this function. */
1535 typedef struct nm_str_item_s {
1540 nm_str_item_t fs_dev_alias[fs_info->ndevAlias];
1541 nm_str_item_t fs_str_items[] = {
1542 {.name = "mountpoint", .value = fs_info->mountpoint},
1543 {.name = "name", .value = fs_info->name},
1544 {.name = "fstype", .value = fs_info->fstype}};
1546 for (int i = 0; i < fs_info->ndevAlias; ++i) {
1547 fs_dev_alias[i].name = "devAlias";
1548 fs_dev_alias[i].value = fs_info->devAlias[i];
1551 init_notif(¬if, domain, NOTIF_OKAY, "File system information",
1552 "file_system", NULL);
1553 NM_ADD_STR_ITEMS(fs_str_items, STATIC_ARRAY_SIZE(fs_str_items));
1554 NM_ADD_ITEM(plugin_notification_meta_add_unsigned_int, "ndevAlias",
1555 fs_info->ndevAlias);
1556 NM_ADD_STR_ITEMS(fs_dev_alias, fs_info->ndevAlias);
1558 plugin_dispatch_notification(¬if);
1562 plugin_notification_meta_free(notif.meta);
1566 #undef RETURN_ON_ERR
1567 #undef NM_ADD_STR_ITEMS
1569 static int get_fs_info(virDomainPtr domain) {
1570 virDomainFSInfoPtr *fs_info = NULL;
1573 int mount_points_cnt = virDomainGetFSInfo(domain, &fs_info, 0);
1574 if (mount_points_cnt == -1) {
1575 ERROR(PLUGIN_NAME " plugin: virDomainGetFSInfo failed: %d",
1577 return mount_points_cnt;
1580 for (int i = 0; i < mount_points_cnt; ++i) {
1581 if (fs_info_notify(domain, fs_info[i]) != 0) {
1582 ERROR(PLUGIN_NAME " plugin: failed to send file system notification "
1583 "for mount point %s",
1584 fs_info[i]->mountpoint);
1587 virDomainFSInfoFree(fs_info[i]);
1594 #endif /* HAVE_FS_INFO */
1596 #ifdef HAVE_JOB_STATS
1597 static void job_stats_submit(virDomainPtr domain, virTypedParameterPtr param) {
1600 if (param->type == VIR_TYPED_PARAM_INT)
1601 vl.derive = param->value.i;
1602 else if (param->type == VIR_TYPED_PARAM_UINT)
1603 vl.derive = param->value.ui;
1604 else if (param->type == VIR_TYPED_PARAM_LLONG)
1605 vl.derive = param->value.l;
1606 else if (param->type == VIR_TYPED_PARAM_ULLONG)
1607 vl.derive = param->value.ul;
1608 else if (param->type == VIR_TYPED_PARAM_DOUBLE)
1609 vl.derive = param->value.d;
1610 else if (param->type == VIR_TYPED_PARAM_BOOLEAN)
1611 vl.derive = param->value.b;
1612 else if (param->type == VIR_TYPED_PARAM_STRING) {
1613 submit_notif(domain, NOTIF_OKAY, param->value.s, "job_stats", param->field);
1616 ERROR(PLUGIN_NAME " plugin: unrecognized virTypedParameterType");
1620 submit(domain, "job_stats", param->field, &vl, 1);
1623 static int get_job_stats(virDomainPtr domain) {
1627 virTypedParameterPtr params = NULL;
1628 int flags = (extra_stats & ex_stats_job_stats_completed)
1629 ? VIR_DOMAIN_JOB_STATS_COMPLETED
1632 ret = virDomainGetJobStats(domain, &job_type, ¶ms, &nparams, flags);
1634 ERROR(PLUGIN_NAME " plugin: virDomainGetJobStats failed: %d", ret);
1638 DEBUG(PLUGIN_NAME " plugin: job_type=%d nparams=%d", job_type, nparams);
1640 for (int i = 0; i < nparams; ++i) {
1641 DEBUG(PLUGIN_NAME " plugin: param[%d] field=%s type=%d", i, params[i].field,
1643 job_stats_submit(domain, ¶ms[i]);
1646 virTypedParamsFree(params, nparams);
1649 #endif /* HAVE_JOB_STATS */
1651 static int get_domain_metrics(domain_t *domain) {
1652 struct lv_info info;
1654 if (!domain || !domain->ptr) {
1655 ERROR(PLUGIN_NAME ": get_domain_metrics: NULL pointer");
1659 init_lv_info(&info);
1660 int status = lv_domain_info(domain->ptr, &info);
1662 ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
1667 if (extra_stats & ex_stats_domain_state) {
1668 #ifdef HAVE_DOM_REASON
1669 /* At this point we already know domain's state from virDomainGetInfo call,
1670 * however it doesn't provide a reason for entering particular state.
1671 * We need to get it from virDomainGetState.
1673 GET_STATS(get_domain_state, "domain reason", domain->ptr);
1675 /* virDomainGetState is not available. Submit 0, which corresponds to
1676 * unknown reason. */
1677 if (persistent_notification)
1678 domain_state_submit(domain->ptr, info.di.state, 0);
1682 /* Gather remaining stats only for running domains */
1683 if (info.di.state != VIR_DOMAIN_RUNNING)
1686 pcpu_submit(domain->ptr, &info);
1687 cpu_submit(domain, info.di.cpuTime);
1689 memory_submit(domain->ptr, (gauge_t)info.di.memory * 1024);
1691 GET_STATS(get_vcpu_stats, "vcpu stats", domain->ptr, info.di.nrVirtCpu);
1692 GET_STATS(get_memory_stats, "memory stats", domain->ptr);
1694 #ifdef HAVE_PERF_STATS
1695 if (extra_stats & ex_stats_perf)
1696 GET_STATS(get_perf_events, "performance monitoring events", domain->ptr);
1700 if (extra_stats & ex_stats_fs_info)
1701 GET_STATS(get_fs_info, "file system info", domain->ptr);
1704 #ifdef HAVE_DISK_ERR
1705 if (extra_stats & ex_stats_disk_err)
1706 GET_STATS(get_disk_err, "disk errors", domain->ptr);
1709 #ifdef HAVE_JOB_STATS
1711 (ex_stats_job_stats_completed | ex_stats_job_stats_background))
1712 GET_STATS(get_job_stats, "job stats", domain->ptr);
1715 /* Update cached virDomainInfo. It has to be done after cpu_submit */
1716 memcpy(&domain->info, &info.di, sizeof(domain->info));
1721 static int get_if_dev_stats(struct interface_device *if_dev) {
1722 virDomainInterfaceStatsStruct stats = {0};
1723 char *display_name = NULL;
1726 ERROR(PLUGIN_NAME " plugin: get_if_dev_stats: NULL pointer");
1730 switch (interface_format) {
1732 display_name = if_dev->address;
1735 display_name = if_dev->number;
1739 display_name = if_dev->path;
1742 if (virDomainInterfaceStats(if_dev->dom, if_dev->path, &stats,
1743 sizeof(stats)) != 0) {
1744 ERROR(PLUGIN_NAME " plugin: virDomainInterfaceStats failed");
1748 if ((stats.rx_bytes != -1) && (stats.tx_bytes != -1))
1749 submit_derive2("if_octets", (derive_t)stats.rx_bytes,
1750 (derive_t)stats.tx_bytes, if_dev->dom, display_name);
1752 if ((stats.rx_packets != -1) && (stats.tx_packets != -1))
1753 submit_derive2("if_packets", (derive_t)stats.rx_packets,
1754 (derive_t)stats.tx_packets, if_dev->dom, display_name);
1756 if ((stats.rx_errs != -1) && (stats.tx_errs != -1))
1757 submit_derive2("if_errors", (derive_t)stats.rx_errs,
1758 (derive_t)stats.tx_errs, if_dev->dom, display_name);
1760 if ((stats.rx_drop != -1) && (stats.tx_drop != -1))
1761 submit_derive2("if_dropped", (derive_t)stats.rx_drop,
1762 (derive_t)stats.tx_drop, if_dev->dom, display_name);
1766 static int domain_lifecycle_event_cb(__attribute__((unused)) virConnectPtr conn,
1767 virDomainPtr dom, int event, int detail,
1768 __attribute__((unused)) void *opaque) {
1769 int domain_state = map_domain_event_to_state(event);
1770 int domain_reason = map_domain_event_detail_to_reason(event, detail);
1771 domain_state_submit(dom, domain_state, domain_reason);
1776 static int register_event_impl(void) {
1777 if (virEventRegisterDefaultImpl() < 0) {
1778 virErrorPtr err = virGetLastError();
1780 " plugin: error while event implementation registering: %s",
1781 err && err->message ? err->message : "Unknown error");
1788 /* worker function running default event implementation */
1789 static void *event_loop_worker(__attribute__((unused)) void *arg) {
1791 if (virEventRunDefaultImpl() < 0) {
1792 virErrorPtr err = virGetLastError();
1793 ERROR(PLUGIN_NAME " plugin: failed to run event loop: %s\n",
1794 err && err->message ? err->message : "Unknown error");
1801 /* register domain event callback and start event loop thread */
1802 static int start_event_loop(void) {
1803 domain_event_cb_id = virConnectDomainEventRegisterAny(
1804 conn, NULL, VIR_DOMAIN_EVENT_ID_LIFECYCLE,
1805 VIR_DOMAIN_EVENT_CALLBACK(domain_lifecycle_event_cb), NULL, NULL);
1806 if (domain_event_cb_id == -1) {
1807 ERROR(PLUGIN_NAME " plugin: error while callback registering");
1811 if (pthread_create(&event_loop_tid, NULL, event_loop_worker, NULL)) {
1812 ERROR(PLUGIN_NAME " plugin: failed event loop thread creation");
1813 virConnectDomainEventDeregisterAny(conn, domain_event_cb_id);
1820 /* stop event loop thread and deregister callback */
1821 static void stop_event_loop(void) {
1822 if (pthread_cancel(event_loop_tid) != 0)
1823 ERROR(PLUGIN_NAME " plugin: cancelling thread %lu failed",
1826 if (pthread_join(event_loop_tid, NULL) != 0)
1827 ERROR(PLUGIN_NAME " plugin: stopping thread %lu failed",
1830 if (conn != NULL && domain_event_cb_id != -1)
1831 virConnectDomainEventDeregisterAny(conn, domain_event_cb_id);
1834 static int lv_read(user_data_t *ud) {
1836 struct lv_read_instance *inst = NULL;
1837 struct lv_read_state *state = NULL;
1839 if (ud->data == NULL) {
1840 ERROR(PLUGIN_NAME " plugin: NULL userdata");
1845 state = &inst->read_state;
1847 _Bool reconnect = conn == NULL ? 1 : 0;
1848 /* event implementation must be registered before connection is opened */
1849 if (inst->id == 0) {
1850 if (!persistent_notification && reconnect)
1851 if (register_event_impl() != 0)
1854 if (lv_connect() < 0)
1857 if (!persistent_notification && reconnect && conn != NULL)
1858 if (start_event_loop() != 0)
1864 /* Need to refresh domain or device lists? */
1865 if ((last_refresh == (time_t)0) ||
1866 ((interval > 0) && ((last_refresh + interval) <= t))) {
1867 if (refresh_lists(inst) != 0) {
1868 if (inst->id == 0) {
1869 if (!persistent_notification)
1879 for (int i = 0; i < state->nr_domains; ++i)
1880 DEBUG(PLUGIN_NAME " plugin: domain %s",
1881 virDomainGetName(state->domains[i].ptr));
1882 for (int i = 0; i < state->nr_block_devices; ++i)
1883 DEBUG(PLUGIN_NAME " plugin: block device %d %s:%s",
1884 i, virDomainGetName(state->block_devices[i].dom),
1885 state->block_devices[i].path);
1886 for (int i = 0; i < state->nr_interface_devices; ++i)
1887 DEBUG(PLUGIN_NAME " plugin: interface device %d %s:%s",
1888 i, virDomainGetName(state->interface_devices[i].dom),
1889 state->interface_devices[i].path);
1892 /* Get domains' metrics */
1893 for (int i = 0; i < state->nr_domains; ++i) {
1894 int status = get_domain_metrics(&state->domains[i]);
1896 ERROR(PLUGIN_NAME " failed to get metrics for domain=%s",
1897 virDomainGetName(state->domains[i].ptr));
1900 /* Get block device stats for each domain. */
1901 for (int i = 0; i < state->nr_block_devices; ++i) {
1902 int status = get_block_stats(&state->block_devices[i]);
1905 " failed to get stats for block device (%s) in domain %s",
1906 state->block_devices[i].path,
1907 virDomainGetName(state->domains[i].ptr));
1910 /* Get interface stats for each domain. */
1911 for (int i = 0; i < state->nr_interface_devices; ++i) {
1912 int status = get_if_dev_stats(&state->interface_devices[i]);
1915 " failed to get interface stats for device (%s) in domain %s",
1916 state->interface_devices[i].path,
1917 virDomainGetName(state->interface_devices[i].dom));
1923 static int lv_init_instance(size_t i, plugin_read_cb callback) {
1924 struct lv_user_data *lv_ud = &(lv_read_user_data[i]);
1925 struct lv_read_instance *inst = &(lv_ud->inst);
1927 memset(lv_ud, 0, sizeof(*lv_ud));
1929 snprintf(inst->tag, sizeof(inst->tag), "%s-%" PRIsz, PLUGIN_NAME, i);
1932 user_data_t *ud = &(lv_ud->ud);
1934 ud->free_func = NULL;
1936 INFO(PLUGIN_NAME " plugin: reader %s initialized", inst->tag);
1938 return plugin_register_complex_read(NULL, inst->tag, callback, 0, ud);
1941 static void lv_clean_read_state(struct lv_read_state *state) {
1942 free_block_devices(state);
1943 free_interface_devices(state);
1944 free_domains(state);
1947 static void lv_fini_instance(size_t i) {
1948 struct lv_read_instance *inst = &(lv_read_user_data[i].inst);
1949 struct lv_read_state *state = &(inst->read_state);
1951 lv_clean_read_state(state);
1953 INFO(PLUGIN_NAME " plugin: reader %s finalized", inst->tag);
1956 static int lv_init(void) {
1957 if (virInitialize() != 0)
1960 /* event implementation must be registered before connection is opened */
1961 if (!persistent_notification)
1962 if (register_event_impl() != 0)
1965 if (lv_connect() != 0)
1968 DEBUG(PLUGIN_NAME " plugin: starting event loop");
1970 if (!persistent_notification)
1971 if (start_event_loop() != 0)
1974 DEBUG(PLUGIN_NAME " plugin: starting %i instances", nr_instances);
1976 for (int i = 0; i < nr_instances; ++i)
1977 if (lv_init_instance(i, lv_read) != 0)
1984 * returns 0 on success and <0 on error
1986 static int lv_domain_get_tag(xmlXPathContextPtr xpath_ctx, const char *dom_name,
1988 char xpath_str[BUFFER_MAX_LEN] = {'\0'};
1989 xmlXPathObjectPtr xpath_obj = NULL;
1990 xmlNodePtr xml_node = NULL;
1994 err = xmlXPathRegisterNs(xpath_ctx,
1995 (const xmlChar *)METADATA_VM_PARTITION_PREFIX,
1996 (const xmlChar *)METADATA_VM_PARTITION_URI);
1998 ERROR(PLUGIN_NAME " plugin: xmlXpathRegisterNs(%s, %s) failed on domain %s",
1999 METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_URI, dom_name);
2003 snprintf(xpath_str, sizeof(xpath_str), "/domain/metadata/%s:%s/text()",
2004 METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_ELEMENT);
2005 xpath_obj = xmlXPathEvalExpression((xmlChar *)xpath_str, xpath_ctx);
2006 if (xpath_obj == NULL) {
2007 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) failed on domain %s",
2008 xpath_str, dom_name);
2012 if (xpath_obj->type != XPATH_NODESET) {
2013 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) unexpected return type %d "
2014 "(wanted %d) on domain %s",
2015 xpath_str, xpath_obj->type, XPATH_NODESET, dom_name);
2020 * from now on there is no real error, it's ok if a domain
2021 * doesn't have the metadata partition tag.
2024 if (xpath_obj->nodesetval == NULL || xpath_obj->nodesetval->nodeNr != 1) {
2025 DEBUG(PLUGIN_NAME " plugin: xmlXPathEval(%s) return nodeset size=%i "
2026 "expected=1 on domain %s",
2028 (xpath_obj->nodesetval == NULL) ? 0 : xpath_obj->nodesetval->nodeNr,
2031 xml_node = xpath_obj->nodesetval->nodeTab[0];
2032 sstrncpy(dom_tag, (const char *)xml_node->content, PARTITION_TAG_MAX_LEN);
2036 /* deregister to clean up */
2037 err = xmlXPathRegisterNs(xpath_ctx,
2038 (const xmlChar *)METADATA_VM_PARTITION_PREFIX, NULL);
2040 /* we can't really recover here */
2042 " plugin: deregistration of namespace %s failed for domain %s",
2043 METADATA_VM_PARTITION_PREFIX, dom_name);
2046 xmlXPathFreeObject(xpath_obj);
2051 static int is_known_tag(const char *dom_tag) {
2052 for (int i = 0; i < nr_instances; ++i)
2053 if (!strcmp(dom_tag, lv_read_user_data[i].inst.tag))
2058 static int lv_instance_include_domain(struct lv_read_instance *inst,
2059 const char *dom_name,
2060 const char *dom_tag) {
2061 if ((dom_tag[0] != '\0') && (strcmp(dom_tag, inst->tag) == 0))
2064 /* instance#0 will always be there, so it is in charge of extra duties */
2065 if (inst->id == 0) {
2066 if (dom_tag[0] == '\0' || !is_known_tag(dom_tag)) {
2067 DEBUG(PLUGIN_NAME " plugin#%s: refreshing domain %s "
2068 "with unknown tag '%s'",
2069 inst->tag, dom_name, dom_tag);
2078 virConnectListAllDomains() appeared in 0.10.2
2079 Note that LIBVIR_CHECK_VERSION appeared a year later, so
2080 in some systems which actually have virConnectListAllDomains()
2081 we can't detect this.
2083 #ifdef LIBVIR_CHECK_VERSION
2084 #if LIBVIR_CHECK_VERSION(0, 10, 2)
2085 #define HAVE_LIST_ALL_DOMAINS 1
2089 static int refresh_lists(struct lv_read_instance *inst) {
2090 struct lv_read_state *state = &inst->read_state;
2093 n = virConnectNumOfDomains(conn);
2095 VIRT_ERROR(conn, "reading number of domains");
2099 lv_clean_read_state(state);
2102 #ifdef HAVE_LIST_ALL_DOMAINS
2103 virDomainPtr *domains;
2104 n = virConnectListAllDomains(conn, &domains,
2105 VIR_CONNECT_LIST_DOMAINS_ACTIVE);
2109 /* Get list of domains. */
2110 domids = malloc(sizeof(*domids) * n);
2111 if (domids == NULL) {
2112 ERROR(PLUGIN_NAME " plugin: malloc failed.");
2116 n = virConnectListDomains(conn, domids, n);
2120 VIRT_ERROR(conn, "reading list of domains");
2121 #ifndef HAVE_LIST_ALL_DOMAINS
2127 /* Fetch each domain and add it to the list, unless ignore. */
2128 for (int i = 0; i < n; ++i) {
2131 xmlDocPtr xml_doc = NULL;
2132 xmlXPathContextPtr xpath_ctx = NULL;
2133 xmlXPathObjectPtr xpath_obj = NULL;
2134 char tag[PARTITION_TAG_MAX_LEN] = {'\0'};
2138 #ifdef HAVE_LIST_ALL_DOMAINS
2139 virDomainPtr dom = domains[i];
2141 virDomainPtr dom = NULL;
2142 dom = virDomainLookupByID(conn, domids[i]);
2144 VIRT_ERROR(conn, "virDomainLookupByID");
2145 /* Could be that the domain went away -- ignore it anyway. */
2150 name = virDomainGetName(dom);
2152 VIRT_ERROR(conn, "virDomainGetName");
2156 status = virDomainGetInfo(dom, &info);
2158 ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
2163 if (info.state != VIR_DOMAIN_RUNNING) {
2164 DEBUG(PLUGIN_NAME " plugin: skipping inactive domain %s", name);
2168 if (il_domains && ignorelist_match(il_domains, name) != 0)
2171 /* Get a list of devices for this domain. */
2172 xml = virDomainGetXMLDesc(dom, 0);
2174 VIRT_ERROR(conn, "virDomainGetXMLDesc");
2178 /* Yuck, XML. Parse out the devices. */
2179 xml_doc = xmlReadDoc((xmlChar *)xml, NULL, NULL, XML_PARSE_NONET);
2180 if (xml_doc == NULL) {
2181 VIRT_ERROR(conn, "xmlReadDoc");
2185 xpath_ctx = xmlXPathNewContext(xml_doc);
2187 if (lv_domain_get_tag(xpath_ctx, name, tag) < 0) {
2188 ERROR(PLUGIN_NAME " plugin: lv_domain_get_tag failed.");
2192 if (!lv_instance_include_domain(inst, name, tag))
2195 if (add_domain(state, dom) < 0) {
2196 ERROR(PLUGIN_NAME " plugin: malloc failed.");
2200 /* Block devices. */
2201 const char *bd_xmlpath = "/domain/devices/disk/target[@dev]";
2202 if (blockdevice_format == source)
2203 bd_xmlpath = "/domain/devices/disk/source[@dev]";
2204 xpath_obj = xmlXPathEval((const xmlChar *)bd_xmlpath, xpath_ctx);
2206 if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
2207 xpath_obj->nodesetval == NULL)
2210 for (int j = 0; j < xpath_obj->nodesetval->nodeNr; ++j) {
2214 node = xpath_obj->nodesetval->nodeTab[j];
2217 path = (char *)xmlGetProp(node, (xmlChar *)"dev");
2221 if (il_block_devices &&
2222 ignore_device_match(il_block_devices, name, path) != 0)
2225 add_block_device(state, dom, path);
2230 xmlXPathFreeObject(xpath_obj);
2232 /* Network interfaces. */
2233 xpath_obj = xmlXPathEval(
2234 (xmlChar *)"/domain/devices/interface[target[@dev]]", xpath_ctx);
2235 if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
2236 xpath_obj->nodesetval == NULL)
2239 xmlNodeSetPtr xml_interfaces = xpath_obj->nodesetval;
2241 for (int j = 0; j < xml_interfaces->nodeNr; ++j) {
2243 char *address = NULL;
2244 xmlNodePtr xml_interface;
2246 xml_interface = xml_interfaces->nodeTab[j];
2250 for (xmlNodePtr child = xml_interface->children; child;
2251 child = child->next) {
2252 if (child->type != XML_ELEMENT_NODE)
2255 if (xmlStrEqual(child->name, (const xmlChar *)"target")) {
2256 path = (char *)xmlGetProp(child, (const xmlChar *)"dev");
2259 } else if (xmlStrEqual(child->name, (const xmlChar *)"mac")) {
2260 address = (char *)xmlGetProp(child, (const xmlChar *)"address");
2266 if (il_interface_devices &&
2267 (ignore_device_match(il_interface_devices, name, path) != 0 ||
2268 ignore_device_match(il_interface_devices, name, address) != 0))
2271 add_interface_device(state, dom, path, address, j + 1);
2281 xmlXPathFreeObject(xpath_obj);
2283 xmlXPathFreeContext(xpath_ctx);
2285 xmlFreeDoc(xml_doc);
2289 #ifdef HAVE_LIST_ALL_DOMAINS
2296 DEBUG(PLUGIN_NAME " plugin#%s: refreshing"
2297 " domains=%i block_devices=%i iface_devices=%i",
2298 inst->tag, state->nr_domains, state->nr_block_devices,
2299 state->nr_interface_devices);
2304 static void free_domains(struct lv_read_state *state) {
2305 if (state->domains) {
2306 for (int i = 0; i < state->nr_domains; ++i)
2307 virDomainFree(state->domains[i].ptr);
2308 sfree(state->domains);
2310 state->domains = NULL;
2311 state->nr_domains = 0;
2314 static int add_domain(struct lv_read_state *state, virDomainPtr dom) {
2316 int new_size = sizeof(state->domains[0]) * (state->nr_domains + 1);
2319 new_ptr = realloc(state->domains, new_size);
2321 new_ptr = malloc(new_size);
2323 if (new_ptr == NULL)
2326 state->domains = new_ptr;
2327 state->domains[state->nr_domains].ptr = dom;
2328 memset(&state->domains[state->nr_domains].info, 0,
2329 sizeof(state->domains[state->nr_domains].info));
2331 return state->nr_domains++;
2334 static void free_block_devices(struct lv_read_state *state) {
2335 if (state->block_devices) {
2336 for (int i = 0; i < state->nr_block_devices; ++i)
2337 sfree(state->block_devices[i].path);
2338 sfree(state->block_devices);
2340 state->block_devices = NULL;
2341 state->nr_block_devices = 0;
2344 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
2346 struct block_device *new_ptr;
2348 sizeof(state->block_devices[0]) * (state->nr_block_devices + 1);
2351 path_copy = strdup(path);
2355 if (state->block_devices)
2356 new_ptr = realloc(state->block_devices, new_size);
2358 new_ptr = malloc(new_size);
2360 if (new_ptr == NULL) {
2364 state->block_devices = new_ptr;
2365 state->block_devices[state->nr_block_devices].dom = dom;
2366 state->block_devices[state->nr_block_devices].path = path_copy;
2367 return state->nr_block_devices++;
2370 static void free_interface_devices(struct lv_read_state *state) {
2371 if (state->interface_devices) {
2372 for (int i = 0; i < state->nr_interface_devices; ++i) {
2373 sfree(state->interface_devices[i].path);
2374 sfree(state->interface_devices[i].address);
2375 sfree(state->interface_devices[i].number);
2377 sfree(state->interface_devices);
2379 state->interface_devices = NULL;
2380 state->nr_interface_devices = 0;
2383 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
2384 const char *path, const char *address,
2385 unsigned int number) {
2386 struct interface_device *new_ptr;
2388 sizeof(state->interface_devices[0]) * (state->nr_interface_devices + 1);
2389 char *path_copy, *address_copy, number_string[15];
2391 if ((path == NULL) || (address == NULL))
2394 path_copy = strdup(path);
2398 address_copy = strdup(address);
2399 if (!address_copy) {
2404 snprintf(number_string, sizeof(number_string), "interface-%u", number);
2406 if (state->interface_devices)
2407 new_ptr = realloc(state->interface_devices, new_size);
2409 new_ptr = malloc(new_size);
2411 if (new_ptr == NULL) {
2413 sfree(address_copy);
2416 state->interface_devices = new_ptr;
2417 state->interface_devices[state->nr_interface_devices].dom = dom;
2418 state->interface_devices[state->nr_interface_devices].path = path_copy;
2419 state->interface_devices[state->nr_interface_devices].address = address_copy;
2420 state->interface_devices[state->nr_interface_devices].number =
2421 strdup(number_string);
2422 return state->nr_interface_devices++;
2425 static int ignore_device_match(ignorelist_t *il, const char *domname,
2426 const char *devpath) {
2430 if ((domname == NULL) || (devpath == NULL))
2433 n = strlen(domname) + strlen(devpath) + 2;
2436 ERROR(PLUGIN_NAME " plugin: malloc failed.");
2439 snprintf(name, n, "%s:%s", domname, devpath);
2440 r = ignorelist_match(il, name);
2445 static int lv_shutdown(void) {
2446 for (int i = 0; i < nr_instances; ++i) {
2447 lv_fini_instance(i);
2450 DEBUG(PLUGIN_NAME " plugin: stopping event loop");
2452 if (!persistent_notification)
2457 ignorelist_free(il_domains);
2459 ignorelist_free(il_block_devices);
2460 il_block_devices = NULL;
2461 ignorelist_free(il_interface_devices);
2462 il_interface_devices = NULL;
2467 void module_register(void) {
2468 plugin_register_config(PLUGIN_NAME, lv_config, config_keys, NR_CONFIG_KEYS);
2469 plugin_register_init(PLUGIN_NAME, lv_init);
2470 plugin_register_shutdown(PLUGIN_NAME, lv_shutdown);