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>
40 #define PLUGIN_NAME "virt"
42 /* Secure strcat macro assuring null termination. Parameter (n) is the size of
43 buffer (d), allowing this macro to be safe for static and dynamic buffers */
44 #define SSTRNCAT(d, s, n) \
46 size_t _l = strlen(d); \
47 sstrncpy((d) + _l, (s), (n)-_l); \
50 #ifdef LIBVIR_CHECK_VERSION
52 #if LIBVIR_CHECK_VERSION(0, 9, 2)
53 #define HAVE_DOM_REASON 1
56 #if LIBVIR_CHECK_VERSION(0, 9, 5)
57 #define HAVE_BLOCK_STATS_FLAGS 1
58 #define HAVE_DOM_REASON_PAUSED_SHUTTING_DOWN 1
61 #if LIBVIR_CHECK_VERSION(0, 9, 10)
62 #define HAVE_DISK_ERR 1
65 #if LIBVIR_CHECK_VERSION(0, 9, 11)
66 #define HAVE_CPU_STATS 1
67 #define HAVE_DOM_STATE_PMSUSPENDED 1
68 #define HAVE_DOM_REASON_RUNNING_WAKEUP 1
72 virConnectListAllDomains() appeared in 0.10.2
73 Note that LIBVIR_CHECK_VERSION appeared a year later, so
74 in some systems which actually have virConnectListAllDomains()
77 #if LIBVIR_CHECK_VERSION(0, 10, 2)
78 #define HAVE_LIST_ALL_DOMAINS 1
81 #if LIBVIR_CHECK_VERSION(1, 0, 1)
82 #define HAVE_DOM_REASON_PAUSED_SNAPSHOT 1
85 #if LIBVIR_CHECK_VERSION(1, 1, 1)
86 #define HAVE_DOM_REASON_PAUSED_CRASHED 1
89 #if LIBVIR_CHECK_VERSION(1, 2, 9)
90 #define HAVE_JOB_STATS 1
93 #if LIBVIR_CHECK_VERSION(1, 2, 10)
94 #define HAVE_DOM_REASON_CRASHED 1
97 #if LIBVIR_CHECK_VERSION(1, 2, 11)
98 #define HAVE_FS_INFO 1
101 #if LIBVIR_CHECK_VERSION(1, 2, 15)
102 #define HAVE_DOM_REASON_PAUSED_STARTING_UP 1
105 #if LIBVIR_CHECK_VERSION(1, 3, 3)
106 #define HAVE_PERF_STATS 1
107 #define HAVE_DOM_REASON_POSTCOPY 1
110 #endif /* LIBVIR_CHECK_VERSION */
112 /* structure used for aggregating notification-thread data*/
113 typedef struct virt_notif_thread_s {
114 pthread_t event_loop_tid;
115 int domain_event_cb_id;
116 pthread_mutex_t active_mutex; /* protects 'is_active' member access*/
118 } virt_notif_thread_t;
120 static const char *config_keys[] = {"Connection",
127 "BlockDeviceFormatBasename",
132 "HostnameMetadataNS",
133 "HostnameMetadataXPath",
136 "PluginInstanceFormat",
140 "PersistentNotification",
143 /* PersistentNotification is false by default */
144 static bool persistent_notification = false;
146 /* Thread used for handling libvirt notifications events */
147 static virt_notif_thread_t notif_thread;
149 const char *domain_states[] = {
150 [VIR_DOMAIN_NOSTATE] = "no state",
151 [VIR_DOMAIN_RUNNING] = "the domain is running",
152 [VIR_DOMAIN_BLOCKED] = "the domain is blocked on resource",
153 [VIR_DOMAIN_PAUSED] = "the domain is paused by user",
154 [VIR_DOMAIN_SHUTDOWN] = "the domain is being shut down",
155 [VIR_DOMAIN_SHUTOFF] = "the domain is shut off",
156 [VIR_DOMAIN_CRASHED] = "the domain is crashed",
157 #ifdef HAVE_DOM_STATE_PMSUSPENDED
158 [VIR_DOMAIN_PMSUSPENDED] =
159 "the domain is suspended by guest power management",
163 static int map_domain_event_to_state(int event) {
166 case VIR_DOMAIN_EVENT_STARTED:
167 ret = VIR_DOMAIN_RUNNING;
169 case VIR_DOMAIN_EVENT_SUSPENDED:
170 ret = VIR_DOMAIN_PAUSED;
172 case VIR_DOMAIN_EVENT_RESUMED:
173 ret = VIR_DOMAIN_RUNNING;
175 case VIR_DOMAIN_EVENT_STOPPED:
176 ret = VIR_DOMAIN_SHUTOFF;
178 case VIR_DOMAIN_EVENT_SHUTDOWN:
179 ret = VIR_DOMAIN_SHUTDOWN;
181 #ifdef HAVE_DOM_STATE_PMSUSPENDED
182 case VIR_DOMAIN_EVENT_PMSUSPENDED:
183 ret = VIR_DOMAIN_PMSUSPENDED;
186 #ifdef HAVE_DOM_REASON_CRASHED
187 case VIR_DOMAIN_EVENT_CRASHED:
188 ret = VIR_DOMAIN_CRASHED;
192 ret = VIR_DOMAIN_NOSTATE;
197 #ifdef HAVE_DOM_REASON
198 static int map_domain_event_detail_to_reason(int event, int detail) {
201 case VIR_DOMAIN_EVENT_STARTED:
203 case VIR_DOMAIN_EVENT_STARTED_BOOTED: /* Normal startup from boot */
204 ret = VIR_DOMAIN_RUNNING_BOOTED;
206 case VIR_DOMAIN_EVENT_STARTED_MIGRATED: /* Incoming migration from another
208 ret = VIR_DOMAIN_RUNNING_MIGRATED;
210 case VIR_DOMAIN_EVENT_STARTED_RESTORED: /* Restored from a state file */
211 ret = VIR_DOMAIN_RUNNING_RESTORED;
213 case VIR_DOMAIN_EVENT_STARTED_FROM_SNAPSHOT: /* Restored from snapshot */
214 ret = VIR_DOMAIN_RUNNING_FROM_SNAPSHOT;
216 #ifdef HAVE_DOM_REASON_RUNNING_WAKEUP
217 case VIR_DOMAIN_EVENT_STARTED_WAKEUP: /* Started due to wakeup event */
218 ret = VIR_DOMAIN_RUNNING_WAKEUP;
222 ret = VIR_DOMAIN_RUNNING_UNKNOWN;
225 case VIR_DOMAIN_EVENT_SUSPENDED:
227 case VIR_DOMAIN_EVENT_SUSPENDED_PAUSED: /* Normal suspend due to admin
229 ret = VIR_DOMAIN_PAUSED_USER;
231 case VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED: /* Suspended for offline
233 ret = VIR_DOMAIN_PAUSED_MIGRATION;
235 case VIR_DOMAIN_EVENT_SUSPENDED_IOERROR: /* Suspended due to a disk I/O
237 ret = VIR_DOMAIN_PAUSED_IOERROR;
239 case VIR_DOMAIN_EVENT_SUSPENDED_WATCHDOG: /* Suspended due to a watchdog
241 ret = VIR_DOMAIN_PAUSED_WATCHDOG;
243 case VIR_DOMAIN_EVENT_SUSPENDED_RESTORED: /* Restored from paused state
245 ret = VIR_DOMAIN_PAUSED_UNKNOWN;
247 case VIR_DOMAIN_EVENT_SUSPENDED_FROM_SNAPSHOT: /* Restored from paused
249 ret = VIR_DOMAIN_PAUSED_FROM_SNAPSHOT;
251 case VIR_DOMAIN_EVENT_SUSPENDED_API_ERROR: /* Suspended after failure during
253 ret = VIR_DOMAIN_PAUSED_UNKNOWN;
255 #ifdef HAVE_DOM_REASON_POSTCOPY
256 case VIR_DOMAIN_EVENT_SUSPENDED_POSTCOPY: /* Suspended for post-copy
258 ret = VIR_DOMAIN_PAUSED_POSTCOPY;
260 case VIR_DOMAIN_EVENT_SUSPENDED_POSTCOPY_FAILED: /* Suspended after failed
262 ret = VIR_DOMAIN_PAUSED_POSTCOPY_FAILED;
266 ret = VIR_DOMAIN_PAUSED_UNKNOWN;
269 case VIR_DOMAIN_EVENT_RESUMED:
271 case VIR_DOMAIN_EVENT_RESUMED_UNPAUSED: /* Normal resume due to admin
273 ret = VIR_DOMAIN_RUNNING_UNPAUSED;
275 case VIR_DOMAIN_EVENT_RESUMED_MIGRATED: /* Resumed for completion of
277 ret = VIR_DOMAIN_RUNNING_MIGRATED;
279 case VIR_DOMAIN_EVENT_RESUMED_FROM_SNAPSHOT: /* Resumed from snapshot */
280 ret = VIR_DOMAIN_RUNNING_FROM_SNAPSHOT;
282 #ifdef HAVE_DOM_REASON_POSTCOPY
283 case VIR_DOMAIN_EVENT_RESUMED_POSTCOPY: /* Resumed, but migration is still
284 running in post-copy mode */
285 ret = VIR_DOMAIN_RUNNING_POSTCOPY;
289 ret = VIR_DOMAIN_RUNNING_UNKNOWN;
292 case VIR_DOMAIN_EVENT_STOPPED:
294 case VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN: /* Normal shutdown */
295 ret = VIR_DOMAIN_SHUTOFF_SHUTDOWN;
297 case VIR_DOMAIN_EVENT_STOPPED_DESTROYED: /* Forced poweroff from host */
298 ret = VIR_DOMAIN_SHUTOFF_DESTROYED;
300 case VIR_DOMAIN_EVENT_STOPPED_CRASHED: /* Guest crashed */
301 ret = VIR_DOMAIN_SHUTOFF_CRASHED;
303 case VIR_DOMAIN_EVENT_STOPPED_MIGRATED: /* Migrated off to another host */
304 ret = VIR_DOMAIN_SHUTOFF_MIGRATED;
306 case VIR_DOMAIN_EVENT_STOPPED_SAVED: /* Saved to a state file */
307 ret = VIR_DOMAIN_SHUTOFF_SAVED;
309 case VIR_DOMAIN_EVENT_STOPPED_FAILED: /* Host emulator/mgmt failed */
310 ret = VIR_DOMAIN_SHUTOFF_FAILED;
312 case VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT: /* Offline snapshot loaded */
313 ret = VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT;
316 ret = VIR_DOMAIN_SHUTOFF_UNKNOWN;
319 case VIR_DOMAIN_EVENT_SHUTDOWN:
321 case VIR_DOMAIN_EVENT_SHUTDOWN_FINISHED: /* Guest finished shutdown
323 ret = VIR_DOMAIN_SHUTDOWN_USER;
326 ret = VIR_DOMAIN_SHUTDOWN_UNKNOWN;
329 #ifdef HAVE_DOM_STATE_PMSUSPENDED
330 case VIR_DOMAIN_EVENT_PMSUSPENDED:
332 case VIR_DOMAIN_EVENT_PMSUSPENDED_MEMORY: /* Guest was PM suspended to
334 ret = VIR_DOMAIN_PMSUSPENDED_UNKNOWN;
336 case VIR_DOMAIN_EVENT_PMSUSPENDED_DISK: /* Guest was PM suspended to disk */
337 ret = VIR_DOMAIN_PMSUSPENDED_DISK_UNKNOWN;
340 ret = VIR_DOMAIN_PMSUSPENDED_UNKNOWN;
344 case VIR_DOMAIN_EVENT_CRASHED:
346 case VIR_DOMAIN_EVENT_CRASHED_PANICKED: /* Guest was panicked */
347 ret = VIR_DOMAIN_CRASHED_PANICKED;
350 ret = VIR_DOMAIN_CRASHED_UNKNOWN;
354 ret = VIR_DOMAIN_NOSTATE_UNKNOWN;
359 #define DOMAIN_STATE_REASON_MAX_SIZE 20
360 const char *domain_reasons[][DOMAIN_STATE_REASON_MAX_SIZE] = {
361 [VIR_DOMAIN_NOSTATE][VIR_DOMAIN_NOSTATE_UNKNOWN] =
362 "the reason is unknown",
364 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_UNKNOWN] =
365 "the reason is unknown",
366 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_BOOTED] =
367 "normal startup from boot",
368 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_MIGRATED] =
369 "migrated from another host",
370 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_RESTORED] =
371 "restored from a state file",
372 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_FROM_SNAPSHOT] =
373 "restored from snapshot",
374 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_UNPAUSED] =
375 "returned from paused state",
376 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_MIGRATION_CANCELED] =
377 "returned from migration",
378 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_SAVE_CANCELED] =
379 "returned from failed save process",
380 #ifdef HAVE_DOM_REASON_RUNNING_WAKEUP
381 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_WAKEUP] =
382 "returned from pmsuspended due to wakeup event",
384 #ifdef HAVE_DOM_REASON_CRASHED
385 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_CRASHED] =
386 "resumed from crashed",
388 #ifdef HAVE_DOM_REASON_POSTCOPY
389 [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_POSTCOPY] =
390 "running in post-copy migration mode",
392 [VIR_DOMAIN_BLOCKED][VIR_DOMAIN_BLOCKED_UNKNOWN] =
393 "the reason is unknown",
395 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_UNKNOWN] =
396 "the reason is unknown",
397 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_USER] = "paused on user request",
398 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_MIGRATION] =
399 "paused for offline migration",
400 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_SAVE] = "paused for save",
401 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_DUMP] =
402 "paused for offline core dump",
403 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_IOERROR] =
404 "paused due to a disk I/O error",
405 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_WATCHDOG] =
406 "paused due to a watchdog event",
407 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_FROM_SNAPSHOT] =
408 "paused after restoring from snapshot",
409 #ifdef HAVE_DOM_REASON_PAUSED_SHUTTING_DOWN
410 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_SHUTTING_DOWN] =
411 "paused during shutdown process",
413 #ifdef HAVE_DOM_REASON_PAUSED_SNAPSHOT
414 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_SNAPSHOT] =
415 "paused while creating a snapshot",
417 #ifdef HAVE_DOM_REASON_PAUSED_CRASHED
418 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_CRASHED] =
419 "paused due to a guest crash",
421 #ifdef HAVE_DOM_REASON_PAUSED_STARTING_UP
422 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_STARTING_UP] =
423 "the domain is being started",
425 #ifdef HAVE_DOM_REASON_POSTCOPY
426 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_POSTCOPY] =
427 "paused for post-copy migration",
428 [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_POSTCOPY_FAILED] =
429 "paused after failed post-copy",
431 [VIR_DOMAIN_SHUTDOWN][VIR_DOMAIN_SHUTDOWN_UNKNOWN] =
432 "the reason is unknown",
433 [VIR_DOMAIN_SHUTDOWN][VIR_DOMAIN_SHUTDOWN_USER] =
434 "shutting down on user request",
436 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_UNKNOWN] =
437 "the reason is unknown",
438 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_SHUTDOWN] = "normal shutdown",
439 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_DESTROYED] = "forced poweroff",
440 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_CRASHED] = "domain crashed",
441 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_MIGRATED] =
442 "migrated to another host",
443 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_SAVED] = "saved to a file",
444 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_FAILED] =
445 "domain failed to start",
446 [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT] =
447 "restored from a snapshot which was taken while domain was shutoff",
449 [VIR_DOMAIN_CRASHED][VIR_DOMAIN_CRASHED_UNKNOWN] =
450 "the reason is unknown",
451 #ifdef VIR_DOMAIN_CRASHED_PANICKED
452 [VIR_DOMAIN_CRASHED][VIR_DOMAIN_CRASHED_PANICKED] = "domain panicked",
455 #ifdef HAVE_DOM_STATE_PMSUSPENDED
456 [VIR_DOMAIN_PMSUSPENDED][VIR_DOMAIN_PMSUSPENDED_UNKNOWN] =
457 "the reason is unknown",
460 #endif /* HAVE_DOM_REASON */
462 #define NR_CONFIG_KEYS ((sizeof config_keys / sizeof config_keys[0]) - 1)
463 #define NANOSEC_IN_SEC 1e9
465 #define GET_STATS(_f, _name, ...) \
467 status = _f(__VA_ARGS__); \
469 ERROR(PLUGIN_NAME " plugin: Failed to get " _name); \
473 static virConnectPtr conn;
474 static char *conn_string;
475 static c_complain_t conn_complain = C_COMPLAIN_INIT_STATIC;
477 /* Node information required for %CPU */
478 static virNodeInfo nodeinfo;
480 /* Seconds between list refreshes, 0 disables completely. */
481 static int interval = 60;
483 /* List of domains, if specified. */
484 static ignorelist_t *il_domains;
485 /* List of block devices, if specified. */
486 static ignorelist_t *il_block_devices;
487 /* List of network interface devices, if specified. */
488 static ignorelist_t *il_interface_devices;
490 static int ignore_device_match(ignorelist_t *, const char *domname,
491 const char *devpath);
493 /* Actual list of block devices found on last refresh. */
494 struct block_device {
495 virDomainPtr dom; /* domain */
496 char *path; /* name of block device */
499 /* Actual list of network interfaces found on last refresh. */
500 struct interface_device {
501 virDomainPtr dom; /* domain */
502 char *path; /* name of interface device */
503 char *address; /* mac address of interface device */
504 char *number; /* interface device number */
507 typedef struct domain_s {
513 struct lv_read_state {
514 /* Actual list of domains found on last refresh. */
518 struct block_device *block_devices;
519 int nr_block_devices;
521 struct interface_device *interface_devices;
522 int nr_interface_devices;
525 static void free_domains(struct lv_read_state *state);
526 static int add_domain(struct lv_read_state *state, virDomainPtr dom,
529 static void free_block_devices(struct lv_read_state *state);
530 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
533 static void free_interface_devices(struct lv_read_state *state);
534 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
535 const char *path, const char *address,
536 unsigned int number);
538 #define METADATA_VM_PARTITION_URI "http://ovirt.org/ovirtmap/tag/1.0"
539 #define METADATA_VM_PARTITION_ELEMENT "tag"
540 #define METADATA_VM_PARTITION_PREFIX "ovirtmap"
542 #define BUFFER_MAX_LEN 256
543 #define PARTITION_TAG_MAX_LEN 32
545 struct lv_read_instance {
546 struct lv_read_state read_state;
547 char tag[PARTITION_TAG_MAX_LEN];
551 struct lv_user_data {
552 struct lv_read_instance inst;
556 #define NR_INSTANCES_DEFAULT 1
557 #define NR_INSTANCES_MAX 128
558 static int nr_instances = NR_INSTANCES_DEFAULT;
559 static struct lv_user_data lv_read_user_data[NR_INSTANCES_MAX];
561 /* HostnameFormat. */
562 #define HF_MAX_FIELDS 4
564 enum hf_field { hf_none = 0, hf_hostname, hf_name, hf_uuid, hf_metadata };
566 static enum hf_field hostname_format[HF_MAX_FIELDS] = {hf_name};
568 /* PluginInstanceFormat */
569 #define PLGINST_MAX_FIELDS 3
578 static enum plginst_field plugin_instance_format[PLGINST_MAX_FIELDS] = {
581 /* HostnameMetadataNS && HostnameMetadataXPath */
582 static char *hm_xpath;
585 /* BlockDeviceFormat */
586 enum bd_field { target, source };
588 /* InterfaceFormat. */
589 enum if_field { if_address, if_name, if_number };
592 #define EX_STATS_MAX_FIELDS 15
595 ex_stats_disk = 1 << 0,
596 ex_stats_pcpu = 1 << 1,
597 ex_stats_cpu_util = 1 << 2,
598 ex_stats_domain_state = 1 << 3,
599 #ifdef HAVE_PERF_STATS
600 ex_stats_perf = 1 << 4,
602 ex_stats_vcpupin = 1 << 5,
604 ex_stats_disk_err = 1 << 6,
607 ex_stats_fs_info = 1 << 7,
609 #ifdef HAVE_JOB_STATS
610 ex_stats_job_stats_completed = 1 << 8,
611 ex_stats_job_stats_background = 1 << 9,
615 static unsigned int extra_stats = ex_stats_none;
617 struct ex_stats_item {
621 static const struct ex_stats_item ex_stats_table[] = {
622 {"disk", ex_stats_disk},
623 {"pcpu", ex_stats_pcpu},
624 {"cpu_util", ex_stats_cpu_util},
625 {"domain_state", ex_stats_domain_state},
626 #ifdef HAVE_PERF_STATS
627 {"perf", ex_stats_perf},
629 {"vcpupin", ex_stats_vcpupin},
631 {"disk_err", ex_stats_disk_err},
634 {"fs_info", ex_stats_fs_info},
636 #ifdef HAVE_JOB_STATS
637 {"job_stats_completed", ex_stats_job_stats_completed},
638 {"job_stats_background", ex_stats_job_stats_background},
640 {NULL, ex_stats_none},
643 /* BlockDeviceFormatBasename */
644 static bool blockdevice_format_basename;
645 static enum bd_field blockdevice_format = target;
646 static enum if_field interface_format = if_name;
648 /* Time that we last refreshed. */
649 static time_t last_refresh = (time_t)0;
651 static int refresh_lists(struct lv_read_instance *inst);
653 struct lv_block_info {
654 virDomainBlockStatsStruct bi;
656 long long rd_total_times;
657 long long wr_total_times;
660 long long fl_total_times;
663 static void init_block_info(struct lv_block_info *binfo) {
667 binfo->bi.rd_req = -1;
668 binfo->bi.wr_req = -1;
669 binfo->bi.rd_bytes = -1;
670 binfo->bi.wr_bytes = -1;
672 binfo->rd_total_times = -1;
673 binfo->wr_total_times = -1;
675 binfo->fl_total_times = -1;
678 #ifdef HAVE_BLOCK_STATS_FLAGS
680 #define GET_BLOCK_INFO_VALUE(NAME, FIELD) \
681 if (!strcmp(param[i].field, NAME)) { \
682 binfo->FIELD = param[i].value.l; \
686 static int get_block_info(struct lv_block_info *binfo,
687 virTypedParameterPtr param, int nparams) {
688 if (binfo == NULL || param == NULL)
691 for (int i = 0; i < nparams; ++i) {
692 /* ignore type. Everything must be LLONG anyway. */
693 GET_BLOCK_INFO_VALUE("rd_operations", bi.rd_req);
694 GET_BLOCK_INFO_VALUE("wr_operations", bi.wr_req);
695 GET_BLOCK_INFO_VALUE("rd_bytes", bi.rd_bytes);
696 GET_BLOCK_INFO_VALUE("wr_bytes", bi.wr_bytes);
697 GET_BLOCK_INFO_VALUE("rd_total_times", rd_total_times);
698 GET_BLOCK_INFO_VALUE("wr_total_times", wr_total_times);
699 GET_BLOCK_INFO_VALUE("flush_operations", fl_req);
700 GET_BLOCK_INFO_VALUE("flush_total_times", fl_total_times);
706 #undef GET_BLOCK_INFO_VALUE
708 #endif /* HAVE_BLOCK_STATS_FLAGS */
710 /* ERROR(...) macro for virterrors. */
711 #define VIRT_ERROR(conn, s) \
714 err = (conn) ? virConnGetLastError((conn)) : virGetLastError(); \
716 ERROR(PLUGIN_NAME " plugin: %s failed: %s", (s), err->message); \
719 char *metadata_get_hostname(virDomainPtr dom) {
720 const char *xpath_str = NULL;
721 if (hm_xpath == NULL)
722 xpath_str = "/instance/name/text()";
724 xpath_str = hm_xpath;
726 const char *namespace = NULL;
728 namespace = "http://openstack.org/xmlns/libvirt/nova/1.0";
733 char *metadata_str = virDomainGetMetadata(
734 dom, VIR_DOMAIN_METADATA_ELEMENT, namespace, VIR_DOMAIN_AFFECT_CURRENT);
735 if (metadata_str == NULL) {
739 char *hostname = NULL;
740 xmlXPathContextPtr xpath_ctx = NULL;
741 xmlXPathObjectPtr xpath_obj = NULL;
742 xmlNodePtr xml_node = NULL;
745 xmlReadDoc((xmlChar *)metadata_str, NULL, NULL, XML_PARSE_NONET);
746 if (xml_doc == NULL) {
747 ERROR(PLUGIN_NAME " plugin: xmlReadDoc failed to read metadata");
751 xpath_ctx = xmlXPathNewContext(xml_doc);
752 if (xpath_ctx == NULL) {
753 ERROR(PLUGIN_NAME " plugin: xmlXPathNewContext(%s) failed for metadata",
757 xpath_obj = xmlXPathEval((xmlChar *)xpath_str, xpath_ctx);
758 if (xpath_obj == NULL) {
759 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) failed for metadata",
764 if (xpath_obj->type != XPATH_NODESET) {
765 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) unexpected return type %d "
766 "(wanted %d) for metadata",
767 xpath_str, xpath_obj->type, XPATH_NODESET);
771 // TODO(sileht): We can support || operator by looping on nodes here
772 if (xpath_obj->nodesetval == NULL || xpath_obj->nodesetval->nodeNr != 1) {
773 WARNING(PLUGIN_NAME " plugin: xmlXPathEval(%s) return nodeset size=%i "
774 "expected=1 for metadata",
776 (xpath_obj->nodesetval == NULL) ? 0
777 : xpath_obj->nodesetval->nodeNr);
781 xml_node = xpath_obj->nodesetval->nodeTab[0];
782 if (xml_node->type == XML_TEXT_NODE) {
783 hostname = strdup((const char *)xml_node->content);
784 } else if (xml_node->type == XML_ATTRIBUTE_NODE) {
785 hostname = strdup((const char *)xml_node->children->content);
787 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) unsupported node type %d",
788 xpath_str, xml_node->type);
792 if (hostname == NULL) {
793 ERROR(PLUGIN_NAME " plugin: strdup(%s) hostname failed", xpath_str);
799 xmlXPathFreeObject(xpath_obj);
801 xmlXPathFreeContext(xpath_ctx);
808 static void init_value_list(value_list_t *vl, virDomainPtr dom) {
810 char uuid[VIR_UUID_STRING_BUFLEN];
812 sstrncpy(vl->plugin, PLUGIN_NAME, sizeof(vl->plugin));
816 /* Construct the hostname field according to HostnameFormat. */
817 for (int i = 0; i < HF_MAX_FIELDS; ++i) {
818 if (hostname_format[i] == hf_none)
822 SSTRNCAT(vl->host, ":", sizeof(vl->host));
824 switch (hostname_format[i]) {
828 SSTRNCAT(vl->host, hostname_g, sizeof(vl->host));
831 name = virDomainGetName(dom);
833 SSTRNCAT(vl->host, name, sizeof(vl->host));
836 if (virDomainGetUUIDString(dom, uuid) == 0)
837 SSTRNCAT(vl->host, uuid, sizeof(vl->host));
840 name = metadata_get_hostname(dom);
842 SSTRNCAT(vl->host, name, sizeof(vl->host));
847 /* Construct the plugin instance field according to PluginInstanceFormat. */
848 for (int i = 0; i < PLGINST_MAX_FIELDS; ++i) {
849 if (plugin_instance_format[i] == plginst_none)
853 SSTRNCAT(vl->plugin_instance, ":", sizeof(vl->plugin_instance));
855 switch (plugin_instance_format[i]) {
859 name = virDomainGetName(dom);
861 SSTRNCAT(vl->plugin_instance, name, sizeof(vl->plugin_instance));
864 if (virDomainGetUUIDString(dom, uuid) == 0)
865 SSTRNCAT(vl->plugin_instance, uuid, sizeof(vl->plugin_instance));
867 case plginst_metadata:
868 name = metadata_get_hostname(dom);
870 SSTRNCAT(vl->plugin_instance, name, sizeof(vl->plugin_instance));
875 } /* void init_value_list */
877 static int init_notif(notification_t *notif, const virDomainPtr domain,
878 int severity, const char *msg, const char *type,
879 const char *type_instance) {
880 value_list_t vl = VALUE_LIST_INIT;
883 ERROR(PLUGIN_NAME " plugin: init_notif: NULL pointer");
887 init_value_list(&vl, domain);
888 notification_init(notif, severity, msg, vl.host, vl.plugin,
889 vl.plugin_instance, type, type_instance);
890 notif->time = cdtime();
894 static void submit_notif(const virDomainPtr domain, int severity,
895 const char *msg, const char *type,
896 const char *type_instance) {
897 notification_t notif;
899 init_notif(¬if, domain, severity, msg, type, type_instance);
900 plugin_dispatch_notification(¬if);
902 plugin_notification_meta_free(notif.meta);
905 static void submit(virDomainPtr dom, char const *type,
906 char const *type_instance, value_t *values,
908 value_list_t vl = VALUE_LIST_INIT;
909 init_value_list(&vl, dom);
912 vl.values_len = values_len;
914 sstrncpy(vl.type, type, sizeof(vl.type));
915 if (type_instance != NULL)
916 sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
918 plugin_dispatch_values(&vl);
921 static void memory_submit(virDomainPtr dom, gauge_t value) {
922 submit(dom, "memory", "total", &(value_t){.gauge = value}, 1);
925 static void memory_stats_submit(gauge_t value, virDomainPtr dom,
927 static const char *tags[] = {"swap_in", "swap_out", "major_fault",
928 "minor_fault", "unused", "available",
929 "actual_balloon", "rss", "usable",
932 if ((tag_index < 0) || (tag_index >= (int)STATIC_ARRAY_SIZE(tags))) {
933 ERROR("virt plugin: Array index out of bounds: tag_index = %d", tag_index);
937 submit(dom, "memory", tags[tag_index], &(value_t){.gauge = value}, 1);
940 static void submit_derive2(const char *type, derive_t v0, derive_t v1,
941 virDomainPtr dom, const char *devname) {
943 {.derive = v0}, {.derive = v1},
946 submit(dom, type, devname, values, STATIC_ARRAY_SIZE(values));
947 } /* void submit_derive2 */
949 static double cpu_ns_to_percent(unsigned int node_cpus,
950 unsigned long long cpu_time_old,
951 unsigned long long cpu_time_new) {
952 double percent = 0.0;
953 unsigned long long cpu_time_diff = 0;
954 double time_diff_sec = CDTIME_T_TO_DOUBLE(plugin_get_interval());
956 if (node_cpus != 0 && time_diff_sec != 0 && cpu_time_old != 0) {
957 cpu_time_diff = cpu_time_new - cpu_time_old;
958 percent = ((double)(100 * cpu_time_diff)) /
959 (time_diff_sec * node_cpus * NANOSEC_IN_SEC);
962 DEBUG(PLUGIN_NAME " plugin: node_cpus=%u cpu_time_old=%" PRIu64
963 " cpu_time_new=%" PRIu64 "cpu_time_diff=%" PRIu64
964 " time_diff_sec=%f percent=%f",
965 node_cpus, (uint64_t)cpu_time_old, (uint64_t)cpu_time_new,
966 (uint64_t)cpu_time_diff, time_diff_sec, percent);
971 static void cpu_submit(const domain_t *dom, unsigned long long cpuTime_new) {
976 if (extra_stats & ex_stats_cpu_util) {
977 /* Computing %CPU requires 2 samples of cpuTime */
978 if (dom->info.cpuTime != 0 && cpuTime_new != 0) {
980 submit(dom->ptr, "percent", "virt_cpu_total",
981 &(value_t){.gauge = cpu_ns_to_percent(
982 nodeinfo.cpus, dom->info.cpuTime, cpuTime_new)},
987 submit(dom->ptr, "virt_cpu_total", NULL, &(value_t){.derive = cpuTime_new},
991 static void vcpu_submit(derive_t value, virDomainPtr dom, int vcpu_nr,
993 char type_instance[DATA_MAX_NAME_LEN];
995 snprintf(type_instance, sizeof(type_instance), "%d", vcpu_nr);
996 submit(dom, type, type_instance, &(value_t){.derive = value}, 1);
999 static void disk_submit(struct lv_block_info *binfo, virDomainPtr dom,
1001 char *dev_copy = strdup(dev);
1002 const char *type_instance = dev_copy;
1007 if (blockdevice_format_basename && blockdevice_format == source)
1008 type_instance = basename(dev_copy);
1010 if (!type_instance) {
1015 char flush_type_instance[DATA_MAX_NAME_LEN];
1016 snprintf(flush_type_instance, sizeof(flush_type_instance), "flush-%s",
1019 if ((binfo->bi.rd_req != -1) && (binfo->bi.wr_req != -1))
1020 submit_derive2("disk_ops", (derive_t)binfo->bi.rd_req,
1021 (derive_t)binfo->bi.wr_req, dom, type_instance);
1023 if ((binfo->bi.rd_bytes != -1) && (binfo->bi.wr_bytes != -1))
1024 submit_derive2("disk_octets", (derive_t)binfo->bi.rd_bytes,
1025 (derive_t)binfo->bi.wr_bytes, dom, type_instance);
1027 if (extra_stats & ex_stats_disk) {
1028 if ((binfo->rd_total_times != -1) && (binfo->wr_total_times != -1))
1029 submit_derive2("disk_time", (derive_t)binfo->rd_total_times,
1030 (derive_t)binfo->wr_total_times, dom, type_instance);
1032 if (binfo->fl_req != -1)
1033 submit(dom, "total_requests", flush_type_instance,
1034 &(value_t){.derive = (derive_t)binfo->fl_req}, 1);
1035 if (binfo->fl_total_times != -1) {
1036 derive_t value = binfo->fl_total_times / 1000; // ns -> ms
1037 submit(dom, "total_time_in_ms", flush_type_instance,
1038 &(value_t){.derive = value}, 1);
1045 static unsigned int parse_ex_stats_flags(char **exstats, int numexstats) {
1046 unsigned int ex_stats_flags = ex_stats_none;
1047 for (int i = 0; i < numexstats; i++) {
1048 for (int j = 0; ex_stats_table[j].name != NULL; j++) {
1049 if (strcasecmp(exstats[i], ex_stats_table[j].name) == 0) {
1050 DEBUG(PLUGIN_NAME " plugin: enabling extra stats for '%s'",
1051 ex_stats_table[j].name);
1052 ex_stats_flags |= ex_stats_table[j].flag;
1056 if (ex_stats_table[j + 1].name == NULL) {
1057 ERROR(PLUGIN_NAME " plugin: Unmatched ExtraStats option: %s",
1062 return ex_stats_flags;
1065 static void domain_state_submit_notif(virDomainPtr dom, int state, int reason) {
1066 if ((state < 0) || ((size_t)state >= STATIC_ARRAY_SIZE(domain_states))) {
1067 ERROR(PLUGIN_NAME " plugin: Array index out of bounds: state=%d", state);
1071 char msg[DATA_MAX_NAME_LEN];
1072 const char *state_str = domain_states[state];
1073 #ifdef HAVE_DOM_REASON
1075 ((size_t)reason >= STATIC_ARRAY_SIZE(domain_reasons[0]))) {
1076 ERROR(PLUGIN_NAME " plugin: Array index out of bounds: reason=%d", reason);
1080 const char *reason_str = domain_reasons[state][reason];
1081 /* Array size for domain reasons is fixed, but different domain states can
1082 * have different number of reasons. We need to check if reason was
1083 * successfully parsed */
1085 ERROR(PLUGIN_NAME " plugin: Invalid reason (%d) for domain state: %s",
1090 const char *reason_str = "N/A";
1093 snprintf(msg, sizeof(msg), "Domain state: %s. Reason: %s", state_str,
1098 case VIR_DOMAIN_NOSTATE:
1099 case VIR_DOMAIN_RUNNING:
1100 case VIR_DOMAIN_SHUTDOWN:
1101 case VIR_DOMAIN_SHUTOFF:
1102 severity = NOTIF_OKAY;
1104 case VIR_DOMAIN_BLOCKED:
1105 case VIR_DOMAIN_PAUSED:
1106 #ifdef DOM_STATE_PMSUSPENDED
1107 case VIR_DOMAIN_PMSUSPENDED:
1109 severity = NOTIF_WARNING;
1111 case VIR_DOMAIN_CRASHED:
1112 severity = NOTIF_FAILURE;
1115 ERROR(PLUGIN_NAME " plugin: Unrecognized domain state (%d)", state);
1118 submit_notif(dom, severity, msg, "domain_state", NULL);
1121 static int lv_init_ignorelists() {
1122 if (il_domains == NULL)
1123 il_domains = ignorelist_create(1);
1124 if (il_block_devices == NULL)
1125 il_block_devices = ignorelist_create(1);
1126 if (il_interface_devices == NULL)
1127 il_interface_devices = ignorelist_create(1);
1129 if (!il_domains || !il_block_devices || !il_interface_devices)
1135 static int lv_config(const char *key, const char *value) {
1136 if (virInitialize() != 0)
1139 if (lv_init_ignorelists() != 0)
1142 if (strcasecmp(key, "Connection") == 0) {
1143 char *tmp = strdup(value);
1145 ERROR(PLUGIN_NAME " plugin: Connection strdup failed.");
1153 if (strcasecmp(key, "RefreshInterval") == 0) {
1155 interval = strtol(value, &eptr, 10);
1156 if (eptr == NULL || *eptr != '\0')
1161 if (strcasecmp(key, "Domain") == 0) {
1162 if (ignorelist_add(il_domains, value))
1166 if (strcasecmp(key, "BlockDevice") == 0) {
1167 if (ignorelist_add(il_block_devices, value))
1172 if (strcasecmp(key, "BlockDeviceFormat") == 0) {
1173 if (strcasecmp(value, "target") == 0)
1174 blockdevice_format = target;
1175 else if (strcasecmp(value, "source") == 0)
1176 blockdevice_format = source;
1178 ERROR(PLUGIN_NAME " plugin: unknown BlockDeviceFormat: %s", value);
1183 if (strcasecmp(key, "BlockDeviceFormatBasename") == 0) {
1184 blockdevice_format_basename = IS_TRUE(value) ? true : false;
1187 if (strcasecmp(key, "InterfaceDevice") == 0) {
1188 if (ignorelist_add(il_interface_devices, value))
1193 if (strcasecmp(key, "IgnoreSelected") == 0) {
1194 if (IS_TRUE(value)) {
1195 ignorelist_set_invert(il_domains, 0);
1196 ignorelist_set_invert(il_block_devices, 0);
1197 ignorelist_set_invert(il_interface_devices, 0);
1199 ignorelist_set_invert(il_domains, 1);
1200 ignorelist_set_invert(il_block_devices, 1);
1201 ignorelist_set_invert(il_interface_devices, 1);
1206 if (strcasecmp(key, "HostnameMetadataNS") == 0) {
1207 char *tmp = strdup(value);
1209 ERROR(PLUGIN_NAME " plugin: HostnameMetadataNS strdup failed.");
1217 if (strcasecmp(key, "HostnameMetadataXPath") == 0) {
1218 char *tmp = strdup(value);
1220 ERROR(PLUGIN_NAME " plugin: HostnameMetadataXPath strdup failed.");
1228 if (strcasecmp(key, "HostnameFormat") == 0) {
1229 char *value_copy = strdup(value);
1230 if (value_copy == NULL) {
1231 ERROR(PLUGIN_NAME " plugin: strdup failed.");
1235 char *fields[HF_MAX_FIELDS];
1236 int n = strsplit(value_copy, fields, HF_MAX_FIELDS);
1239 ERROR(PLUGIN_NAME " plugin: HostnameFormat: no fields");
1243 for (int i = 0; i < n; ++i) {
1244 if (strcasecmp(fields[i], "hostname") == 0)
1245 hostname_format[i] = hf_hostname;
1246 else if (strcasecmp(fields[i], "name") == 0)
1247 hostname_format[i] = hf_name;
1248 else if (strcasecmp(fields[i], "uuid") == 0)
1249 hostname_format[i] = hf_uuid;
1250 else if (strcasecmp(fields[i], "metadata") == 0)
1251 hostname_format[i] = hf_metadata;
1253 ERROR(PLUGIN_NAME " plugin: unknown HostnameFormat field: %s",
1261 for (int i = n; i < HF_MAX_FIELDS; ++i)
1262 hostname_format[i] = hf_none;
1267 if (strcasecmp(key, "PluginInstanceFormat") == 0) {
1268 char *value_copy = strdup(value);
1269 if (value_copy == NULL) {
1270 ERROR(PLUGIN_NAME " plugin: strdup failed.");
1274 char *fields[PLGINST_MAX_FIELDS];
1275 int n = strsplit(value_copy, fields, PLGINST_MAX_FIELDS);
1278 ERROR(PLUGIN_NAME " plugin: PluginInstanceFormat: no fields");
1282 for (int i = 0; i < n; ++i) {
1283 if (strcasecmp(fields[i], "none") == 0) {
1284 plugin_instance_format[i] = plginst_none;
1286 } else if (strcasecmp(fields[i], "name") == 0)
1287 plugin_instance_format[i] = plginst_name;
1288 else if (strcasecmp(fields[i], "uuid") == 0)
1289 plugin_instance_format[i] = plginst_uuid;
1290 else if (strcasecmp(fields[i], "metadata") == 0)
1291 plugin_instance_format[i] = plginst_metadata;
1293 ERROR(PLUGIN_NAME " plugin: unknown PluginInstanceFormat field: %s",
1301 for (int i = n; i < PLGINST_MAX_FIELDS; ++i)
1302 plugin_instance_format[i] = plginst_none;
1307 if (strcasecmp(key, "InterfaceFormat") == 0) {
1308 if (strcasecmp(value, "name") == 0)
1309 interface_format = if_name;
1310 else if (strcasecmp(value, "address") == 0)
1311 interface_format = if_address;
1312 else if (strcasecmp(value, "number") == 0)
1313 interface_format = if_number;
1315 ERROR(PLUGIN_NAME " plugin: unknown InterfaceFormat: %s", value);
1321 if (strcasecmp(key, "Instances") == 0) {
1323 double val = strtod(value, &eptr);
1325 if (*eptr != '\0') {
1326 ERROR(PLUGIN_NAME " plugin: Invalid value for Instances = '%s'", value);
1330 ERROR(PLUGIN_NAME " plugin: Instances <= 0 makes no sense.");
1333 if (val > NR_INSTANCES_MAX) {
1334 ERROR(PLUGIN_NAME " plugin: Instances=%f > NR_INSTANCES_MAX=%i"
1335 " use a lower setting or recompile the plugin.",
1336 val, NR_INSTANCES_MAX);
1340 nr_instances = (int)val;
1341 DEBUG(PLUGIN_NAME " plugin: configured %i instances", nr_instances);
1345 if (strcasecmp(key, "ExtraStats") == 0) {
1346 char *localvalue = strdup(value);
1347 if (localvalue != NULL) {
1348 char *exstats[EX_STATS_MAX_FIELDS];
1350 strsplit(localvalue, exstats, STATIC_ARRAY_SIZE(exstats));
1351 extra_stats = parse_ex_stats_flags(exstats, numexstats);
1354 #ifdef HAVE_JOB_STATS
1355 if ((extra_stats & ex_stats_job_stats_completed) &&
1356 (extra_stats & ex_stats_job_stats_background)) {
1357 ERROR(PLUGIN_NAME " plugin: Invalid job stats configuration. Only one "
1358 "type of job statistics can be collected at the same "
1366 if (strcasecmp(key, "PersistentNotification") == 0) {
1367 persistent_notification = IS_TRUE(value);
1371 /* Unrecognised option. */
1375 static int lv_connect(void) {
1377 /* `conn_string == NULL' is acceptable */
1379 /* virDomainGetFSInfo requires full read-write access connection */
1380 if (extra_stats & ex_stats_fs_info)
1381 conn = virConnectOpen(conn_string);
1384 conn = virConnectOpenReadOnly(conn_string);
1386 c_complain(LOG_ERR, &conn_complain,
1387 PLUGIN_NAME " plugin: Unable to connect: "
1388 "virConnectOpen failed.");
1391 int status = virNodeGetInfo(conn, &nodeinfo);
1393 ERROR(PLUGIN_NAME " plugin: virNodeGetInfo failed");
1397 c_release(LOG_NOTICE, &conn_complain,
1398 PLUGIN_NAME " plugin: Connection established.");
1402 static void lv_disconnect(void) {
1404 virConnectClose(conn);
1406 WARNING(PLUGIN_NAME " plugin: closed connection to libvirt");
1409 static int lv_domain_block_info(virDomainPtr dom, const char *path,
1410 struct lv_block_info *binfo) {
1411 #ifdef HAVE_BLOCK_STATS_FLAGS
1413 if (virDomainBlockStatsFlags(dom, path, NULL, &nparams, 0) < 0 ||
1415 VIRT_ERROR(conn, "getting the disk params count");
1419 virTypedParameterPtr params = calloc((size_t)nparams, sizeof(*params));
1420 if (params == NULL) {
1421 ERROR("virt plugin: alloc(%i) for block=%s parameters failed.", nparams,
1427 if (virDomainBlockStatsFlags(dom, path, params, &nparams, 0) < 0) {
1428 VIRT_ERROR(conn, "getting the disk params values");
1430 rc = get_block_info(binfo, params, nparams);
1433 virTypedParamsClear(params, nparams);
1437 return virDomainBlockStats(dom, path, &(binfo->bi), sizeof(binfo->bi));
1438 #endif /* HAVE_BLOCK_STATS_FLAGS */
1441 #ifdef HAVE_PERF_STATS
1442 static void perf_submit(virDomainStatsRecordPtr stats) {
1443 for (int i = 0; i < stats->nparams; ++i) {
1444 /* Replace '.' with '_' in event field to match other metrics' naming
1446 char *c = strchr(stats->params[i].field, '.');
1449 submit(stats->dom, "perf", stats->params[i].field,
1450 &(value_t){.derive = stats->params[i].value.ul}, 1);
1454 static int get_perf_events(virDomainPtr domain) {
1455 virDomainStatsRecordPtr *stats = NULL;
1456 /* virDomainListGetStats requires a NULL terminated list of domains */
1457 virDomainPtr domain_array[] = {domain, NULL};
1460 virDomainListGetStats(domain_array, VIR_DOMAIN_STATS_PERF, &stats, 0);
1462 ERROR("virt plugin: virDomainListGetStats failed with status %i.", status);
1466 for (int i = 0; i < status; ++i)
1467 perf_submit(stats[i]);
1469 virDomainStatsRecordListFree(stats);
1472 #endif /* HAVE_PERF_STATS */
1474 static void vcpu_pin_submit(virDomainPtr dom, int max_cpus, int vcpu,
1475 unsigned char *cpu_maps, int cpu_map_len) {
1476 for (int cpu = 0; cpu < max_cpus; ++cpu) {
1477 char type_instance[DATA_MAX_NAME_LEN];
1478 bool is_set = VIR_CPU_USABLE(cpu_maps, cpu_map_len, vcpu, cpu);
1480 snprintf(type_instance, sizeof(type_instance), "vcpu_%d-cpu_%d", vcpu, cpu);
1481 submit(dom, "cpu_affinity", type_instance, &(value_t){.gauge = is_set}, 1);
1485 static int get_vcpu_stats(virDomainPtr domain, unsigned short nr_virt_cpu) {
1486 int max_cpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
1487 int cpu_map_len = VIR_CPU_MAPLEN(max_cpus);
1489 virVcpuInfoPtr vinfo = calloc(nr_virt_cpu, sizeof(vinfo[0]));
1490 if (vinfo == NULL) {
1491 ERROR(PLUGIN_NAME " plugin: calloc failed.");
1495 unsigned char *cpumaps = calloc(nr_virt_cpu, cpu_map_len);
1496 if (cpumaps == NULL) {
1497 ERROR(PLUGIN_NAME " plugin: calloc failed.");
1503 virDomainGetVcpus(domain, vinfo, nr_virt_cpu, cpumaps, cpu_map_len);
1505 ERROR(PLUGIN_NAME " plugin: virDomainGetVcpus failed with status %i.",
1512 for (int i = 0; i < nr_virt_cpu; ++i) {
1513 vcpu_submit(vinfo[i].cpuTime, domain, vinfo[i].number, "virt_vcpu");
1514 if (extra_stats & ex_stats_vcpupin)
1515 vcpu_pin_submit(domain, max_cpus, i, cpumaps, cpu_map_len);
1523 #ifdef HAVE_CPU_STATS
1524 static int get_pcpu_stats(virDomainPtr dom) {
1525 int nparams = virDomainGetCPUStats(dom, NULL, 0, -1, 1, 0);
1527 VIRT_ERROR(conn, "getting the CPU params count");
1531 virTypedParameterPtr param = calloc(nparams, sizeof(virTypedParameter));
1532 if (param == NULL) {
1533 ERROR(PLUGIN_NAME " plugin: alloc(%i) for cpu parameters failed.", nparams);
1537 int ret = virDomainGetCPUStats(dom, param, nparams, -1, 1, 0); // total stats.
1539 virTypedParamsClear(param, nparams);
1541 VIRT_ERROR(conn, "getting the CPU params values");
1545 unsigned long long total_user_cpu_time = 0;
1546 unsigned long long total_syst_cpu_time = 0;
1548 for (int i = 0; i < nparams; ++i) {
1549 if (!strcmp(param[i].field, "user_time"))
1550 total_user_cpu_time = param[i].value.ul;
1551 else if (!strcmp(param[i].field, "system_time"))
1552 total_syst_cpu_time = param[i].value.ul;
1555 if (total_user_cpu_time > 0 || total_syst_cpu_time > 0)
1556 submit_derive2("ps_cputime", total_user_cpu_time, total_syst_cpu_time, dom,
1559 virTypedParamsClear(param, nparams);
1564 #endif /* HAVE_CPU_STATS */
1566 #ifdef HAVE_DOM_REASON
1568 static void domain_state_submit(virDomainPtr dom, int state, int reason) {
1569 value_t values[] = {
1570 {.gauge = (gauge_t)state}, {.gauge = (gauge_t)reason},
1573 submit(dom, "domain_state", NULL, values, STATIC_ARRAY_SIZE(values));
1576 static int get_domain_state(virDomainPtr domain) {
1577 int domain_state = 0;
1578 int domain_reason = 0;
1580 int status = virDomainGetState(domain, &domain_state, &domain_reason, 0);
1582 ERROR(PLUGIN_NAME " plugin: virDomainGetState failed with status %i.",
1587 domain_state_submit(domain, domain_state, domain_reason);
1592 #ifdef HAVE_LIST_ALL_DOMAINS
1593 static int get_domain_state_notify(virDomainPtr domain) {
1594 int domain_state = 0;
1595 int domain_reason = 0;
1597 int status = virDomainGetState(domain, &domain_state, &domain_reason, 0);
1599 ERROR(PLUGIN_NAME " plugin: virDomainGetState failed with status %i.",
1604 if (persistent_notification)
1605 domain_state_submit_notif(domain, domain_state, domain_reason);
1609 #endif /* HAVE_LIST_ALL_DOMAINS */
1610 #endif /* HAVE_DOM_REASON */
1612 static int get_memory_stats(virDomainPtr domain) {
1613 virDomainMemoryStatPtr minfo =
1614 calloc(VIR_DOMAIN_MEMORY_STAT_NR, sizeof(virDomainMemoryStatStruct));
1615 if (minfo == NULL) {
1616 ERROR("virt plugin: malloc failed.");
1621 virDomainMemoryStats(domain, minfo, VIR_DOMAIN_MEMORY_STAT_NR, 0);
1622 if (mem_stats < 0) {
1623 ERROR("virt plugin: virDomainMemoryStats failed with mem_stats %i.",
1629 for (int i = 0; i < mem_stats; i++)
1630 memory_stats_submit((gauge_t)minfo[i].val * 1024, domain, minfo[i].tag);
1636 #ifdef HAVE_DISK_ERR
1637 static void disk_err_submit(virDomainPtr domain,
1638 virDomainDiskErrorPtr disk_err) {
1639 submit(domain, "disk_error", disk_err->disk,
1640 &(value_t){.gauge = disk_err->error}, 1);
1643 static int get_disk_err(virDomainPtr domain) {
1644 /* Get preferred size of disk errors array */
1645 int disk_err_count = virDomainGetDiskErrors(domain, NULL, 0, 0);
1646 if (disk_err_count == -1) {
1648 " plugin: failed to get preferred size of disk errors array");
1653 " plugin: preferred size of disk errors array: %d for domain %s",
1654 disk_err_count, virDomainGetName(domain));
1655 virDomainDiskError disk_err[disk_err_count];
1657 disk_err_count = virDomainGetDiskErrors(domain, disk_err, disk_err_count, 0);
1658 if (disk_err_count == -1) {
1659 ERROR(PLUGIN_NAME " plugin: virDomainGetDiskErrors failed with status %d",
1664 DEBUG(PLUGIN_NAME " plugin: detected %d disk errors in domain %s",
1665 disk_err_count, virDomainGetName(domain));
1667 for (int i = 0; i < disk_err_count; ++i) {
1668 disk_err_submit(domain, &disk_err[i]);
1669 sfree(disk_err[i].disk);
1674 #endif /* HAVE_DISK_ERR */
1676 static int get_block_stats(struct block_device *block_dev) {
1679 ERROR(PLUGIN_NAME " plugin: get_block_stats NULL pointer");
1683 struct lv_block_info binfo;
1684 init_block_info(&binfo);
1686 if (lv_domain_block_info(block_dev->dom, block_dev->path, &binfo) < 0) {
1687 ERROR(PLUGIN_NAME " plugin: lv_domain_block_info failed");
1691 disk_submit(&binfo, block_dev->dom, block_dev->path);
1697 #define NM_ADD_ITEM(_fun, _name, _val) \
1699 ret = _fun(¬if, _name, _val); \
1701 ERROR(PLUGIN_NAME " plugin: failed to add notification metadata"); \
1706 #define NM_ADD_STR_ITEMS(_items, _size) \
1708 for (size_t _i = 0; _i < _size; ++_i) { \
1710 " plugin: Adding notification metadata name=%s value=%s", \
1711 _items[_i].name, _items[_i].value); \
1712 NM_ADD_ITEM(plugin_notification_meta_add_string, _items[_i].name, \
1713 _items[_i].value); \
1717 static int fs_info_notify(virDomainPtr domain, virDomainFSInfoPtr fs_info) {
1718 notification_t notif;
1721 /* Local struct, just for the purpose of this function. */
1722 typedef struct nm_str_item_s {
1727 nm_str_item_t fs_dev_alias[fs_info->ndevAlias];
1728 nm_str_item_t fs_str_items[] = {
1729 {.name = "mountpoint", .value = fs_info->mountpoint},
1730 {.name = "name", .value = fs_info->name},
1731 {.name = "fstype", .value = fs_info->fstype}};
1733 for (size_t i = 0; i < fs_info->ndevAlias; ++i) {
1734 fs_dev_alias[i].name = "devAlias";
1735 fs_dev_alias[i].value = fs_info->devAlias[i];
1738 init_notif(¬if, domain, NOTIF_OKAY, "File system information",
1739 "file_system", NULL);
1740 NM_ADD_STR_ITEMS(fs_str_items, STATIC_ARRAY_SIZE(fs_str_items));
1741 NM_ADD_ITEM(plugin_notification_meta_add_unsigned_int, "ndevAlias",
1742 fs_info->ndevAlias);
1743 NM_ADD_STR_ITEMS(fs_dev_alias, fs_info->ndevAlias);
1745 plugin_dispatch_notification(¬if);
1749 plugin_notification_meta_free(notif.meta);
1753 #undef RETURN_ON_ERR
1754 #undef NM_ADD_STR_ITEMS
1756 static int get_fs_info(virDomainPtr domain) {
1757 virDomainFSInfoPtr *fs_info = NULL;
1760 int mount_points_cnt = virDomainGetFSInfo(domain, &fs_info, 0);
1761 if (mount_points_cnt == -1) {
1762 ERROR(PLUGIN_NAME " plugin: virDomainGetFSInfo failed: %d",
1764 return mount_points_cnt;
1767 for (int i = 0; i < mount_points_cnt; ++i) {
1768 if (fs_info_notify(domain, fs_info[i]) != 0) {
1769 ERROR(PLUGIN_NAME " plugin: failed to send file system notification "
1770 "for mount point %s",
1771 fs_info[i]->mountpoint);
1774 virDomainFSInfoFree(fs_info[i]);
1781 #endif /* HAVE_FS_INFO */
1783 #ifdef HAVE_JOB_STATS
1784 static void job_stats_submit(virDomainPtr domain, virTypedParameterPtr param) {
1787 if (param->type == VIR_TYPED_PARAM_INT)
1788 vl.derive = param->value.i;
1789 else if (param->type == VIR_TYPED_PARAM_UINT)
1790 vl.derive = param->value.ui;
1791 else if (param->type == VIR_TYPED_PARAM_LLONG)
1792 vl.derive = param->value.l;
1793 else if (param->type == VIR_TYPED_PARAM_ULLONG)
1794 vl.derive = param->value.ul;
1795 else if (param->type == VIR_TYPED_PARAM_DOUBLE)
1796 vl.derive = param->value.d;
1797 else if (param->type == VIR_TYPED_PARAM_BOOLEAN)
1798 vl.derive = param->value.b;
1799 else if (param->type == VIR_TYPED_PARAM_STRING) {
1800 submit_notif(domain, NOTIF_OKAY, param->value.s, "job_stats", param->field);
1803 ERROR(PLUGIN_NAME " plugin: unrecognized virTypedParameterType");
1807 submit(domain, "job_stats", param->field, &vl, 1);
1810 static int get_job_stats(virDomainPtr domain) {
1814 virTypedParameterPtr params = NULL;
1815 int flags = (extra_stats & ex_stats_job_stats_completed)
1816 ? VIR_DOMAIN_JOB_STATS_COMPLETED
1819 ret = virDomainGetJobStats(domain, &job_type, ¶ms, &nparams, flags);
1821 ERROR(PLUGIN_NAME " plugin: virDomainGetJobStats failed: %d", ret);
1825 DEBUG(PLUGIN_NAME " plugin: job_type=%d nparams=%d", job_type, nparams);
1827 for (int i = 0; i < nparams; ++i) {
1828 DEBUG(PLUGIN_NAME " plugin: param[%d] field=%s type=%d", i, params[i].field,
1830 job_stats_submit(domain, ¶ms[i]);
1833 virTypedParamsFree(params, nparams);
1836 #endif /* HAVE_JOB_STATS */
1838 static int get_domain_metrics(domain_t *domain) {
1839 if (!domain || !domain->ptr) {
1840 ERROR(PLUGIN_NAME " plugin: get_domain_metrics: NULL pointer");
1845 int status = virDomainGetInfo(domain->ptr, &info);
1847 ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
1852 if (extra_stats & ex_stats_domain_state) {
1853 #ifdef HAVE_DOM_REASON
1854 /* At this point we already know domain's state from virDomainGetInfo call,
1855 * however it doesn't provide a reason for entering particular state.
1856 * We need to get it from virDomainGetState.
1858 GET_STATS(get_domain_state, "domain reason", domain->ptr);
1862 /* Gather remaining stats only for running domains */
1863 if (info.state != VIR_DOMAIN_RUNNING)
1866 #ifdef HAVE_CPU_STATS
1867 if (extra_stats & ex_stats_pcpu)
1868 get_pcpu_stats(domain->ptr);
1871 cpu_submit(domain, info.cpuTime);
1873 memory_submit(domain->ptr, (gauge_t)info.memory * 1024);
1875 GET_STATS(get_vcpu_stats, "vcpu stats", domain->ptr, info.nrVirtCpu);
1876 GET_STATS(get_memory_stats, "memory stats", domain->ptr);
1878 #ifdef HAVE_PERF_STATS
1879 if (extra_stats & ex_stats_perf)
1880 GET_STATS(get_perf_events, "performance monitoring events", domain->ptr);
1884 if (extra_stats & ex_stats_fs_info)
1885 GET_STATS(get_fs_info, "file system info", domain->ptr);
1888 #ifdef HAVE_DISK_ERR
1889 if (extra_stats & ex_stats_disk_err)
1890 GET_STATS(get_disk_err, "disk errors", domain->ptr);
1893 #ifdef HAVE_JOB_STATS
1895 (ex_stats_job_stats_completed | ex_stats_job_stats_background))
1896 GET_STATS(get_job_stats, "job stats", domain->ptr);
1899 /* Update cached virDomainInfo. It has to be done after cpu_submit */
1900 memcpy(&domain->info, &info, sizeof(domain->info));
1905 static int get_if_dev_stats(struct interface_device *if_dev) {
1906 virDomainInterfaceStatsStruct stats = {0};
1907 char *display_name = NULL;
1910 ERROR(PLUGIN_NAME " plugin: get_if_dev_stats: NULL pointer");
1914 switch (interface_format) {
1916 display_name = if_dev->address;
1919 display_name = if_dev->number;
1923 display_name = if_dev->path;
1926 if (virDomainInterfaceStats(if_dev->dom, if_dev->path, &stats,
1927 sizeof(stats)) != 0) {
1928 ERROR(PLUGIN_NAME " plugin: virDomainInterfaceStats failed");
1932 if ((stats.rx_bytes != -1) && (stats.tx_bytes != -1))
1933 submit_derive2("if_octets", (derive_t)stats.rx_bytes,
1934 (derive_t)stats.tx_bytes, if_dev->dom, display_name);
1936 if ((stats.rx_packets != -1) && (stats.tx_packets != -1))
1937 submit_derive2("if_packets", (derive_t)stats.rx_packets,
1938 (derive_t)stats.tx_packets, if_dev->dom, display_name);
1940 if ((stats.rx_errs != -1) && (stats.tx_errs != -1))
1941 submit_derive2("if_errors", (derive_t)stats.rx_errs,
1942 (derive_t)stats.tx_errs, if_dev->dom, display_name);
1944 if ((stats.rx_drop != -1) && (stats.tx_drop != -1))
1945 submit_derive2("if_dropped", (derive_t)stats.rx_drop,
1946 (derive_t)stats.tx_drop, if_dev->dom, display_name);
1950 static int domain_lifecycle_event_cb(__attribute__((unused)) virConnectPtr con_,
1951 virDomainPtr dom, int event, int detail,
1952 __attribute__((unused)) void *opaque) {
1953 int domain_state = map_domain_event_to_state(event);
1954 int domain_reason = 0; /* 0 means UNKNOWN reason for any state */
1955 #ifdef HAVE_DOM_REASON
1956 domain_reason = map_domain_event_detail_to_reason(event, detail);
1958 domain_state_submit_notif(dom, domain_state, domain_reason);
1963 static int register_event_impl(void) {
1964 if (virEventRegisterDefaultImpl() < 0) {
1965 virErrorPtr err = virGetLastError();
1967 " plugin: error while event implementation registering: %s",
1968 err && err->message ? err->message : "Unknown error");
1975 static void virt_notif_thread_set_active(virt_notif_thread_t *thread_data,
1976 const bool active) {
1977 assert(thread_data != NULL);
1978 pthread_mutex_lock(&thread_data->active_mutex);
1979 thread_data->is_active = active;
1980 pthread_mutex_unlock(&thread_data->active_mutex);
1983 static bool virt_notif_thread_is_active(virt_notif_thread_t *thread_data) {
1984 bool active = false;
1986 assert(thread_data != NULL);
1987 pthread_mutex_lock(&thread_data->active_mutex);
1988 active = thread_data->is_active;
1989 pthread_mutex_unlock(&thread_data->active_mutex);
1994 /* worker function running default event implementation */
1995 static void *event_loop_worker(void *arg) {
1996 virt_notif_thread_t *thread_data = (virt_notif_thread_t *)arg;
1998 while (virt_notif_thread_is_active(thread_data)) {
1999 if (virEventRunDefaultImpl() < 0) {
2000 virErrorPtr err = virGetLastError();
2001 ERROR(PLUGIN_NAME " plugin: failed to run event loop: %s\n",
2002 err && err->message ? err->message : "Unknown error");
2009 static int virt_notif_thread_init(virt_notif_thread_t *thread_data) {
2012 assert(thread_data != NULL);
2013 ret = pthread_mutex_init(&thread_data->active_mutex, NULL);
2015 ERROR(PLUGIN_NAME " plugin: Failed to initialize mutex, err %u", ret);
2020 * '0' and positive integers are meaningful ID's, therefore setting
2021 * domain_event_cb_id to '-1'
2023 thread_data->domain_event_cb_id = -1;
2024 pthread_mutex_lock(&thread_data->active_mutex);
2025 thread_data->is_active = false;
2026 pthread_mutex_unlock(&thread_data->active_mutex);
2031 /* register domain event callback and start event loop thread */
2032 static int start_event_loop(virt_notif_thread_t *thread_data) {
2033 assert(thread_data != NULL);
2034 thread_data->domain_event_cb_id = virConnectDomainEventRegisterAny(
2035 conn, NULL, VIR_DOMAIN_EVENT_ID_LIFECYCLE,
2036 VIR_DOMAIN_EVENT_CALLBACK(domain_lifecycle_event_cb), NULL, NULL);
2037 if (thread_data->domain_event_cb_id == -1) {
2038 ERROR(PLUGIN_NAME " plugin: error while callback registering");
2042 virt_notif_thread_set_active(thread_data, 1);
2043 if (pthread_create(&thread_data->event_loop_tid, NULL, event_loop_worker,
2045 ERROR(PLUGIN_NAME " plugin: failed event loop thread creation");
2046 virConnectDomainEventDeregisterAny(conn, thread_data->domain_event_cb_id);
2053 /* stop event loop thread and deregister callback */
2054 static void stop_event_loop(virt_notif_thread_t *thread_data) {
2055 /* stopping loop and de-registering event handler*/
2056 virt_notif_thread_set_active(thread_data, 0);
2057 if (conn != NULL && thread_data->domain_event_cb_id != -1)
2058 virConnectDomainEventDeregisterAny(conn, thread_data->domain_event_cb_id);
2060 if (pthread_join(notif_thread.event_loop_tid, NULL) != 0)
2061 ERROR(PLUGIN_NAME " plugin: stopping notification thread failed");
2064 static int persistent_domains_state_notification(void) {
2067 #ifdef HAVE_LIST_ALL_DOMAINS
2068 virDomainPtr *domains = NULL;
2069 n = virConnectListAllDomains(conn, &domains,
2070 VIR_CONNECT_LIST_DOMAINS_PERSISTENT);
2072 VIRT_ERROR(conn, "reading list of persistent domains");
2075 DEBUG(PLUGIN_NAME " plugin: getting state of %i persistent domains", n);
2076 /* Fetch each persistent domain's state and notify it */
2078 for (int i = 0; i < n; ++i) {
2079 status = get_domain_state_notify(domains[i]);
2082 ERROR(PLUGIN_NAME " plugin: could not notify state of domain %s",
2083 virDomainGetName(domains[i]));
2085 virDomainFree(domains[i]);
2089 DEBUG(PLUGIN_NAME " plugin: notified state of %i persistent domains",
2093 n = virConnectNumOfDomains(conn);
2096 /* Get list of domains. */
2097 domids = calloc(n, sizeof(*domids));
2098 if (domids == NULL) {
2099 ERROR(PLUGIN_NAME " plugin: calloc failed.");
2102 n = virConnectListDomains(conn, domids, n);
2104 VIRT_ERROR(conn, "reading list of domains");
2108 /* Fetch info of each active domain and notify it */
2109 for (int i = 0; i < n; ++i) {
2111 virDomainPtr dom = NULL;
2112 dom = virDomainLookupByID(conn, domids[i]);
2114 VIRT_ERROR(conn, "virDomainLookupByID");
2115 /* Could be that the domain went away -- ignore it anyway. */
2118 status = virDomainGetInfo(dom, &info);
2120 /* virDomainGetState is not available. Submit 0, which corresponds to
2121 * unknown reason. */
2122 domain_state_submit_notif(dom, info.state, 0);
2124 ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
2136 static int lv_read(user_data_t *ud) {
2138 struct lv_read_instance *inst = NULL;
2139 struct lv_read_state *state = NULL;
2141 if (ud->data == NULL) {
2142 ERROR(PLUGIN_NAME " plugin: NULL userdata");
2147 state = &inst->read_state;
2149 bool reconnect = conn == NULL ? true : false;
2150 /* event implementation must be registered before connection is opened */
2151 if (inst->id == 0) {
2152 if (!persistent_notification && reconnect)
2153 if (register_event_impl() != 0)
2156 if (lv_connect() < 0)
2159 if (!persistent_notification && reconnect && conn != NULL)
2160 if (start_event_loop(¬if_thread) != 0)
2166 /* Need to refresh domain or device lists? */
2167 if ((last_refresh == (time_t)0) ||
2168 ((interval > 0) && ((last_refresh + interval) <= t))) {
2169 if (refresh_lists(inst) != 0) {
2170 if (inst->id == 0) {
2171 if (!persistent_notification)
2172 stop_event_loop(¬if_thread);
2180 /* persistent domains state notifications are handled by instance 0 */
2181 if (inst->id == 0 && persistent_notification) {
2182 int status = persistent_domains_state_notification();
2184 DEBUG(PLUGIN_NAME " plugin: persistent_domains_state_notifications "
2185 "returned with status %i",
2190 for (int i = 0; i < state->nr_domains; ++i)
2191 DEBUG(PLUGIN_NAME " plugin: domain %s",
2192 virDomainGetName(state->domains[i].ptr));
2193 for (int i = 0; i < state->nr_block_devices; ++i)
2194 DEBUG(PLUGIN_NAME " plugin: block device %d %s:%s", i,
2195 virDomainGetName(state->block_devices[i].dom),
2196 state->block_devices[i].path);
2197 for (int i = 0; i < state->nr_interface_devices; ++i)
2198 DEBUG(PLUGIN_NAME " plugin: interface device %d %s:%s", i,
2199 virDomainGetName(state->interface_devices[i].dom),
2200 state->interface_devices[i].path);
2203 /* Get domains' metrics */
2204 for (int i = 0; i < state->nr_domains; ++i) {
2205 domain_t *dom = &state->domains[i];
2208 status = get_domain_metrics(dom);
2209 #ifdef HAVE_DOM_REASON
2211 status = get_domain_state(dom->ptr);
2215 ERROR(PLUGIN_NAME " plugin: failed to get metrics for domain=%s",
2216 virDomainGetName(dom->ptr));
2219 /* Get block device stats for each domain. */
2220 for (int i = 0; i < state->nr_block_devices; ++i) {
2221 int status = get_block_stats(&state->block_devices[i]);
2224 " plugin: failed to get stats for block device (%s) in domain %s",
2225 state->block_devices[i].path,
2226 virDomainGetName(state->block_devices[i].dom));
2229 /* Get interface stats for each domain. */
2230 for (int i = 0; i < state->nr_interface_devices; ++i) {
2231 int status = get_if_dev_stats(&state->interface_devices[i]);
2235 " plugin: failed to get interface stats for device (%s) in domain %s",
2236 state->interface_devices[i].path,
2237 virDomainGetName(state->interface_devices[i].dom));
2243 static int lv_init_instance(size_t i, plugin_read_cb callback) {
2244 struct lv_user_data *lv_ud = &(lv_read_user_data[i]);
2245 struct lv_read_instance *inst = &(lv_ud->inst);
2247 memset(lv_ud, 0, sizeof(*lv_ud));
2249 snprintf(inst->tag, sizeof(inst->tag), "%s-%" PRIsz, PLUGIN_NAME, i);
2252 user_data_t *ud = &(lv_ud->ud);
2254 ud->free_func = NULL;
2256 INFO(PLUGIN_NAME " plugin: reader %s initialized", inst->tag);
2258 return plugin_register_complex_read(NULL, inst->tag, callback, 0, ud);
2261 static void lv_clean_read_state(struct lv_read_state *state) {
2262 free_block_devices(state);
2263 free_interface_devices(state);
2264 free_domains(state);
2267 static void lv_fini_instance(size_t i) {
2268 struct lv_read_instance *inst = &(lv_read_user_data[i].inst);
2269 struct lv_read_state *state = &(inst->read_state);
2271 lv_clean_read_state(state);
2273 INFO(PLUGIN_NAME " plugin: reader %s finalized", inst->tag);
2276 static int lv_init(void) {
2277 if (virInitialize() != 0)
2280 /* Init ignorelists if there was no explicit configuration */
2281 if (lv_init_ignorelists() != 0)
2284 /* event implementation must be registered before connection is opened */
2285 if (!persistent_notification)
2286 if (register_event_impl() != 0)
2289 if (lv_connect() != 0)
2292 DEBUG(PLUGIN_NAME " plugin: starting event loop");
2294 if (!persistent_notification) {
2295 virt_notif_thread_init(¬if_thread);
2296 if (start_event_loop(¬if_thread) != 0)
2300 DEBUG(PLUGIN_NAME " plugin: starting %i instances", nr_instances);
2302 for (int i = 0; i < nr_instances; ++i)
2303 if (lv_init_instance(i, lv_read) != 0)
2310 * returns 0 on success and <0 on error
2312 static int lv_domain_get_tag(xmlXPathContextPtr xpath_ctx, const char *dom_name,
2314 char xpath_str[BUFFER_MAX_LEN] = {'\0'};
2315 xmlXPathObjectPtr xpath_obj = NULL;
2316 xmlNodePtr xml_node = NULL;
2320 err = xmlXPathRegisterNs(xpath_ctx,
2321 (const xmlChar *)METADATA_VM_PARTITION_PREFIX,
2322 (const xmlChar *)METADATA_VM_PARTITION_URI);
2324 ERROR(PLUGIN_NAME " plugin: xmlXpathRegisterNs(%s, %s) failed on domain %s",
2325 METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_URI, dom_name);
2329 snprintf(xpath_str, sizeof(xpath_str), "/domain/metadata/%s:%s/text()",
2330 METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_ELEMENT);
2331 xpath_obj = xmlXPathEvalExpression((xmlChar *)xpath_str, xpath_ctx);
2332 if (xpath_obj == NULL) {
2333 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) failed on domain %s",
2334 xpath_str, dom_name);
2338 if (xpath_obj->type != XPATH_NODESET) {
2339 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) unexpected return type %d "
2340 "(wanted %d) on domain %s",
2341 xpath_str, xpath_obj->type, XPATH_NODESET, dom_name);
2346 * from now on there is no real error, it's ok if a domain
2347 * doesn't have the metadata partition tag.
2350 if (xpath_obj->nodesetval == NULL || xpath_obj->nodesetval->nodeNr != 1) {
2351 DEBUG(PLUGIN_NAME " plugin: xmlXPathEval(%s) return nodeset size=%i "
2352 "expected=1 on domain %s",
2354 (xpath_obj->nodesetval == NULL) ? 0 : xpath_obj->nodesetval->nodeNr,
2357 xml_node = xpath_obj->nodesetval->nodeTab[0];
2358 sstrncpy(dom_tag, (const char *)xml_node->content, PARTITION_TAG_MAX_LEN);
2362 /* deregister to clean up */
2363 err = xmlXPathRegisterNs(xpath_ctx,
2364 (const xmlChar *)METADATA_VM_PARTITION_PREFIX, NULL);
2366 /* we can't really recover here */
2368 " plugin: deregistration of namespace %s failed for domain %s",
2369 METADATA_VM_PARTITION_PREFIX, dom_name);
2372 xmlXPathFreeObject(xpath_obj);
2377 static int is_known_tag(const char *dom_tag) {
2378 for (int i = 0; i < nr_instances; ++i)
2379 if (!strcmp(dom_tag, lv_read_user_data[i].inst.tag))
2384 static int lv_instance_include_domain(struct lv_read_instance *inst,
2385 const char *dom_name,
2386 const char *dom_tag) {
2387 if ((dom_tag[0] != '\0') && (strcmp(dom_tag, inst->tag) == 0))
2390 /* instance#0 will always be there, so it is in charge of extra duties */
2391 if (inst->id == 0) {
2392 if (dom_tag[0] == '\0' || !is_known_tag(dom_tag)) {
2393 DEBUG(PLUGIN_NAME " plugin#%s: refreshing domain %s "
2394 "with unknown tag '%s'",
2395 inst->tag, dom_name, dom_tag);
2403 static int refresh_lists(struct lv_read_instance *inst) {
2404 struct lv_read_state *state = &inst->read_state;
2407 #ifndef HAVE_LIST_ALL_DOMAINS
2408 n = virConnectNumOfDomains(conn);
2410 VIRT_ERROR(conn, "reading number of domains");
2415 lv_clean_read_state(state);
2417 #ifndef HAVE_LIST_ALL_DOMAINS
2422 #ifdef HAVE_LIST_ALL_DOMAINS
2423 virDomainPtr *domains, *domains_inactive;
2424 int m = virConnectListAllDomains(conn, &domains_inactive,
2425 VIR_CONNECT_LIST_DOMAINS_INACTIVE);
2426 n = virConnectListAllDomains(conn, &domains, VIR_CONNECT_LIST_DOMAINS_ACTIVE);
2428 /* Get list of domains. */
2429 int *domids = calloc(n, sizeof(*domids));
2430 if (domids == NULL) {
2431 ERROR(PLUGIN_NAME " plugin: calloc failed.");
2435 n = virConnectListDomains(conn, domids, n);
2439 VIRT_ERROR(conn, "reading list of domains");
2440 #ifndef HAVE_LIST_ALL_DOMAINS
2443 for (int i = 0; i < m; ++i)
2444 virDomainFree(domains_inactive[i]);
2445 sfree(domains_inactive);
2450 #ifdef HAVE_LIST_ALL_DOMAINS
2451 for (int i = 0; i < m; ++i)
2452 if (add_domain(state, domains_inactive[i], 0) < 0) {
2453 ERROR(PLUGIN_NAME " plugin: malloc failed.");
2454 virDomainFree(domains_inactive[i]);
2455 domains_inactive[i] = NULL;
2460 /* Fetch each domain and add it to the list, unless ignore. */
2461 for (int i = 0; i < n; ++i) {
2463 #ifdef HAVE_LIST_ALL_DOMAINS
2464 virDomainPtr dom = domains[i];
2466 virDomainPtr dom = virDomainLookupByID(conn, domids[i]);
2468 VIRT_ERROR(conn, "virDomainLookupByID");
2469 /* Could be that the domain went away -- ignore it anyway. */
2474 if (add_domain(state, dom, 1) < 0) {
2476 * When domain is already tracked, then there is
2477 * no problem with memory handling (will be freed
2478 * with the rest of domains cached data)
2479 * But in case of error like this (error occurred
2480 * before adding domain to track) we have to take
2481 * care it ourselves and call virDomainFree
2483 ERROR(PLUGIN_NAME " plugin: malloc failed.");
2488 const char *domname = virDomainGetName(dom);
2489 if (domname == NULL) {
2490 VIRT_ERROR(conn, "virDomainGetName");
2495 int status = virDomainGetInfo(dom, &info);
2497 ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
2502 if (info.state != VIR_DOMAIN_RUNNING) {
2503 DEBUG(PLUGIN_NAME " plugin: skipping inactive domain %s", domname);
2507 if (ignorelist_match(il_domains, domname) != 0)
2510 /* Get a list of devices for this domain. */
2511 xmlDocPtr xml_doc = NULL;
2512 xmlXPathContextPtr xpath_ctx = NULL;
2513 xmlXPathObjectPtr xpath_obj = NULL;
2515 char *xml = virDomainGetXMLDesc(dom, 0);
2517 VIRT_ERROR(conn, "virDomainGetXMLDesc");
2521 /* Yuck, XML. Parse out the devices. */
2522 xml_doc = xmlReadDoc((xmlChar *)xml, NULL, NULL, XML_PARSE_NONET);
2523 if (xml_doc == NULL) {
2524 VIRT_ERROR(conn, "xmlReadDoc");
2528 xpath_ctx = xmlXPathNewContext(xml_doc);
2530 char tag[PARTITION_TAG_MAX_LEN] = {'\0'};
2531 if (lv_domain_get_tag(xpath_ctx, domname, tag) < 0) {
2532 ERROR(PLUGIN_NAME " plugin: lv_domain_get_tag failed.");
2536 if (!lv_instance_include_domain(inst, domname, tag))
2539 /* Block devices. */
2540 const char *bd_xmlpath = "/domain/devices/disk/target[@dev]";
2541 if (blockdevice_format == source)
2542 bd_xmlpath = "/domain/devices/disk/source[@dev]";
2543 xpath_obj = xmlXPathEval((const xmlChar *)bd_xmlpath, xpath_ctx);
2545 if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
2546 xpath_obj->nodesetval == NULL)
2549 for (int j = 0; j < xpath_obj->nodesetval->nodeNr; ++j) {
2550 xmlNodePtr node = xpath_obj->nodesetval->nodeTab[j];
2554 char *path = (char *)xmlGetProp(node, (xmlChar *)"dev");
2558 if (ignore_device_match(il_block_devices, domname, path) == 0)
2559 add_block_device(state, dom, path);
2563 xmlXPathFreeObject(xpath_obj);
2565 /* Network interfaces. */
2566 xpath_obj = xmlXPathEval(
2567 (xmlChar *)"/domain/devices/interface[target[@dev]]", xpath_ctx);
2568 if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
2569 xpath_obj->nodesetval == NULL)
2572 xmlNodeSetPtr xml_interfaces = xpath_obj->nodesetval;
2574 for (int j = 0; j < xml_interfaces->nodeNr; ++j) {
2576 char *address = NULL;
2578 xmlNodePtr xml_interface = xml_interfaces->nodeTab[j];
2582 for (xmlNodePtr child = xml_interface->children; child;
2583 child = child->next) {
2584 if (child->type != XML_ELEMENT_NODE)
2587 if (xmlStrEqual(child->name, (const xmlChar *)"target")) {
2588 path = (char *)xmlGetProp(child, (const xmlChar *)"dev");
2591 } else if (xmlStrEqual(child->name, (const xmlChar *)"mac")) {
2592 address = (char *)xmlGetProp(child, (const xmlChar *)"address");
2598 if ((ignore_device_match(il_interface_devices, domname, path) == 0 &&
2599 ignore_device_match(il_interface_devices, domname, address) == 0)) {
2600 add_interface_device(state, dom, path, address, j + 1);
2611 xmlXPathFreeObject(xpath_obj);
2613 xmlXPathFreeContext(xpath_ctx);
2615 xmlFreeDoc(xml_doc);
2619 #ifdef HAVE_LIST_ALL_DOMAINS
2620 /* NOTE: domains_active and domains_inactive data will be cleared during
2621 refresh of all domains (inside lv_clean_read_state function) so we need
2622 to free here only allocated arrays */
2624 sfree(domains_inactive);
2631 DEBUG(PLUGIN_NAME " plugin#%s: refreshing"
2632 " domains=%i block_devices=%i iface_devices=%i",
2633 inst->tag, state->nr_domains, state->nr_block_devices,
2634 state->nr_interface_devices);
2639 static void free_domains(struct lv_read_state *state) {
2640 if (state->domains) {
2641 for (int i = 0; i < state->nr_domains; ++i)
2642 virDomainFree(state->domains[i].ptr);
2643 sfree(state->domains);
2645 state->domains = NULL;
2646 state->nr_domains = 0;
2649 static int add_domain(struct lv_read_state *state, virDomainPtr dom,
2652 int new_size = sizeof(state->domains[0]) * (state->nr_domains + 1);
2654 domain_t *new_ptr = realloc(state->domains, new_size);
2655 if (new_ptr == NULL)
2658 state->domains = new_ptr;
2659 state->domains[state->nr_domains].ptr = dom;
2660 state->domains[state->nr_domains].active = active;
2661 memset(&state->domains[state->nr_domains].info, 0,
2662 sizeof(state->domains[state->nr_domains].info));
2664 return state->nr_domains++;
2667 static void free_block_devices(struct lv_read_state *state) {
2668 if (state->block_devices) {
2669 for (int i = 0; i < state->nr_block_devices; ++i)
2670 sfree(state->block_devices[i].path);
2671 sfree(state->block_devices);
2673 state->block_devices = NULL;
2674 state->nr_block_devices = 0;
2677 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
2680 char *path_copy = strdup(path);
2685 sizeof(state->block_devices[0]) * (state->nr_block_devices + 1);
2687 struct block_device *new_ptr = realloc(state->block_devices, new_size);
2688 if (new_ptr == NULL) {
2692 state->block_devices = new_ptr;
2693 state->block_devices[state->nr_block_devices].dom = dom;
2694 state->block_devices[state->nr_block_devices].path = path_copy;
2695 return state->nr_block_devices++;
2698 static void free_interface_devices(struct lv_read_state *state) {
2699 if (state->interface_devices) {
2700 for (int i = 0; i < state->nr_interface_devices; ++i) {
2701 sfree(state->interface_devices[i].path);
2702 sfree(state->interface_devices[i].address);
2703 sfree(state->interface_devices[i].number);
2705 sfree(state->interface_devices);
2707 state->interface_devices = NULL;
2708 state->nr_interface_devices = 0;
2711 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
2712 const char *path, const char *address,
2713 unsigned int number) {
2715 if ((path == NULL) || (address == NULL))
2718 char *path_copy = strdup(path);
2722 char *address_copy = strdup(address);
2723 if (!address_copy) {
2728 char number_string[21];
2729 snprintf(number_string, sizeof(number_string), "interface-%u", number);
2730 char *number_copy = strdup(number_string);
2733 sfree(address_copy);
2738 sizeof(state->interface_devices[0]) * (state->nr_interface_devices + 1);
2740 struct interface_device *new_ptr =
2741 realloc(state->interface_devices, new_size);
2742 if (new_ptr == NULL) {
2744 sfree(address_copy);
2749 state->interface_devices = new_ptr;
2750 state->interface_devices[state->nr_interface_devices].dom = dom;
2751 state->interface_devices[state->nr_interface_devices].path = path_copy;
2752 state->interface_devices[state->nr_interface_devices].address = address_copy;
2753 state->interface_devices[state->nr_interface_devices].number = number_copy;
2754 return state->nr_interface_devices++;
2757 static int ignore_device_match(ignorelist_t *il, const char *domname,
2758 const char *devpath) {
2759 if ((domname == NULL) || (devpath == NULL))
2762 size_t n = strlen(domname) + strlen(devpath) + 2;
2763 char *name = malloc(n);
2765 ERROR(PLUGIN_NAME " plugin: malloc failed.");
2768 snprintf(name, n, "%s:%s", domname, devpath);
2769 int r = ignorelist_match(il, name);
2774 static int lv_shutdown(void) {
2775 for (int i = 0; i < nr_instances; ++i) {
2776 lv_fini_instance(i);
2779 DEBUG(PLUGIN_NAME " plugin: stopping event loop");
2781 if (!persistent_notification)
2782 stop_event_loop(¬if_thread);
2786 ignorelist_free(il_domains);
2788 ignorelist_free(il_block_devices);
2789 il_block_devices = NULL;
2790 ignorelist_free(il_interface_devices);
2791 il_interface_devices = NULL;
2796 void module_register(void) {
2797 plugin_register_config(PLUGIN_NAME, lv_config, config_keys, NR_CONFIG_KEYS);
2798 plugin_register_init(PLUGIN_NAME, lv_init);
2799 plugin_register_shutdown(PLUGIN_NAME, lv_shutdown);