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",
113 const char *domain_states[] = {
114 [VIR_DOMAIN_NOSTATE] = "no state",
115 [VIR_DOMAIN_RUNNING] = "the domain is running",
116 [VIR_DOMAIN_BLOCKED] = "the domain is blocked on resource",
117 [VIR_DOMAIN_PAUSED] = "the domain is paused by user",
118 [VIR_DOMAIN_SHUTDOWN] = "the domain is being shut down",
119 [VIR_DOMAIN_SHUTOFF] = "the domain is shut off",
120 [VIR_DOMAIN_CRASHED] = "the domain is crashed",
121 #ifdef HAVE_DOM_STATE_PMSUSPENDED
122 [VIR_DOMAIN_PMSUSPENDED] =
123 "the domain is suspended by guest power management",
127 #ifdef HAVE_DOM_REASON
128 #define DOMAIN_STATE_REASON_MAX_SIZE 20
129 const char *domain_reasons[][DOMAIN_STATE_REASON_MAX_SIZE] = {
130 [VIR_DOMAIN_NOSTATE][VIR_DOMAIN_NOSTATE_UNKNOWN] =
131 "the reason is unknown",
133 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_UNKNOWN] =
134 "the reason is unknown",
135 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_BOOTED] =
136 "normal startup from boot",
137 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_MIGRATED] =
138 "migrated from another host",
139 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_RESTORED] =
140 "restored from a state file",
141 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_FROM_SNAPSHOT] =
142 "restored from snapshot",
143 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_UNPAUSED] =
144 "returned from paused state",
145 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_MIGRATION_CANCELED] =
146 "returned from migration",
147 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_SAVE_CANCELED] =
148 "returned from failed save process",
149 #ifdef HAVE_DOM_REASON_RUNNING_WAKEUP
150 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_WAKEUP] =
151 "returned from pmsuspended due to wakeup event",
153 #ifdef HAVE_DOM_REASON_CRASHED
154 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_CRASHED] =
155 "resumed from crashed",
157 #ifdef HAVE_DOM_REASON_POSTCOPY
158 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_POSTCOPY] =
159 "running in post-copy migration mode",
162 [VIR_DOMAIN_BLOCKED][VIR_DOMAIN_BLOCKED_UNKNOWN] =
163 "the reason is unknown",
165 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_UNKNOWN] =
166 "the reason is unknown",
167 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_USER] = "paused on user request",
168 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_MIGRATION] =
169 "paused for offline migration",
170 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_SAVE] = "paused for save",
171 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_DUMP] =
172 "paused for offline core dump",
173 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_IOERROR] =
174 "paused due to a disk I/O error",
175 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_WATCHDOG] =
176 "paused due to a watchdog event",
177 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_FROM_SNAPSHOT] =
178 "paused after restoring from snapshot",
179 #ifdef HAVE_DOM_REASON_PAUSED_SHUTTING_DOWN
180 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_SHUTTING_DOWN] =
181 "paused during shutdown process",
183 #ifdef HAVE_DOM_REASON_PAUSED_SNAPSHOT
184 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_SNAPSHOT] =
185 "paused while creating a snapshot",
187 #ifdef HAVE_DOM_REASON_PAUSED_CRASHED
188 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_CRASHED] =
189 "paused due to a guest crash",
191 #ifdef HAVE_DOM_REASON_PAUSED_STARTING_UP
192 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_STARTING_UP] =
193 "the domain is being started",
195 #ifdef HAVE_DOM_REASON_POSTCOPY
196 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_POSTCOPY] =
197 "paused for post-copy migration",
198 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_POSTCOPY_FAILED] =
199 "paused after failed post-copy",
202 [VIR_DOMAIN_SHUTDOWN][VIR_DOMAIN_SHUTDOWN_UNKNOWN] =
203 "the reason is unknown",
204 [VIR_DOMAIN_SHUTDOWN][VIR_DOMAIN_SHUTDOWN_USER] =
205 "shutting down on user request",
207 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_UNKNOWN] =
208 "the reason is unknown",
209 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_SHUTDOWN] = "normal shutdown",
210 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_DESTROYED] = "forced poweroff",
211 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_CRASHED] = "domain crashed",
212 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_MIGRATED] =
213 "migrated to another host",
214 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_SAVED] = "saved to a file",
215 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_FAILED] =
216 "domain failed to start",
217 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT] =
218 "restored from a snapshot which was taken while domain was shutoff",
220 [VIR_DOMAIN_CRASHED][VIR_DOMAIN_CRASHED_UNKNOWN] =
221 "the reason is unknown",
222 #ifdef VIR_DOMAIN_CRASHED_PANICKED
223 [VIR_DOMAIN_CRASHED][VIR_DOMAIN_CRASHED_PANICKED] = "domain panicked",
226 #ifdef HAVE_DOM_STATE_PMSUSPENDED
227 [VIR_DOMAIN_PMSUSPENDED][VIR_DOMAIN_PMSUSPENDED_UNKNOWN] =
228 "the reason is unknown",
231 #endif /* HAVE_DOM_REASON */
233 #define NR_CONFIG_KEYS ((sizeof config_keys / sizeof config_keys[0]) - 1)
234 #define NANOSEC_IN_SEC 1e9
236 #define GET_STATS(_f, _name, ...) \
238 status = _f(__VA_ARGS__); \
240 ERROR(PLUGIN_NAME ": Failed to get " _name); \
244 static virConnectPtr conn = 0;
245 static char *conn_string = NULL;
246 static c_complain_t conn_complain = C_COMPLAIN_INIT_STATIC;
248 /* Node information required for %CPU */
249 static virNodeInfo nodeinfo;
251 /* Seconds between list refreshes, 0 disables completely. */
252 static int interval = 60;
254 /* List of domains, if specified. */
255 static ignorelist_t *il_domains = NULL;
256 /* List of block devices, if specified. */
257 static ignorelist_t *il_block_devices = NULL;
258 /* List of network interface devices, if specified. */
259 static ignorelist_t *il_interface_devices = NULL;
261 static int ignore_device_match(ignorelist_t *, const char *domname,
262 const char *devpath);
264 /* Actual list of block devices found on last refresh. */
265 struct block_device {
266 virDomainPtr dom; /* domain */
267 char *path; /* name of block device */
270 /* Actual list of network interfaces found on last refresh. */
271 struct interface_device {
272 virDomainPtr dom; /* domain */
273 char *path; /* name of interface device */
274 char *address; /* mac address of interface device */
275 char *number; /* interface device number */
278 typedef struct domain_s {
283 struct lv_read_state {
284 /* Actual list of domains found on last refresh. */
288 struct block_device *block_devices;
289 int nr_block_devices;
291 struct interface_device *interface_devices;
292 int nr_interface_devices;
295 static void free_domains(struct lv_read_state *state);
296 static int add_domain(struct lv_read_state *state, virDomainPtr dom);
298 static void free_block_devices(struct lv_read_state *state);
299 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
302 static void free_interface_devices(struct lv_read_state *state);
303 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
304 const char *path, const char *address,
305 unsigned int number);
307 #define METADATA_VM_PARTITION_URI "http://ovirt.org/ovirtmap/tag/1.0"
308 #define METADATA_VM_PARTITION_ELEMENT "tag"
309 #define METADATA_VM_PARTITION_PREFIX "ovirtmap"
311 #define BUFFER_MAX_LEN 256
312 #define PARTITION_TAG_MAX_LEN 32
314 struct lv_read_instance {
315 struct lv_read_state read_state;
316 char tag[PARTITION_TAG_MAX_LEN];
320 struct lv_user_data {
321 struct lv_read_instance inst;
325 #define NR_INSTANCES_DEFAULT 1
326 #define NR_INSTANCES_MAX 128
327 static int nr_instances = NR_INSTANCES_DEFAULT;
328 static struct lv_user_data lv_read_user_data[NR_INSTANCES_MAX];
330 /* HostnameFormat. */
331 #define HF_MAX_FIELDS 3
333 enum hf_field { hf_none = 0, hf_hostname, hf_name, hf_uuid };
335 static enum hf_field hostname_format[HF_MAX_FIELDS] = {hf_name};
337 /* PluginInstanceFormat */
338 #define PLGINST_MAX_FIELDS 2
340 enum plginst_field { plginst_none = 0, plginst_name, plginst_uuid };
342 static enum plginst_field plugin_instance_format[PLGINST_MAX_FIELDS] = {
345 /* BlockDeviceFormat */
346 enum bd_field { target, source };
348 /* InterfaceFormat. */
349 enum if_field { if_address, if_name, if_number };
352 #define EX_STATS_MAX_FIELDS 15
355 ex_stats_disk = 1 << 0,
356 ex_stats_pcpu = 1 << 1,
357 ex_stats_cpu_util = 1 << 2,
358 ex_stats_domain_state = 1 << 3,
359 #ifdef HAVE_PERF_STATS
360 ex_stats_perf = 1 << 4,
362 ex_stats_vcpupin = 1 << 5,
364 ex_stats_disk_err = 1 << 6,
367 ex_stats_fs_info = 1 << 7,
369 #ifdef HAVE_JOB_STATS
370 ex_stats_job_stats_completed = 1 << 8,
371 ex_stats_job_stats_background = 1 << 9,
375 static unsigned int extra_stats = ex_stats_none;
377 struct ex_stats_item {
381 static const struct ex_stats_item ex_stats_table[] = {
382 {"disk", ex_stats_disk},
383 {"pcpu", ex_stats_pcpu},
384 {"cpu_util", ex_stats_cpu_util},
385 {"domain_state", ex_stats_domain_state},
386 #ifdef HAVE_PERF_STATS
387 {"perf", ex_stats_perf},
389 {"vcpupin", ex_stats_vcpupin},
391 {"disk_err", ex_stats_disk_err},
394 {"fs_info", ex_stats_fs_info},
396 #ifdef HAVE_JOB_STATS
397 {"job_stats_completed", ex_stats_job_stats_completed},
398 {"job_stats_background", ex_stats_job_stats_background},
400 {NULL, ex_stats_none},
403 /* BlockDeviceFormatBasename */
404 _Bool blockdevice_format_basename = 0;
405 static enum bd_field blockdevice_format = target;
406 static enum if_field interface_format = if_name;
408 /* Time that we last refreshed. */
409 static time_t last_refresh = (time_t)0;
411 static int refresh_lists(struct lv_read_instance *inst);
415 unsigned long long total_user_cpu_time;
416 unsigned long long total_syst_cpu_time;
419 struct lv_block_info {
420 virDomainBlockStatsStruct bi;
422 long long rd_total_times;
423 long long wr_total_times;
426 long long fl_total_times;
429 static void init_block_info(struct lv_block_info *binfo) {
433 binfo->bi.rd_req = -1;
434 binfo->bi.wr_req = -1;
435 binfo->bi.rd_bytes = -1;
436 binfo->bi.wr_bytes = -1;
438 binfo->rd_total_times = -1;
439 binfo->wr_total_times = -1;
441 binfo->fl_total_times = -1;
444 #ifdef HAVE_BLOCK_STATS_FLAGS
446 #define GET_BLOCK_INFO_VALUE(NAME, FIELD) \
448 if (!strcmp(param[i].field, NAME)) { \
449 binfo->FIELD = param[i].value.l; \
454 static int get_block_info(struct lv_block_info *binfo,
455 virTypedParameterPtr param, int nparams) {
456 if (binfo == NULL || param == NULL)
459 for (int i = 0; i < nparams; ++i) {
460 /* ignore type. Everything must be LLONG anyway. */
461 GET_BLOCK_INFO_VALUE("rd_operations", bi.rd_req);
462 GET_BLOCK_INFO_VALUE("wr_operations", bi.wr_req);
463 GET_BLOCK_INFO_VALUE("rd_bytes", bi.rd_bytes);
464 GET_BLOCK_INFO_VALUE("wr_bytes", bi.wr_bytes);
465 GET_BLOCK_INFO_VALUE("rd_total_times", rd_total_times);
466 GET_BLOCK_INFO_VALUE("wr_total_times", wr_total_times);
467 GET_BLOCK_INFO_VALUE("flush_operations", fl_req);
468 GET_BLOCK_INFO_VALUE("flush_total_times", fl_total_times);
474 #undef GET_BLOCK_INFO_VALUE
476 #endif /* HAVE_BLOCK_STATS_FLAGS */
478 /* ERROR(...) macro for virterrors. */
479 #define VIRT_ERROR(conn, s) \
482 err = (conn) ? virConnGetLastError((conn)) : virGetLastError(); \
484 ERROR("%s: %s", (s), err->message); \
487 static void init_lv_info(struct lv_info *info) {
489 memset(info, 0, sizeof(*info));
492 static int lv_domain_info(virDomainPtr dom, struct lv_info *info) {
493 #ifdef HAVE_CPU_STATS
494 virTypedParameterPtr param = NULL;
496 #endif /* HAVE_CPU_STATS */
497 int ret = virDomainGetInfo(dom, &(info->di));
502 #ifdef HAVE_CPU_STATS
503 nparams = virDomainGetCPUStats(dom, NULL, 0, -1, 1, 0);
505 VIRT_ERROR(conn, "getting the CPU params count");
509 param = calloc(nparams, sizeof(virTypedParameter));
511 ERROR("virt plugin: alloc(%i) for cpu parameters failed.", nparams);
515 ret = virDomainGetCPUStats(dom, param, nparams, -1, 1, 0); // total stats.
517 virTypedParamsClear(param, nparams);
519 VIRT_ERROR(conn, "getting the disk params values");
523 for (int i = 0; i < nparams; ++i) {
524 if (!strcmp(param[i].field, "user_time"))
525 info->total_user_cpu_time = param[i].value.ul;
526 else if (!strcmp(param[i].field, "system_time"))
527 info->total_syst_cpu_time = param[i].value.ul;
530 virTypedParamsClear(param, nparams);
532 #endif /* HAVE_CPU_STATS */
537 static void init_value_list(value_list_t *vl, virDomainPtr dom) {
540 char uuid[VIR_UUID_STRING_BUFLEN];
542 sstrncpy(vl->plugin, PLUGIN_NAME, sizeof(vl->plugin));
546 /* Construct the hostname field according to HostnameFormat. */
547 for (int i = 0; i < HF_MAX_FIELDS; ++i) {
548 if (hostname_format[i] == hf_none)
551 n = DATA_MAX_NAME_LEN - strlen(vl->host) - 2;
553 if (i > 0 && n >= 1) {
554 strncat(vl->host, ":", 1);
558 switch (hostname_format[i]) {
562 strncat(vl->host, hostname_g, n);
565 name = virDomainGetName(dom);
567 strncat(vl->host, name, n);
570 if (virDomainGetUUIDString(dom, uuid) == 0)
571 strncat(vl->host, uuid, n);
576 vl->host[sizeof(vl->host) - 1] = '\0';
578 /* Construct the plugin instance field according to PluginInstanceFormat. */
579 for (int i = 0; i < PLGINST_MAX_FIELDS; ++i) {
580 if (plugin_instance_format[i] == plginst_none)
583 n = sizeof(vl->plugin_instance) - strlen(vl->plugin_instance) - 2;
585 if (i > 0 && n >= 1) {
586 strncat(vl->plugin_instance, ":", 1);
590 switch (plugin_instance_format[i]) {
594 name = virDomainGetName(dom);
596 strncat(vl->plugin_instance, name, n);
599 if (virDomainGetUUIDString(dom, uuid) == 0)
600 strncat(vl->plugin_instance, uuid, n);
605 vl->plugin_instance[sizeof(vl->plugin_instance) - 1] = '\0';
607 } /* void init_value_list */
609 static int init_notif(notification_t *notif, const virDomainPtr domain,
610 int severity, const char *msg, const char *type,
611 const char *type_instance) {
612 value_list_t vl = VALUE_LIST_INIT;
615 ERROR(PLUGIN_NAME ": init_notif: NULL pointer");
619 init_value_list(&vl, domain);
620 notification_init(notif, severity, msg, vl.host, vl.plugin,
621 vl.plugin_instance, type, type_instance);
622 notif->time = cdtime();
626 static void submit_notif(const virDomainPtr domain, int severity,
627 const char *msg, const char *type,
628 const char *type_instance) {
629 notification_t notif;
631 init_notif(¬if, domain, severity, msg, type, type_instance);
632 plugin_dispatch_notification(¬if);
634 plugin_notification_meta_free(notif.meta);
637 static void submit(virDomainPtr dom, char const *type,
638 char const *type_instance, value_t *values,
640 value_list_t vl = VALUE_LIST_INIT;
641 init_value_list(&vl, dom);
644 vl.values_len = values_len;
646 sstrncpy(vl.type, type, sizeof(vl.type));
647 if (type_instance != NULL)
648 sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
650 plugin_dispatch_values(&vl);
653 static void memory_submit(virDomainPtr dom, gauge_t value) {
654 submit(dom, "memory", "total", &(value_t){.gauge = value}, 1);
657 static void memory_stats_submit(gauge_t value, virDomainPtr dom,
659 static const char *tags[] = {"swap_in", "swap_out", "major_fault",
660 "minor_fault", "unused", "available",
661 "actual_balloon", "rss", "usable",
664 if ((tag_index < 0) || (tag_index >= (int)STATIC_ARRAY_SIZE(tags))) {
665 ERROR("virt plugin: Array index out of bounds: tag_index = %d", tag_index);
669 submit(dom, "memory", tags[tag_index], &(value_t){.gauge = value}, 1);
672 static void submit_derive2(const char *type, derive_t v0, derive_t v1,
673 virDomainPtr dom, const char *devname) {
675 {.derive = v0}, {.derive = v1},
678 submit(dom, type, devname, values, STATIC_ARRAY_SIZE(values));
679 } /* void submit_derive2 */
681 static void pcpu_submit(virDomainPtr dom, struct lv_info *info) {
682 #ifdef HAVE_CPU_STATS
683 if (extra_stats & ex_stats_pcpu)
684 submit_derive2("ps_cputime", info->total_user_cpu_time,
685 info->total_syst_cpu_time, dom, NULL);
686 #endif /* HAVE_CPU_STATS */
689 static double cpu_ns_to_percent(unsigned int node_cpus,
690 unsigned long long cpu_time_old,
691 unsigned long long cpu_time_new) {
692 double percent = 0.0;
693 unsigned long long cpu_time_diff = 0;
694 double time_diff_sec = CDTIME_T_TO_DOUBLE(plugin_get_interval());
696 if (node_cpus != 0 && time_diff_sec != 0 && cpu_time_old != 0) {
697 cpu_time_diff = cpu_time_new - cpu_time_old;
698 percent = ((double)(100 * cpu_time_diff)) /
699 (time_diff_sec * node_cpus * NANOSEC_IN_SEC);
702 DEBUG(PLUGIN_NAME ": node_cpus=%u cpu_time_old=%llu cpu_time_new=%llu"
703 "cpu_time_diff=%llu time_diff_sec=%f percent=%f",
704 node_cpus, cpu_time_old, cpu_time_new, cpu_time_diff, time_diff_sec,
710 static void cpu_submit(const domain_t *dom, unsigned long long cpuTime_new) {
715 if (extra_stats & ex_stats_cpu_util) {
716 /* Computing %CPU requires 2 samples of cpuTime */
717 if (dom->info.cpuTime != 0 && cpuTime_new != 0) {
719 submit(dom->ptr, "percent", "virt_cpu_total",
720 &(value_t){.gauge = cpu_ns_to_percent(
721 nodeinfo.cpus, dom->info.cpuTime, cpuTime_new)},
726 submit(dom->ptr, "virt_cpu_total", NULL, &(value_t){.derive = cpuTime_new},
730 static void vcpu_submit(derive_t value, virDomainPtr dom, int vcpu_nr,
732 char type_instance[DATA_MAX_NAME_LEN];
734 snprintf(type_instance, sizeof(type_instance), "%d", vcpu_nr);
735 submit(dom, type, type_instance, &(value_t){.derive = value}, 1);
738 static void disk_submit(struct lv_block_info *binfo, virDomainPtr dom,
740 char *dev_copy = strdup(dev);
741 const char *type_instance = dev_copy;
746 if (blockdevice_format_basename && blockdevice_format == source)
747 type_instance = basename(dev_copy);
749 if (!type_instance) {
754 char flush_type_instance[DATA_MAX_NAME_LEN];
755 snprintf(flush_type_instance, sizeof(flush_type_instance), "flush-%s",
758 if ((binfo->bi.rd_req != -1) && (binfo->bi.wr_req != -1))
759 submit_derive2("disk_ops", (derive_t)binfo->bi.rd_req,
760 (derive_t)binfo->bi.wr_req, dom, type_instance);
762 if ((binfo->bi.rd_bytes != -1) && (binfo->bi.wr_bytes != -1))
763 submit_derive2("disk_octets", (derive_t)binfo->bi.rd_bytes,
764 (derive_t)binfo->bi.wr_bytes, dom, type_instance);
766 if (extra_stats & ex_stats_disk) {
767 if ((binfo->rd_total_times != -1) && (binfo->wr_total_times != -1))
768 submit_derive2("disk_time", (derive_t)binfo->rd_total_times,
769 (derive_t)binfo->wr_total_times, dom, type_instance);
771 if (binfo->fl_req != -1)
772 submit(dom, "total_requests", flush_type_instance,
773 &(value_t){.derive = (derive_t)binfo->fl_req}, 1);
774 if (binfo->fl_total_times != -1) {
775 derive_t value = binfo->fl_total_times / 1000; // ns -> ms
776 submit(dom, "total_time_in_ms", flush_type_instance,
777 &(value_t){.derive = value}, 1);
784 static unsigned int parse_ex_stats_flags(char **exstats, int numexstats) {
785 unsigned int ex_stats_flags = ex_stats_none;
786 for (int i = 0; i < numexstats; i++) {
787 for (int j = 0; ex_stats_table[j].name != NULL; j++) {
788 if (strcasecmp(exstats[i], ex_stats_table[j].name) == 0) {
789 DEBUG(PLUGIN_NAME " plugin: enabling extra stats for '%s'",
790 ex_stats_table[j].name);
791 ex_stats_flags |= ex_stats_table[j].flag;
795 if (ex_stats_table[j + 1].name == NULL) {
796 ERROR(PLUGIN_NAME ": Unmatched ExtraStats option: %s", exstats[i]);
800 return ex_stats_flags;
803 static void domain_state_submit(virDomainPtr dom, int state, int reason) {
805 if ((state < 0) || (state >= STATIC_ARRAY_SIZE(domain_states))) {
806 ERROR(PLUGIN_NAME ": Array index out of bounds: state=%d", state);
810 char msg[DATA_MAX_NAME_LEN];
811 const char *state_str = domain_states[state];
812 #ifdef HAVE_DOM_REASON
813 if ((reason < 0) || (reason >= STATIC_ARRAY_SIZE(domain_reasons[0]))) {
814 ERROR(PLUGIN_NAME ": Array index out of bounds: reason=%d", reason);
818 const char *reason_str = domain_reasons[state][reason];
819 /* Array size for domain reasons is fixed, but different domain states can
820 * have different number of reasons. We need to check if reason was
821 * successfully parsed */
823 ERROR(PLUGIN_NAME ": Invalid reason (%d) for domain state: %s", reason,
828 const char *reason_str = "N/A";
831 snprintf(msg, sizeof(msg), "Domain state: %s. Reason: %s", state_str,
836 case VIR_DOMAIN_NOSTATE:
837 case VIR_DOMAIN_RUNNING:
838 case VIR_DOMAIN_SHUTDOWN:
839 case VIR_DOMAIN_SHUTOFF:
840 severity = NOTIF_OKAY;
842 case VIR_DOMAIN_BLOCKED:
843 case VIR_DOMAIN_PAUSED:
844 #ifdef DOM_STATE_PMSUSPENDED
845 case VIR_DOMAIN_PMSUSPENDED:
847 severity = NOTIF_WARNING;
849 case VIR_DOMAIN_CRASHED:
850 severity = NOTIF_FAILURE;
853 ERROR(PLUGIN_NAME ": Unrecognized domain state (%d)", state);
856 submit_notif(dom, severity, msg, "domain_state", NULL);
859 static int lv_config(const char *key, const char *value) {
860 if (virInitialize() != 0)
863 if (il_domains == NULL)
864 il_domains = ignorelist_create(1);
865 if (il_block_devices == NULL)
866 il_block_devices = ignorelist_create(1);
867 if (il_interface_devices == NULL)
868 il_interface_devices = ignorelist_create(1);
870 if (strcasecmp(key, "Connection") == 0) {
871 char *tmp = strdup(value);
873 ERROR(PLUGIN_NAME " plugin: Connection strdup failed.");
881 if (strcasecmp(key, "RefreshInterval") == 0) {
883 interval = strtol(value, &eptr, 10);
884 if (eptr == NULL || *eptr != '\0')
889 if (strcasecmp(key, "Domain") == 0) {
890 if (ignorelist_add(il_domains, value))
894 if (strcasecmp(key, "BlockDevice") == 0) {
895 if (ignorelist_add(il_block_devices, value))
900 if (strcasecmp(key, "BlockDeviceFormat") == 0) {
901 if (strcasecmp(value, "target") == 0)
902 blockdevice_format = target;
903 else if (strcasecmp(value, "source") == 0)
904 blockdevice_format = source;
906 ERROR(PLUGIN_NAME " plugin: unknown BlockDeviceFormat: %s", value);
911 if (strcasecmp(key, "BlockDeviceFormatBasename") == 0) {
912 blockdevice_format_basename = IS_TRUE(value);
915 if (strcasecmp(key, "InterfaceDevice") == 0) {
916 if (ignorelist_add(il_interface_devices, value))
921 if (strcasecmp(key, "IgnoreSelected") == 0) {
922 if (IS_TRUE(value)) {
923 ignorelist_set_invert(il_domains, 0);
924 ignorelist_set_invert(il_block_devices, 0);
925 ignorelist_set_invert(il_interface_devices, 0);
927 ignorelist_set_invert(il_domains, 1);
928 ignorelist_set_invert(il_block_devices, 1);
929 ignorelist_set_invert(il_interface_devices, 1);
934 if (strcasecmp(key, "HostnameFormat") == 0) {
936 char *fields[HF_MAX_FIELDS];
939 value_copy = strdup(value);
940 if (value_copy == NULL) {
941 ERROR(PLUGIN_NAME " plugin: strdup failed.");
945 n = strsplit(value_copy, fields, HF_MAX_FIELDS);
948 ERROR(PLUGIN_NAME " plugin: HostnameFormat: no fields");
952 for (int i = 0; i < n; ++i) {
953 if (strcasecmp(fields[i], "hostname") == 0)
954 hostname_format[i] = hf_hostname;
955 else if (strcasecmp(fields[i], "name") == 0)
956 hostname_format[i] = hf_name;
957 else if (strcasecmp(fields[i], "uuid") == 0)
958 hostname_format[i] = hf_uuid;
960 ERROR(PLUGIN_NAME " plugin: unknown HostnameFormat field: %s",
968 for (int i = n; i < HF_MAX_FIELDS; ++i)
969 hostname_format[i] = hf_none;
974 if (strcasecmp(key, "PluginInstanceFormat") == 0) {
976 char *fields[PLGINST_MAX_FIELDS];
979 value_copy = strdup(value);
980 if (value_copy == NULL) {
981 ERROR(PLUGIN_NAME " plugin: strdup failed.");
985 n = strsplit(value_copy, fields, PLGINST_MAX_FIELDS);
988 ERROR(PLUGIN_NAME " plugin: PluginInstanceFormat: no fields");
992 for (int i = 0; i < n; ++i) {
993 if (strcasecmp(fields[i], "none") == 0) {
994 plugin_instance_format[i] = plginst_none;
996 } else if (strcasecmp(fields[i], "name") == 0)
997 plugin_instance_format[i] = plginst_name;
998 else if (strcasecmp(fields[i], "uuid") == 0)
999 plugin_instance_format[i] = plginst_uuid;
1001 ERROR(PLUGIN_NAME " plugin: unknown PluginInstanceFormat field: %s",
1009 for (int i = n; i < PLGINST_MAX_FIELDS; ++i)
1010 plugin_instance_format[i] = plginst_none;
1015 if (strcasecmp(key, "InterfaceFormat") == 0) {
1016 if (strcasecmp(value, "name") == 0)
1017 interface_format = if_name;
1018 else if (strcasecmp(value, "address") == 0)
1019 interface_format = if_address;
1020 else if (strcasecmp(value, "number") == 0)
1021 interface_format = if_number;
1023 ERROR(PLUGIN_NAME " plugin: unknown InterfaceFormat: %s", value);
1029 if (strcasecmp(key, "Instances") == 0) {
1031 double val = strtod(value, &eptr);
1033 if (*eptr != '\0') {
1034 ERROR(PLUGIN_NAME " plugin: Invalid value for Instances = '%s'", value);
1038 ERROR(PLUGIN_NAME " plugin: Instances <= 0 makes no sense.");
1041 if (val > NR_INSTANCES_MAX) {
1042 ERROR(PLUGIN_NAME " plugin: Instances=%f > NR_INSTANCES_MAX=%i"
1043 " use a lower setting or recompile the plugin.",
1044 val, NR_INSTANCES_MAX);
1048 nr_instances = (int)val;
1049 DEBUG(PLUGIN_NAME " plugin: configured %i instances", nr_instances);
1053 if (strcasecmp(key, "ExtraStats") == 0) {
1054 char *localvalue = strdup(value);
1055 if (localvalue != NULL) {
1056 char *exstats[EX_STATS_MAX_FIELDS];
1058 strsplit(localvalue, exstats, STATIC_ARRAY_SIZE(exstats));
1059 extra_stats = parse_ex_stats_flags(exstats, numexstats);
1062 #ifdef HAVE_JOB_STATS
1063 if ((extra_stats & ex_stats_job_stats_completed) &&
1064 (extra_stats & ex_stats_job_stats_background)) {
1065 ERROR(PLUGIN_NAME " plugin: Invalid job stats configuration. Only one "
1066 "type of job statistics can be collected at the same "
1074 /* Unrecognised option. */
1078 static int lv_connect(void) {
1080 /* `conn_string == NULL' is acceptable */
1082 /* virDomainGetFSInfo requires full read-write access connection */
1083 if (extra_stats & ex_stats_fs_info)
1084 conn = virConnectOpen(conn_string);
1087 conn = virConnectOpenReadOnly(conn_string);
1089 c_complain(LOG_ERR, &conn_complain,
1090 PLUGIN_NAME " plugin: Unable to connect: "
1091 "virConnectOpen failed.");
1094 int status = virNodeGetInfo(conn, &nodeinfo);
1096 ERROR(PLUGIN_NAME ": virNodeGetInfo failed");
1100 c_release(LOG_NOTICE, &conn_complain,
1101 PLUGIN_NAME " plugin: Connection established.");
1105 static void lv_disconnect(void) {
1107 virConnectClose(conn);
1109 WARNING(PLUGIN_NAME " plugin: closed connection to libvirt");
1112 static int lv_domain_block_info(virDomainPtr dom, const char *path,
1113 struct lv_block_info *binfo) {
1114 #ifdef HAVE_BLOCK_STATS_FLAGS
1116 if (virDomainBlockStatsFlags(dom, path, NULL, &nparams, 0) < 0 ||
1118 VIRT_ERROR(conn, "getting the disk params count");
1122 virTypedParameterPtr params = calloc((size_t)nparams, sizeof(*params));
1123 if (params == NULL) {
1124 ERROR("virt plugin: alloc(%i) for block=%s parameters failed.", nparams,
1130 if (virDomainBlockStatsFlags(dom, path, params, &nparams, 0) < 0) {
1131 VIRT_ERROR(conn, "getting the disk params values");
1133 rc = get_block_info(binfo, params, nparams);
1136 virTypedParamsClear(params, nparams);
1140 return virDomainBlockStats(dom, path, &(binfo->bi), sizeof(binfo->bi));
1141 #endif /* HAVE_BLOCK_STATS_FLAGS */
1144 #ifdef HAVE_PERF_STATS
1145 static void perf_submit(virDomainStatsRecordPtr stats) {
1146 for (int i = 0; i < stats->nparams; ++i) {
1147 /* Replace '.' with '_' in event field to match other metrics' naming
1149 char *c = strchr(stats->params[i].field, '.');
1152 submit(stats->dom, "perf", stats->params[i].field,
1153 &(value_t){.derive = stats->params[i].value.ul}, 1);
1157 static int get_perf_events(virDomainPtr domain) {
1158 virDomainStatsRecordPtr *stats = NULL;
1159 /* virDomainListGetStats requires a NULL terminated list of domains */
1160 virDomainPtr domain_array[] = {domain, NULL};
1163 virDomainListGetStats(domain_array, VIR_DOMAIN_STATS_PERF, &stats, 0);
1165 ERROR("virt plugin: virDomainListGetStats failed with status %i.", status);
1169 for (int i = 0; i < status; ++i)
1170 perf_submit(stats[i]);
1172 virDomainStatsRecordListFree(stats);
1175 #endif /* HAVE_PERF_STATS */
1177 static void vcpu_pin_submit(virDomainPtr dom, int max_cpus, int vcpu,
1178 unsigned char *cpu_maps, int cpu_map_len) {
1179 for (int cpu = 0; cpu < max_cpus; ++cpu) {
1180 char type_instance[DATA_MAX_NAME_LEN];
1181 _Bool is_set = VIR_CPU_USABLE(cpu_maps, cpu_map_len, vcpu, cpu) ? 1 : 0;
1183 snprintf(type_instance, sizeof(type_instance), "vcpu_%d-cpu_%d", vcpu, cpu);
1184 submit(dom, "cpu_affinity", type_instance, &(value_t){.gauge = is_set}, 1);
1188 static int get_vcpu_stats(virDomainPtr domain, unsigned short nr_virt_cpu) {
1189 int max_cpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
1190 int cpu_map_len = VIR_CPU_MAPLEN(max_cpus);
1192 virVcpuInfoPtr vinfo = calloc(nr_virt_cpu, sizeof(vinfo[0]));
1193 if (vinfo == NULL) {
1194 ERROR(PLUGIN_NAME " plugin: malloc failed.");
1198 unsigned char *cpumaps = calloc(nr_virt_cpu, cpu_map_len);
1199 if (cpumaps == NULL) {
1200 ERROR(PLUGIN_NAME " plugin: malloc failed.");
1206 virDomainGetVcpus(domain, vinfo, nr_virt_cpu, cpumaps, cpu_map_len);
1208 ERROR(PLUGIN_NAME " plugin: virDomainGetVcpus failed with status %i.",
1215 for (int i = 0; i < nr_virt_cpu; ++i) {
1216 vcpu_submit(vinfo[i].cpuTime, domain, vinfo[i].number, "virt_vcpu");
1217 if (extra_stats & ex_stats_vcpupin)
1218 vcpu_pin_submit(domain, max_cpus, i, cpumaps, cpu_map_len);
1226 #ifdef HAVE_DOM_REASON
1227 static int get_domain_state(virDomainPtr domain) {
1228 int domain_state = 0;
1229 int domain_reason = 0;
1231 int status = virDomainGetState(domain, &domain_state, &domain_reason, 0);
1233 ERROR(PLUGIN_NAME " plugin: virDomainGetState failed with status %i.",
1238 domain_state_submit(domain, domain_state, domain_reason);
1241 #endif /* HAVE_DOM_REASON */
1243 static int get_memory_stats(virDomainPtr domain) {
1244 virDomainMemoryStatPtr minfo =
1245 calloc(VIR_DOMAIN_MEMORY_STAT_NR, sizeof(virDomainMemoryStatStruct));
1246 if (minfo == NULL) {
1247 ERROR("virt plugin: malloc failed.");
1252 virDomainMemoryStats(domain, minfo, VIR_DOMAIN_MEMORY_STAT_NR, 0);
1253 if (mem_stats < 0) {
1254 ERROR("virt plugin: virDomainMemoryStats failed with mem_stats %i.",
1260 for (int i = 0; i < mem_stats; i++)
1261 memory_stats_submit((gauge_t)minfo[i].val * 1024, domain, minfo[i].tag);
1267 #ifdef HAVE_DISK_ERR
1268 static void disk_err_submit(virDomainPtr domain,
1269 virDomainDiskErrorPtr disk_err) {
1270 submit(domain, "disk_error", disk_err->disk,
1271 &(value_t){.gauge = disk_err->error}, 1);
1274 static int get_disk_err(virDomainPtr domain) {
1275 /* Get preferred size of disk errors array */
1276 int disk_err_count = virDomainGetDiskErrors(domain, NULL, 0, 0);
1277 if (disk_err_count == -1) {
1279 " plugin: failed to get preferred size of disk errors array");
1284 " plugin: preferred size of disk errors array: %d for domain %s",
1285 disk_err_count, virDomainGetName(domain));
1286 virDomainDiskError disk_err[disk_err_count];
1288 disk_err_count = virDomainGetDiskErrors(domain, disk_err, disk_err_count, 0);
1289 if (disk_err_count == -1) {
1290 ERROR(PLUGIN_NAME " plugin: virDomainGetDiskErrors failed with status %d",
1295 DEBUG(PLUGIN_NAME " plugin: detected %d disk errors in domain %s",
1296 disk_err_count, virDomainGetName(domain));
1298 for (int i = 0; i < disk_err_count; ++i) {
1299 disk_err_submit(domain, &disk_err[i]);
1300 sfree(disk_err[i].disk);
1305 #endif /* HAVE_DISK_ERR */
1307 static int get_block_stats(struct block_device *block_dev) {
1310 ERROR(PLUGIN_NAME " plugin: get_block_stats NULL pointer");
1314 struct lv_block_info binfo;
1315 init_block_info(&binfo);
1317 if (lv_domain_block_info(block_dev->dom, block_dev->path, &binfo) < 0) {
1318 ERROR(PLUGIN_NAME " plugin: lv_domain_block_info failed");
1322 disk_submit(&binfo, block_dev->dom, block_dev->path);
1328 #define NM_ADD_ITEM(_fun, _name, _val) \
1330 ret = _fun(¬if, _name, _val); \
1332 ERROR(PLUGIN_NAME " plugin: failed to add notification metadata"); \
1337 #define NM_ADD_STR_ITEMS(_items, _size) \
1339 for (int _i = 0; _i < _size; ++_i) { \
1341 " plugin: Adding notification metadata name=%s value=%s", \
1342 _items[_i].name, _items[_i].value); \
1343 NM_ADD_ITEM(plugin_notification_meta_add_string, _items[_i].name, \
1344 _items[_i].value); \
1348 static int fs_info_notify(virDomainPtr domain, virDomainFSInfoPtr fs_info) {
1349 notification_t notif;
1352 /* Local struct, just for the purpose of this function. */
1353 typedef struct nm_str_item_s {
1358 nm_str_item_t fs_dev_alias[fs_info->ndevAlias];
1359 nm_str_item_t fs_str_items[] = {
1360 {.name = "mountpoint", .value = fs_info->mountpoint},
1361 {.name = "name", .value = fs_info->name},
1362 {.name = "fstype", .value = fs_info->fstype}};
1364 for (int i = 0; i < fs_info->ndevAlias; ++i) {
1365 fs_dev_alias[i].name = "devAlias";
1366 fs_dev_alias[i].value = fs_info->devAlias[i];
1369 init_notif(¬if, domain, NOTIF_OKAY, "File system information",
1370 "file_system", NULL);
1371 NM_ADD_STR_ITEMS(fs_str_items, STATIC_ARRAY_SIZE(fs_str_items));
1372 NM_ADD_ITEM(plugin_notification_meta_add_unsigned_int, "ndevAlias",
1373 fs_info->ndevAlias);
1374 NM_ADD_STR_ITEMS(fs_dev_alias, fs_info->ndevAlias);
1376 plugin_dispatch_notification(¬if);
1380 plugin_notification_meta_free(notif.meta);
1384 #undef RETURN_ON_ERR
1385 #undef NM_ADD_STR_ITEMS
1387 static int get_fs_info(virDomainPtr domain) {
1388 virDomainFSInfoPtr *fs_info = NULL;
1391 int mount_points_cnt = virDomainGetFSInfo(domain, &fs_info, 0);
1392 if (mount_points_cnt == -1) {
1393 ERROR(PLUGIN_NAME " plugin: virDomainGetFSInfo failed: %d",
1395 return mount_points_cnt;
1398 for (int i = 0; i < mount_points_cnt; ++i) {
1399 if (fs_info_notify(domain, fs_info[i]) != 0) {
1400 ERROR(PLUGIN_NAME " plugin: failed to send file system notification "
1401 "for mount point %s",
1402 fs_info[i]->mountpoint);
1405 virDomainFSInfoFree(fs_info[i]);
1412 #endif /* HAVE_FS_INFO */
1414 #ifdef HAVE_JOB_STATS
1415 static void job_stats_submit(virDomainPtr domain, virTypedParameterPtr param) {
1418 if (param->type == VIR_TYPED_PARAM_INT)
1419 vl.derive = param->value.i;
1420 else if (param->type == VIR_TYPED_PARAM_UINT)
1421 vl.derive = param->value.ui;
1422 else if (param->type == VIR_TYPED_PARAM_LLONG)
1423 vl.derive = param->value.l;
1424 else if (param->type == VIR_TYPED_PARAM_ULLONG)
1425 vl.derive = param->value.ul;
1426 else if (param->type == VIR_TYPED_PARAM_DOUBLE)
1427 vl.derive = param->value.d;
1428 else if (param->type == VIR_TYPED_PARAM_BOOLEAN)
1429 vl.derive = param->value.b;
1430 else if (param->type == VIR_TYPED_PARAM_STRING) {
1431 submit_notif(domain, NOTIF_OKAY, param->value.s, "job_stats", param->field);
1434 ERROR(PLUGIN_NAME " plugin: unrecognized virTypedParameterType");
1438 submit(domain, "job_stats", param->field, &vl, 1);
1441 static int get_job_stats(virDomainPtr domain) {
1445 virTypedParameterPtr params = NULL;
1446 int flags = (extra_stats & ex_stats_job_stats_completed)
1447 ? VIR_DOMAIN_JOB_STATS_COMPLETED
1450 ret = virDomainGetJobStats(domain, &job_type, ¶ms, &nparams, flags);
1452 ERROR(PLUGIN_NAME " plugin: virDomainGetJobStats failed: %d", ret);
1456 DEBUG(PLUGIN_NAME " plugin: job_type=%d nparams=%d", job_type, nparams);
1458 for (int i = 0; i < nparams; ++i) {
1459 DEBUG(PLUGIN_NAME " plugin: param[%d] field=%s type=%d", i, params[i].field,
1461 job_stats_submit(domain, ¶ms[i]);
1464 virTypedParamsFree(params, nparams);
1467 #endif /* HAVE_JOB_STATS */
1469 static int get_domain_metrics(domain_t *domain) {
1470 struct lv_info info;
1472 if (!domain || !domain->ptr) {
1473 ERROR(PLUGIN_NAME ": get_domain_metrics: NULL pointer");
1477 init_lv_info(&info);
1478 int status = lv_domain_info(domain->ptr, &info);
1480 ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
1485 if (extra_stats & ex_stats_domain_state) {
1486 #ifdef HAVE_DOM_REASON
1487 /* At this point we already know domain's state from virDomainGetInfo call,
1488 * however it doesn't provide a reason for entering particular state.
1489 * We need to get it from virDomainGetState.
1491 GET_STATS(get_domain_state, "domain reason", domain->ptr);
1493 /* virDomainGetState is not available. Submit 0, which corresponds to
1494 * unknown reason. */
1495 domain_state_submit(domain->ptr, info.di.state, 0);
1499 /* Gather remaining stats only for running domains */
1500 if (info.di.state != VIR_DOMAIN_RUNNING)
1503 pcpu_submit(domain->ptr, &info);
1504 cpu_submit(domain, info.di.cpuTime);
1506 memory_submit(domain->ptr, (gauge_t)info.di.memory * 1024);
1508 GET_STATS(get_vcpu_stats, "vcpu stats", domain->ptr, info.di.nrVirtCpu);
1509 GET_STATS(get_memory_stats, "memory stats", domain->ptr);
1511 #ifdef HAVE_PERF_STATS
1512 if (extra_stats & ex_stats_perf)
1513 GET_STATS(get_perf_events, "performance monitoring events", domain->ptr);
1517 if (extra_stats & ex_stats_fs_info)
1518 GET_STATS(get_fs_info, "file system info", domain->ptr);
1521 #ifdef HAVE_DISK_ERR
1522 if (extra_stats & ex_stats_disk_err)
1523 GET_STATS(get_disk_err, "disk errors", domain->ptr);
1526 #ifdef HAVE_JOB_STATS
1528 (ex_stats_job_stats_completed | ex_stats_job_stats_background))
1529 GET_STATS(get_job_stats, "job stats", domain->ptr);
1532 /* Update cached virDomainInfo. It has to be done after cpu_submit */
1533 memcpy(&domain->info, &info.di, sizeof(domain->info));
1537 static int get_if_dev_stats(struct interface_device *if_dev) {
1538 virDomainInterfaceStatsStruct stats = {0};
1539 char *display_name = NULL;
1542 ERROR(PLUGIN_NAME " plugin: get_if_dev_stats: NULL pointer");
1546 switch (interface_format) {
1548 display_name = if_dev->address;
1551 display_name = if_dev->number;
1555 display_name = if_dev->path;
1558 if (virDomainInterfaceStats(if_dev->dom, if_dev->path, &stats,
1559 sizeof(stats)) != 0) {
1560 ERROR(PLUGIN_NAME " plugin: virDomainInterfaceStats failed");
1564 if ((stats.rx_bytes != -1) && (stats.tx_bytes != -1))
1565 submit_derive2("if_octets", (derive_t)stats.rx_bytes,
1566 (derive_t)stats.tx_bytes, if_dev->dom, display_name);
1568 if ((stats.rx_packets != -1) && (stats.tx_packets != -1))
1569 submit_derive2("if_packets", (derive_t)stats.rx_packets,
1570 (derive_t)stats.tx_packets, if_dev->dom, display_name);
1572 if ((stats.rx_errs != -1) && (stats.tx_errs != -1))
1573 submit_derive2("if_errors", (derive_t)stats.rx_errs,
1574 (derive_t)stats.tx_errs, if_dev->dom, display_name);
1576 if ((stats.rx_drop != -1) && (stats.tx_drop != -1))
1577 submit_derive2("if_dropped", (derive_t)stats.rx_drop,
1578 (derive_t)stats.tx_drop, if_dev->dom, display_name);
1582 static int lv_read(user_data_t *ud) {
1584 struct lv_read_instance *inst = NULL;
1585 struct lv_read_state *state = NULL;
1587 if (ud->data == NULL) {
1588 ERROR(PLUGIN_NAME " plugin: NULL userdata");
1593 state = &inst->read_state;
1595 if (inst->id == 0) {
1596 if (lv_connect() < 0)
1602 /* Need to refresh domain or device lists? */
1603 if ((last_refresh == (time_t)0) ||
1604 ((interval > 0) && ((last_refresh + interval) <= t))) {
1605 if (refresh_lists(inst) != 0) {
1614 for (int i = 0; i < nr_domains; ++i)
1615 fprintf (stderr, "domain %s\n", virDomainGetName (state->domains[i].ptr));
1616 for (int i = 0; i < nr_block_devices; ++i)
1617 fprintf (stderr, "block device %d %s:%s\n",
1618 i, virDomainGetName (block_devices[i].dom),
1619 block_devices[i].path);
1620 for (int i = 0; i < nr_interface_devices; ++i)
1621 fprintf (stderr, "interface device %d %s:%s\n",
1622 i, virDomainGetName (interface_devices[i].dom),
1623 interface_devices[i].path);
1626 /* Get domains' metrics */
1627 for (int i = 0; i < state->nr_domains; ++i) {
1628 int status = get_domain_metrics(&state->domains[i]);
1630 ERROR(PLUGIN_NAME " failed to get metrics for domain=%s",
1631 virDomainGetName(state->domains[i].ptr));
1634 /* Get block device stats for each domain. */
1635 for (int i = 0; i < state->nr_block_devices; ++i) {
1636 int status = get_block_stats(&state->block_devices[i]);
1639 " failed to get stats for block device (%s) in domain %s",
1640 state->block_devices[i].path,
1641 virDomainGetName(state->domains[i].ptr));
1644 /* Get interface stats for each domain. */
1645 for (int i = 0; i < state->nr_interface_devices; ++i) {
1646 int status = get_if_dev_stats(&state->interface_devices[i]);
1649 " failed to get interface stats for device (%s) in domain %s",
1650 state->interface_devices[i].path,
1651 virDomainGetName(state->interface_devices[i].dom));
1657 static int lv_init_instance(size_t i, plugin_read_cb callback) {
1658 struct lv_user_data *lv_ud = &(lv_read_user_data[i]);
1659 struct lv_read_instance *inst = &(lv_ud->inst);
1661 memset(lv_ud, 0, sizeof(*lv_ud));
1663 snprintf(inst->tag, sizeof(inst->tag), "%s-%zu", PLUGIN_NAME, i);
1666 user_data_t *ud = &(lv_ud->ud);
1668 ud->free_func = NULL;
1670 INFO(PLUGIN_NAME " plugin: reader %s initialized", inst->tag);
1671 return plugin_register_complex_read(NULL, inst->tag, callback, 0, ud);
1674 static void lv_clean_read_state(struct lv_read_state *state) {
1675 free_block_devices(state);
1676 free_interface_devices(state);
1677 free_domains(state);
1680 static void lv_fini_instance(size_t i) {
1681 struct lv_read_instance *inst = &(lv_read_user_data[i].inst);
1682 struct lv_read_state *state = &(inst->read_state);
1684 lv_clean_read_state(state);
1685 INFO(PLUGIN_NAME " plugin: reader %s finalized", inst->tag);
1688 static int lv_init(void) {
1689 if (virInitialize() != 0)
1692 if (lv_connect() != 0)
1695 DEBUG(PLUGIN_NAME " plugin: starting %i instances", nr_instances);
1697 for (int i = 0; i < nr_instances; ++i)
1698 lv_init_instance(i, lv_read);
1704 * returns 0 on success and <0 on error
1706 static int lv_domain_get_tag(xmlXPathContextPtr xpath_ctx, const char *dom_name,
1708 char xpath_str[BUFFER_MAX_LEN] = {'\0'};
1709 xmlXPathObjectPtr xpath_obj = NULL;
1710 xmlNodePtr xml_node = NULL;
1714 err = xmlXPathRegisterNs(xpath_ctx,
1715 (const xmlChar *)METADATA_VM_PARTITION_PREFIX,
1716 (const xmlChar *)METADATA_VM_PARTITION_URI);
1718 ERROR(PLUGIN_NAME " plugin: xmlXpathRegisterNs(%s, %s) failed on domain %s",
1719 METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_URI, dom_name);
1723 snprintf(xpath_str, sizeof(xpath_str), "/domain/metadata/%s:%s/text()",
1724 METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_ELEMENT);
1725 xpath_obj = xmlXPathEvalExpression((xmlChar *)xpath_str, xpath_ctx);
1726 if (xpath_obj == NULL) {
1727 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) failed on domain %s",
1728 xpath_str, dom_name);
1732 if (xpath_obj->type != XPATH_NODESET) {
1733 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) unexpected return type %d "
1734 "(wanted %d) on domain %s",
1735 xpath_str, xpath_obj->type, XPATH_NODESET, dom_name);
1740 * from now on there is no real error, it's ok if a domain
1741 * doesn't have the metadata partition tag.
1744 if (xpath_obj->nodesetval == NULL || xpath_obj->nodesetval->nodeNr != 1) {
1745 DEBUG(PLUGIN_NAME " plugin: xmlXPathEval(%s) return nodeset size=%i "
1746 "expected=1 on domain %s",
1748 (xpath_obj->nodesetval == NULL) ? 0 : xpath_obj->nodesetval->nodeNr,
1751 xml_node = xpath_obj->nodesetval->nodeTab[0];
1752 sstrncpy(dom_tag, (const char *)xml_node->content, PARTITION_TAG_MAX_LEN);
1756 /* deregister to clean up */
1757 err = xmlXPathRegisterNs(xpath_ctx,
1758 (const xmlChar *)METADATA_VM_PARTITION_PREFIX, NULL);
1760 /* we can't really recover here */
1762 " plugin: deregistration of namespace %s failed for domain %s",
1763 METADATA_VM_PARTITION_PREFIX, dom_name);
1766 xmlXPathFreeObject(xpath_obj);
1771 static int is_known_tag(const char *dom_tag) {
1772 for (int i = 0; i < nr_instances; ++i)
1773 if (!strcmp(dom_tag, lv_read_user_data[i].inst.tag))
1778 static int lv_instance_include_domain(struct lv_read_instance *inst,
1779 const char *dom_name,
1780 const char *dom_tag) {
1781 if ((dom_tag[0] != '\0') && (strcmp(dom_tag, inst->tag) == 0))
1784 /* instance#0 will always be there, so it is in charge of extra duties */
1785 if (inst->id == 0) {
1786 if (dom_tag[0] == '\0' || !is_known_tag(dom_tag)) {
1787 DEBUG(PLUGIN_NAME " plugin#%s: refreshing domain %s "
1788 "with unknown tag '%s'",
1789 inst->tag, dom_name, dom_tag);
1798 virConnectListAllDomains() appeared in 0.10.2
1799 Note that LIBVIR_CHECK_VERSION appeared a year later, so
1800 in some systems which actually have virConnectListAllDomains()
1801 we can't detect this.
1803 #ifdef LIBVIR_CHECK_VERSION
1804 #if LIBVIR_CHECK_VERSION(0, 10, 2)
1805 #define HAVE_LIST_ALL_DOMAINS 1
1809 static int refresh_lists(struct lv_read_instance *inst) {
1810 struct lv_read_state *state = &inst->read_state;
1813 n = virConnectNumOfDomains(conn);
1815 VIRT_ERROR(conn, "reading number of domains");
1819 lv_clean_read_state(state);
1822 #ifdef HAVE_LIST_ALL_DOMAINS
1823 virDomainPtr *domains;
1824 n = virConnectListAllDomains(conn, &domains,
1825 VIR_CONNECT_LIST_DOMAINS_ACTIVE);
1829 /* Get list of domains. */
1830 domids = malloc(sizeof(*domids) * n);
1831 if (domids == NULL) {
1832 ERROR(PLUGIN_NAME " plugin: malloc failed.");
1836 n = virConnectListDomains(conn, domids, n);
1840 VIRT_ERROR(conn, "reading list of domains");
1841 #ifndef HAVE_LIST_ALL_DOMAINS
1847 /* Fetch each domain and add it to the list, unless ignore. */
1848 for (int i = 0; i < n; ++i) {
1851 xmlDocPtr xml_doc = NULL;
1852 xmlXPathContextPtr xpath_ctx = NULL;
1853 xmlXPathObjectPtr xpath_obj = NULL;
1854 char tag[PARTITION_TAG_MAX_LEN] = {'\0'};
1858 #ifdef HAVE_LIST_ALL_DOMAINS
1859 virDomainPtr dom = domains[i];
1861 virDomainPtr dom = NULL;
1862 dom = virDomainLookupByID(conn, domids[i]);
1864 VIRT_ERROR(conn, "virDomainLookupByID");
1865 /* Could be that the domain went away -- ignore it anyway. */
1870 name = virDomainGetName(dom);
1872 VIRT_ERROR(conn, "virDomainGetName");
1876 status = virDomainGetInfo(dom, &info);
1878 ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
1883 if (info.state != VIR_DOMAIN_RUNNING) {
1884 DEBUG(PLUGIN_NAME " plugin: skipping inactive domain %s", name);
1888 if (il_domains && ignorelist_match(il_domains, name) != 0)
1891 /* Get a list of devices for this domain. */
1892 xml = virDomainGetXMLDesc(dom, 0);
1894 VIRT_ERROR(conn, "virDomainGetXMLDesc");
1898 /* Yuck, XML. Parse out the devices. */
1899 xml_doc = xmlReadDoc((xmlChar *)xml, NULL, NULL, XML_PARSE_NONET);
1900 if (xml_doc == NULL) {
1901 VIRT_ERROR(conn, "xmlReadDoc");
1905 xpath_ctx = xmlXPathNewContext(xml_doc);
1907 if (lv_domain_get_tag(xpath_ctx, name, tag) < 0) {
1908 ERROR(PLUGIN_NAME " plugin: lv_domain_get_tag failed.");
1912 if (!lv_instance_include_domain(inst, name, tag))
1915 if (add_domain(state, dom) < 0) {
1916 ERROR(PLUGIN_NAME " plugin: malloc failed.");
1920 /* Block devices. */
1921 const char *bd_xmlpath = "/domain/devices/disk/target[@dev]";
1922 if (blockdevice_format == source)
1923 bd_xmlpath = "/domain/devices/disk/source[@dev]";
1924 xpath_obj = xmlXPathEval((const xmlChar *)bd_xmlpath, xpath_ctx);
1926 if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
1927 xpath_obj->nodesetval == NULL)
1930 for (int j = 0; j < xpath_obj->nodesetval->nodeNr; ++j) {
1934 node = xpath_obj->nodesetval->nodeTab[j];
1937 path = (char *)xmlGetProp(node, (xmlChar *)"dev");
1941 if (il_block_devices &&
1942 ignore_device_match(il_block_devices, name, path) != 0)
1945 add_block_device(state, dom, path);
1950 xmlXPathFreeObject(xpath_obj);
1952 /* Network interfaces. */
1953 xpath_obj = xmlXPathEval(
1954 (xmlChar *)"/domain/devices/interface[target[@dev]]", xpath_ctx);
1955 if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
1956 xpath_obj->nodesetval == NULL)
1959 xmlNodeSetPtr xml_interfaces = xpath_obj->nodesetval;
1961 for (int j = 0; j < xml_interfaces->nodeNr; ++j) {
1963 char *address = NULL;
1964 xmlNodePtr xml_interface;
1966 xml_interface = xml_interfaces->nodeTab[j];
1970 for (xmlNodePtr child = xml_interface->children; child;
1971 child = child->next) {
1972 if (child->type != XML_ELEMENT_NODE)
1975 if (xmlStrEqual(child->name, (const xmlChar *)"target")) {
1976 path = (char *)xmlGetProp(child, (const xmlChar *)"dev");
1979 } else if (xmlStrEqual(child->name, (const xmlChar *)"mac")) {
1980 address = (char *)xmlGetProp(child, (const xmlChar *)"address");
1986 if (il_interface_devices &&
1987 (ignore_device_match(il_interface_devices, name, path) != 0 ||
1988 ignore_device_match(il_interface_devices, name, address) != 0))
1991 add_interface_device(state, dom, path, address, j + 1);
2001 xmlXPathFreeObject(xpath_obj);
2003 xmlXPathFreeContext(xpath_ctx);
2005 xmlFreeDoc(xml_doc);
2009 #ifdef HAVE_LIST_ALL_DOMAINS
2016 DEBUG(PLUGIN_NAME " plugin#%s: refreshing"
2017 " domains=%i block_devices=%i iface_devices=%i",
2018 inst->tag, state->nr_domains, state->nr_block_devices,
2019 state->nr_interface_devices);
2024 static void free_domains(struct lv_read_state *state) {
2025 if (state->domains) {
2026 for (int i = 0; i < state->nr_domains; ++i)
2027 virDomainFree(state->domains[i].ptr);
2028 sfree(state->domains);
2030 state->domains = NULL;
2031 state->nr_domains = 0;
2034 static int add_domain(struct lv_read_state *state, virDomainPtr dom) {
2036 int new_size = sizeof(state->domains[0]) * (state->nr_domains + 1);
2039 new_ptr = realloc(state->domains, new_size);
2041 new_ptr = malloc(new_size);
2043 if (new_ptr == NULL)
2046 state->domains = new_ptr;
2047 state->domains[state->nr_domains].ptr = dom;
2048 memset(&state->domains[state->nr_domains].info, 0,
2049 sizeof(state->domains[state->nr_domains].info));
2051 return state->nr_domains++;
2054 static void free_block_devices(struct lv_read_state *state) {
2055 if (state->block_devices) {
2056 for (int i = 0; i < state->nr_block_devices; ++i)
2057 sfree(state->block_devices[i].path);
2058 sfree(state->block_devices);
2060 state->block_devices = NULL;
2061 state->nr_block_devices = 0;
2064 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
2066 struct block_device *new_ptr;
2068 sizeof(state->block_devices[0]) * (state->nr_block_devices + 1);
2071 path_copy = strdup(path);
2075 if (state->block_devices)
2076 new_ptr = realloc(state->block_devices, new_size);
2078 new_ptr = malloc(new_size);
2080 if (new_ptr == NULL) {
2084 state->block_devices = new_ptr;
2085 state->block_devices[state->nr_block_devices].dom = dom;
2086 state->block_devices[state->nr_block_devices].path = path_copy;
2087 return state->nr_block_devices++;
2090 static void free_interface_devices(struct lv_read_state *state) {
2091 if (state->interface_devices) {
2092 for (int i = 0; i < state->nr_interface_devices; ++i) {
2093 sfree(state->interface_devices[i].path);
2094 sfree(state->interface_devices[i].address);
2095 sfree(state->interface_devices[i].number);
2097 sfree(state->interface_devices);
2099 state->interface_devices = NULL;
2100 state->nr_interface_devices = 0;
2103 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
2104 const char *path, const char *address,
2105 unsigned int number) {
2106 struct interface_device *new_ptr;
2108 sizeof(state->interface_devices[0]) * (state->nr_interface_devices + 1);
2109 char *path_copy, *address_copy, number_string[15];
2111 if ((path == NULL) || (address == NULL))
2114 path_copy = strdup(path);
2118 address_copy = strdup(address);
2119 if (!address_copy) {
2124 snprintf(number_string, sizeof(number_string), "interface-%u", number);
2126 if (state->interface_devices)
2127 new_ptr = realloc(state->interface_devices, new_size);
2129 new_ptr = malloc(new_size);
2131 if (new_ptr == NULL) {
2133 sfree(address_copy);
2136 state->interface_devices = new_ptr;
2137 state->interface_devices[state->nr_interface_devices].dom = dom;
2138 state->interface_devices[state->nr_interface_devices].path = path_copy;
2139 state->interface_devices[state->nr_interface_devices].address = address_copy;
2140 state->interface_devices[state->nr_interface_devices].number =
2141 strdup(number_string);
2142 return state->nr_interface_devices++;
2145 static int ignore_device_match(ignorelist_t *il, const char *domname,
2146 const char *devpath) {
2150 if ((domname == NULL) || (devpath == NULL))
2153 n = strlen(domname) + strlen(devpath) + 2;
2156 ERROR(PLUGIN_NAME " plugin: malloc failed.");
2159 snprintf(name, n, "%s:%s", domname, devpath);
2160 r = ignorelist_match(il, name);
2165 static int lv_shutdown(void) {
2166 for (int i = 0; i < nr_instances; ++i) {
2167 lv_fini_instance(i);
2172 ignorelist_free(il_domains);
2174 ignorelist_free(il_block_devices);
2175 il_block_devices = NULL;
2176 ignorelist_free(il_interface_devices);
2177 il_interface_devices = NULL;
2182 void module_register(void) {
2183 plugin_register_config(PLUGIN_NAME, lv_config, config_keys, NR_CONFIG_KEYS);
2184 plugin_register_init(PLUGIN_NAME, lv_init);
2185 plugin_register_shutdown(PLUGIN_NAME, lv_shutdown);