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>
26 #include "utils_complain.h"
27 #include "utils_ignorelist.h"
29 #include <libgen.h> /* for basename(3) */
30 #include <libvirt/libvirt.h>
31 #include <libvirt/virterror.h>
32 #include <libxml/parser.h>
33 #include <libxml/tree.h>
34 #include <libxml/xpath.h>
35 #include <libxml/xpathInternals.h>
38 #define PLUGIN_NAME "virt"
40 #ifdef LIBVIR_CHECK_VERSION
41 #if LIBVIR_CHECK_VERSION(0, 9, 5)
42 #define HAVE_BLOCK_STATS_FLAGS 1
46 static const char *config_keys[] = {"Connection",
53 "BlockDeviceFormatBasename",
60 "PluginInstanceFormat",
66 #define NR_CONFIG_KEYS ((sizeof config_keys / sizeof config_keys[0]) - 1)
69 static virConnectPtr conn = 0;
70 static char *conn_string = NULL;
71 static c_complain_t conn_complain = C_COMPLAIN_INIT_STATIC;
73 /* Seconds between list refreshes, 0 disables completely. */
74 static int interval = 60;
76 /* List of domains, if specified. */
77 static ignorelist_t *il_domains = NULL;
78 /* List of block devices, if specified. */
79 static ignorelist_t *il_block_devices = NULL;
80 /* List of network interface devices, if specified. */
81 static ignorelist_t *il_interface_devices = NULL;
83 static int ignore_device_match(ignorelist_t *, const char *domname,
86 /* Actual list of block devices found on last refresh. */
88 virDomainPtr dom; /* domain */
89 char *path; /* name of block device */
92 /* Actual list of network interfaces found on last refresh. */
93 struct interface_device {
94 virDomainPtr dom; /* domain */
95 char *path; /* name of interface device */
96 char *address; /* mac address of interface device */
97 char *number; /* interface device number */
100 struct lv_read_state {
101 /* Actual list of domains found on last refresh. */
102 virDomainPtr *domains;
105 struct block_device *block_devices;
106 int nr_block_devices;
108 struct interface_device *interface_devices;
109 int nr_interface_devices;
112 static void free_domains(struct lv_read_state *state);
113 static int add_domain(struct lv_read_state *state, virDomainPtr dom);
115 static void free_block_devices(struct lv_read_state *state);
116 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
119 static void free_interface_devices(struct lv_read_state *state);
120 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
121 const char *path, const char *address,
122 unsigned int number);
124 #define METADATA_VM_PARTITION_URI "http://ovirt.org/ovirtmap/tag/1.0"
125 #define METADATA_VM_PARTITION_ELEMENT "tag"
126 #define METADATA_VM_PARTITION_PREFIX "ovirtmap"
128 #define BUFFER_MAX_LEN 256
129 #define PARTITION_TAG_MAX_LEN 32
131 struct lv_read_instance {
132 struct lv_read_state read_state;
133 char tag[PARTITION_TAG_MAX_LEN];
137 struct lv_user_data {
138 struct lv_read_instance inst;
142 #define NR_INSTANCES_DEFAULT 1
143 #define NR_INSTANCES_MAX 128
144 static int nr_instances = NR_INSTANCES_DEFAULT;
145 static struct lv_user_data lv_read_user_data[NR_INSTANCES_MAX];
147 /* HostnameFormat. */
148 #define HF_MAX_FIELDS 3
150 enum hf_field { hf_none = 0, hf_hostname, hf_name, hf_uuid };
152 static enum hf_field hostname_format[HF_MAX_FIELDS] = {hf_name};
154 /* PluginInstanceFormat */
155 #define PLGINST_MAX_FIELDS 2
157 enum plginst_field { plginst_none = 0, plginst_name, plginst_uuid };
159 static enum plginst_field plugin_instance_format[PLGINST_MAX_FIELDS] = {
162 /* BlockDeviceFormat */
163 enum bd_field { target, source };
165 /* InterfaceFormat. */
166 enum if_field { if_address, if_name, if_number };
169 #define EX_STATS_MAX_FIELDS 8
170 #define EX_STATS_DISK "disk"
171 enum ex_stats { ex_stats_none = 0, ex_stats_disk = 1 };
172 static enum ex_stats extra_stats = ex_stats_none;
174 /* BlockDeviceFormatBasename */
175 _Bool blockdevice_format_basename = 0;
176 static enum bd_field blockdevice_format = target;
177 static enum if_field interface_format = if_name;
179 /* Time that we last refreshed. */
180 static time_t last_refresh = (time_t)0;
182 static int refresh_lists(struct lv_read_instance *inst);
184 struct lv_block_info {
185 virDomainBlockStatsStruct bi;
187 long long rd_total_times;
188 long long wr_total_times;
191 long long fl_total_times;
194 static void init_block_info(struct lv_block_info *binfo) {
198 binfo->bi.rd_req = -1;
199 binfo->bi.wr_req = -1;
200 binfo->bi.rd_bytes = -1;
201 binfo->bi.wr_bytes = -1;
203 binfo->rd_total_times = -1;
204 binfo->wr_total_times = -1;
206 binfo->fl_total_times = -1;
209 #ifdef HAVE_BLOCK_STATS_FLAGS
211 #define GET_BLOCK_INFO_VALUE(NAME, FIELD) \
213 if (!strcmp(param[i].field, NAME)) { \
214 binfo->FIELD = param[i].value.l; \
219 static int get_block_info(struct lv_block_info *binfo,
220 virTypedParameterPtr param, int nparams) {
221 if (binfo == NULL || param == NULL)
224 for (int i = 0; i < nparams; ++i) {
225 /* ignore type. Everything must be LLONG anyway. */
226 GET_BLOCK_INFO_VALUE("rd_operations", bi.rd_req);
227 GET_BLOCK_INFO_VALUE("wr_operations", bi.wr_req);
228 GET_BLOCK_INFO_VALUE("rd_bytes", bi.rd_bytes);
229 GET_BLOCK_INFO_VALUE("wr_bytes", bi.wr_bytes);
230 GET_BLOCK_INFO_VALUE("rd_total_times", rd_total_times);
231 GET_BLOCK_INFO_VALUE("wr_total_times", wr_total_times);
232 GET_BLOCK_INFO_VALUE("flush_operations", fl_req);
233 GET_BLOCK_INFO_VALUE("flush_total_times", fl_total_times);
239 #undef GET_BLOCK_INFO_VALUE
241 #endif /* HAVE_BLOCK_STATS_FLAGS */
243 /* ERROR(...) macro for virterrors. */
244 #define VIRT_ERROR(conn, s) \
247 err = (conn) ? virConnGetLastError((conn)) : virGetLastError(); \
249 ERROR("%s: %s", (s), err->message); \
252 static void init_value_list(value_list_t *vl, virDomainPtr dom) {
255 char uuid[VIR_UUID_STRING_BUFLEN];
257 sstrncpy(vl->plugin, PLUGIN_NAME, sizeof(vl->plugin));
261 /* Construct the hostname field according to HostnameFormat. */
262 for (int i = 0; i < HF_MAX_FIELDS; ++i) {
263 if (hostname_format[i] == hf_none)
266 n = DATA_MAX_NAME_LEN - strlen(vl->host) - 2;
268 if (i > 0 && n >= 1) {
269 strncat(vl->host, ":", 1);
273 switch (hostname_format[i]) {
277 strncat(vl->host, hostname_g, n);
280 name = virDomainGetName(dom);
282 strncat(vl->host, name, n);
285 if (virDomainGetUUIDString(dom, uuid) == 0)
286 strncat(vl->host, uuid, n);
291 vl->host[sizeof(vl->host) - 1] = '\0';
293 /* Construct the plugin instance field according to PluginInstanceFormat. */
294 for (int i = 0; i < PLGINST_MAX_FIELDS; ++i) {
295 if (plugin_instance_format[i] == plginst_none)
298 n = sizeof(vl->plugin_instance) - strlen(vl->plugin_instance) - 2;
300 if (i > 0 && n >= 1) {
301 strncat(vl->plugin_instance, ":", 1);
305 switch (plugin_instance_format[i]) {
309 name = virDomainGetName(dom);
311 strncat(vl->plugin_instance, name, n);
314 if (virDomainGetUUIDString(dom, uuid) == 0)
315 strncat(vl->plugin_instance, uuid, n);
320 vl->plugin_instance[sizeof(vl->plugin_instance) - 1] = '\0';
322 } /* void init_value_list */
324 static void submit(virDomainPtr dom, char const *type,
325 char const *type_instance, value_t *values,
327 value_list_t vl = VALUE_LIST_INIT;
328 init_value_list(&vl, dom);
331 vl.values_len = values_len;
333 sstrncpy(vl.type, type, sizeof(vl.type));
334 if (type_instance != NULL)
335 sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
337 plugin_dispatch_values(&vl);
340 static void memory_submit(gauge_t value, virDomainPtr dom) {
341 submit(dom, "memory", "total", &(value_t){.gauge = value}, 1);
344 static void memory_stats_submit(gauge_t value, virDomainPtr dom,
346 static const char *tags[] = {"swap_in", "swap_out", "major_fault",
347 "minor_fault", "unused", "available",
348 "actual_balloon", "rss"};
350 if ((tag_index < 0) || (tag_index >= STATIC_ARRAY_SIZE(tags))) {
351 ERROR("virt plugin: Array index out of bounds: tag_index = %d", tag_index);
355 submit(dom, "memory", tags[tag_index], &(value_t){.gauge = value}, 1);
358 static void cpu_submit(unsigned long long value, virDomainPtr dom,
360 submit(dom, type, NULL, &(value_t){.derive = (derive_t)value}, 1);
363 static void vcpu_submit(derive_t value, virDomainPtr dom, int vcpu_nr,
365 char type_instance[DATA_MAX_NAME_LEN];
367 ssnprintf(type_instance, sizeof(type_instance), "%d", vcpu_nr);
369 submit(dom, type, type_instance, &(value_t){.derive = value}, 1);
372 static void submit_derive2(const char *type, derive_t v0, derive_t v1,
373 virDomainPtr dom, const char *devname) {
375 {.derive = v0}, {.derive = v1},
378 submit(dom, type, devname, values, STATIC_ARRAY_SIZE(values));
379 } /* void submit_derive2 */
381 static void disk_submit(struct lv_block_info *binfo, virDomainPtr dom,
382 const char *type_instance) {
383 char flush_type_instance[DATA_MAX_NAME_LEN];
385 ssnprintf(flush_type_instance, sizeof(flush_type_instance), "flush-%s",
388 if ((binfo->bi.rd_req != -1) && (binfo->bi.wr_req != -1))
389 submit_derive2("disk_ops", (derive_t)binfo->bi.rd_req,
390 (derive_t)binfo->bi.wr_req, dom, type_instance);
392 if ((binfo->bi.rd_bytes != -1) && (binfo->bi.wr_bytes != -1))
393 submit_derive2("disk_octets", (derive_t)binfo->bi.rd_bytes,
394 (derive_t)binfo->bi.wr_bytes, dom, type_instance);
396 if (extra_stats & ex_stats_disk) {
397 if ((binfo->rd_total_times != -1) && (binfo->wr_total_times != -1))
398 submit_derive2("disk_time", (derive_t)binfo->rd_total_times,
399 (derive_t)binfo->wr_total_times, dom, type_instance);
401 if (binfo->fl_req != -1)
402 submit(dom, "total_requests", flush_type_instance,
403 &(value_t){.derive = (derive_t)binfo->fl_req}, 1);
404 if (binfo->fl_total_times != -1) {
405 derive_t value = binfo->fl_total_times / 1000; // ns -> ms
406 submit(dom, "total_time_in_ms", flush_type_instance,
407 &(value_t){.derive = value}, 1);
412 static int lv_config(const char *key, const char *value) {
413 if (virInitialize() != 0)
416 if (il_domains == NULL)
417 il_domains = ignorelist_create(1);
418 if (il_block_devices == NULL)
419 il_block_devices = ignorelist_create(1);
420 if (il_interface_devices == NULL)
421 il_interface_devices = ignorelist_create(1);
423 if (strcasecmp(key, "Connection") == 0) {
424 char *tmp = strdup(value);
426 ERROR(PLUGIN_NAME " plugin: Connection strdup failed.");
434 if (strcasecmp(key, "RefreshInterval") == 0) {
436 interval = strtol(value, &eptr, 10);
437 if (eptr == NULL || *eptr != '\0')
442 if (strcasecmp(key, "Domain") == 0) {
443 if (ignorelist_add(il_domains, value))
447 if (strcasecmp(key, "BlockDevice") == 0) {
448 if (ignorelist_add(il_block_devices, value))
453 if (strcasecmp(key, "BlockDeviceFormat") == 0) {
454 if (strcasecmp(value, "target") == 0)
455 blockdevice_format = target;
456 else if (strcasecmp(value, "source") == 0)
457 blockdevice_format = source;
459 ERROR(PLUGIN_NAME " plugin: unknown BlockDeviceFormat: %s", value);
464 if (strcasecmp(key, "BlockDeviceFormatBasename") == 0) {
465 blockdevice_format_basename = IS_TRUE(value);
468 if (strcasecmp(key, "InterfaceDevice") == 0) {
469 if (ignorelist_add(il_interface_devices, value))
474 if (strcasecmp(key, "IgnoreSelected") == 0) {
475 if (IS_TRUE(value)) {
476 ignorelist_set_invert(il_domains, 0);
477 ignorelist_set_invert(il_block_devices, 0);
478 ignorelist_set_invert(il_interface_devices, 0);
480 ignorelist_set_invert(il_domains, 1);
481 ignorelist_set_invert(il_block_devices, 1);
482 ignorelist_set_invert(il_interface_devices, 1);
487 if (strcasecmp(key, "HostnameFormat") == 0) {
489 char *fields[HF_MAX_FIELDS];
492 value_copy = strdup(value);
493 if (value_copy == NULL) {
494 ERROR(PLUGIN_NAME " plugin: strdup failed.");
498 n = strsplit(value_copy, fields, HF_MAX_FIELDS);
501 ERROR(PLUGIN_NAME " plugin: HostnameFormat: no fields");
505 for (int i = 0; i < n; ++i) {
506 if (strcasecmp(fields[i], "hostname") == 0)
507 hostname_format[i] = hf_hostname;
508 else if (strcasecmp(fields[i], "name") == 0)
509 hostname_format[i] = hf_name;
510 else if (strcasecmp(fields[i], "uuid") == 0)
511 hostname_format[i] = hf_uuid;
513 ERROR(PLUGIN_NAME " plugin: unknown HostnameFormat field: %s",
521 for (int i = n; i < HF_MAX_FIELDS; ++i)
522 hostname_format[i] = hf_none;
527 if (strcasecmp(key, "PluginInstanceFormat") == 0) {
529 char *fields[PLGINST_MAX_FIELDS];
532 value_copy = strdup(value);
533 if (value_copy == NULL) {
534 ERROR(PLUGIN_NAME " plugin: strdup failed.");
538 n = strsplit(value_copy, fields, PLGINST_MAX_FIELDS);
541 ERROR(PLUGIN_NAME " plugin: PluginInstanceFormat: no fields");
545 for (int i = 0; i < n; ++i) {
546 if (strcasecmp(fields[i], "none") == 0) {
547 plugin_instance_format[i] = plginst_none;
549 } else if (strcasecmp(fields[i], "name") == 0)
550 plugin_instance_format[i] = plginst_name;
551 else if (strcasecmp(fields[i], "uuid") == 0)
552 plugin_instance_format[i] = plginst_uuid;
554 ERROR(PLUGIN_NAME " plugin: unknown PluginInstanceFormat field: %s",
562 for (int i = n; i < PLGINST_MAX_FIELDS; ++i)
563 plugin_instance_format[i] = plginst_none;
568 if (strcasecmp(key, "InterfaceFormat") == 0) {
569 if (strcasecmp(value, "name") == 0)
570 interface_format = if_name;
571 else if (strcasecmp(value, "address") == 0)
572 interface_format = if_address;
573 else if (strcasecmp(value, "number") == 0)
574 interface_format = if_number;
576 ERROR(PLUGIN_NAME " plugin: unknown InterfaceFormat: %s", value);
582 if (strcasecmp(key, "Instances") == 0) {
584 double val = strtod(value, &eptr);
587 ERROR(PLUGIN_NAME " plugin: Invalid value for Instances = '%s'", value);
591 ERROR(PLUGIN_NAME " plugin: Instances <= 0 makes no sense.");
594 if (val > NR_INSTANCES_MAX) {
595 ERROR(PLUGIN_NAME " plugin: Instances=%f > NR_INSTANCES_MAX=%i"
596 " use a lower setting or recompile the plugin.",
597 val, NR_INSTANCES_MAX);
601 nr_instances = (int)val;
602 DEBUG(PLUGIN_NAME " plugin: configured %i instances", nr_instances);
606 if (strcasecmp(key, "ExtraStats") == 0) {
607 char *localvalue = sstrdup(value);
608 if (localvalue != NULL) {
609 char *exstats[EX_STATS_MAX_FIELDS];
611 strsplit(localvalue, exstats, STATIC_ARRAY_SIZE(exstats));
612 for (int i = 0; i < numexstats; i++) {
613 if (strcasecmp(exstats[i], EX_STATS_DISK) == 0) {
614 DEBUG(PLUGIN_NAME " plugin: enabling extra stats for '%s'",
616 extra_stats |= ex_stats_disk;
623 /* Unrecognised option. */
627 static int lv_connect(void) {
629 /* `conn_string == NULL' is acceptable. */
630 conn = virConnectOpenReadOnly(conn_string);
632 c_complain(LOG_ERR, &conn_complain,
633 PLUGIN_NAME " plugin: Unable to connect: "
634 "virConnectOpenReadOnly failed.");
638 c_release(LOG_NOTICE, &conn_complain,
639 PLUGIN_NAME " plugin: Connection established.");
643 static void lv_disconnect(void) {
645 virConnectClose(conn);
647 WARNING(PLUGIN_NAME " plugin: closed connection to libvirt");
650 static int lv_domain_block_info(virDomainPtr dom, const char *path,
651 struct lv_block_info *binfo) {
652 #ifdef HAVE_BLOCK_STATS_FLAGS
653 virTypedParameterPtr params = NULL;
656 int ret = virDomainBlockStatsFlags(dom, path, NULL, &nparams, 0);
657 if (ret < 0 || nparams == 0) {
658 VIRT_ERROR(conn, "getting the disk params count");
662 params = calloc(nparams, sizeof(virTypedParameter));
663 if (params == NULL) {
664 ERROR("virt plugin: alloc(%i) for block=%s parameters failed.", nparams,
668 ret = virDomainBlockStatsFlags(dom, path, params, &nparams, 0);
670 VIRT_ERROR(conn, "getting the disk params values");
674 rc = get_block_info(binfo, params, nparams);
677 virTypedParamsFree(params, nparams);
680 return virDomainBlockStats(dom, path, &(binfo->bi), sizeof(binfo->bi));
681 #endif /* HAVE_BLOCK_STATS_FLAGS */
684 static int lv_read(user_data_t *ud) {
686 struct lv_read_instance *inst = NULL;
687 struct lv_read_state *state = NULL;
689 if (ud->data == NULL) {
690 ERROR(PLUGIN_NAME " plugin: NULL userdata");
695 state = &inst->read_state;
698 if (lv_connect() < 0)
704 /* Need to refresh domain or device lists? */
705 if ((last_refresh == (time_t)0) ||
706 ((interval > 0) && ((last_refresh + interval) <= t))) {
707 if (refresh_lists(inst) != 0) {
716 for (int i = 0; i < nr_domains; ++i)
717 fprintf (stderr, "domain %s\n", virDomainGetName (domains[i]));
718 for (int i = 0; i < nr_block_devices; ++i)
719 fprintf (stderr, "block device %d %s:%s\n",
720 i, virDomainGetName (block_devices[i].dom),
721 block_devices[i].path);
722 for (int i = 0; i < nr_interface_devices; ++i)
723 fprintf (stderr, "interface device %d %s:%s\n",
724 i, virDomainGetName (interface_devices[i].dom),
725 interface_devices[i].path);
728 /* Get CPU usage, memory, VCPU usage for each domain. */
729 for (int i = 0; i < state->nr_domains; ++i) {
731 virVcpuInfoPtr vinfo = NULL;
732 virDomainMemoryStatPtr minfo = NULL;
735 status = virDomainGetInfo(state->domains[i], &info);
737 ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
742 if (info.state != VIR_DOMAIN_RUNNING) {
743 /* only gather stats for running domains */
747 cpu_submit(info.cpuTime, state->domains[i], "virt_cpu_total");
748 memory_submit((gauge_t)info.memory * 1024, state->domains[i]);
750 vinfo = malloc(info.nrVirtCpu * sizeof(vinfo[0]));
752 ERROR(PLUGIN_NAME " plugin: malloc failed.");
756 status = virDomainGetVcpus(state->domains[i], vinfo, info.nrVirtCpu,
757 /* cpu map = */ NULL, /* cpu map length = */ 0);
759 ERROR(PLUGIN_NAME " plugin: virDomainGetVcpus failed with status %i.",
765 for (int j = 0; j < info.nrVirtCpu; ++j)
766 vcpu_submit(vinfo[j].cpuTime, state->domains[i], vinfo[j].number,
772 malloc(VIR_DOMAIN_MEMORY_STAT_NR * sizeof(virDomainMemoryStatStruct));
774 ERROR("virt plugin: malloc failed.");
778 status = virDomainMemoryStats(state->domains[i], minfo,
779 VIR_DOMAIN_MEMORY_STAT_NR, 0);
782 ERROR("virt plugin: virDomainMemoryStats failed with status %i.", status);
787 for (int j = 0; j < status; j++) {
788 memory_stats_submit((gauge_t)minfo[j].val * 1024, state->domains[i],
795 /* Get block device stats for each domain. */
796 for (int i = 0; i < state->nr_block_devices; ++i) {
797 struct block_device *bdev = &(state->block_devices[i]);
798 struct lv_block_info binfo;
799 init_block_info(&binfo);
801 if (lv_domain_block_info(bdev->dom, bdev->path, &binfo) < 0)
804 char *type_instance = bdev->path;
806 if (blockdevice_format_basename && blockdevice_format == source) {
807 path = strdup(bdev->path);
810 " plugin: error extracting the basename for '%s', skipped",
814 type_instance = basename(path);
817 disk_submit(&binfo, bdev->dom, type_instance);
820 } /* for (nr_block_devices) */
822 /* Get interface stats for each domain. */
823 for (int i = 0; i < state->nr_interface_devices; ++i) {
824 struct _virDomainInterfaceStats stats;
825 char *display_name = NULL;
827 switch (interface_format) {
829 display_name = state->interface_devices[i].address;
832 display_name = state->interface_devices[i].number;
836 display_name = state->interface_devices[i].path;
839 if (virDomainInterfaceStats(state->interface_devices[i].dom,
840 state->interface_devices[i].path, &stats,
844 if ((stats.rx_bytes != -1) && (stats.tx_bytes != -1))
845 submit_derive2("if_octets", (derive_t)stats.rx_bytes,
846 (derive_t)stats.tx_bytes, state->interface_devices[i].dom,
849 if ((stats.rx_packets != -1) && (stats.tx_packets != -1))
850 submit_derive2("if_packets", (derive_t)stats.rx_packets,
851 (derive_t)stats.tx_packets,
852 state->interface_devices[i].dom, display_name);
854 if ((stats.rx_errs != -1) && (stats.tx_errs != -1))
855 submit_derive2("if_errors", (derive_t)stats.rx_errs,
856 (derive_t)stats.tx_errs, state->interface_devices[i].dom,
859 if ((stats.rx_drop != -1) && (stats.tx_drop != -1))
860 submit_derive2("if_dropped", (derive_t)stats.rx_drop,
861 (derive_t)stats.tx_drop, state->interface_devices[i].dom,
863 } /* for (nr_interface_devices) */
868 static int lv_init_instance(size_t i, plugin_read_cb callback) {
869 struct lv_user_data *lv_ud = &(lv_read_user_data[i]);
870 struct lv_read_instance *inst = &(lv_ud->inst);
872 memset(lv_ud, 0, sizeof(*lv_ud));
874 ssnprintf(inst->tag, sizeof(inst->tag), "%s-%zu", PLUGIN_NAME, i);
877 user_data_t *ud = &(lv_ud->ud);
879 ud->free_func = NULL;
881 INFO(PLUGIN_NAME " plugin: reader %s initialized", inst->tag);
882 return plugin_register_complex_read(NULL, inst->tag, callback, 0, ud);
885 static void lv_clean_read_state(struct lv_read_state *state) {
886 free_block_devices(state);
887 free_interface_devices(state);
891 static void lv_fini_instance(size_t i) {
892 struct lv_read_instance *inst = &(lv_read_user_data[i].inst);
893 struct lv_read_state *state = &(inst->read_state);
895 lv_clean_read_state(state);
896 INFO(PLUGIN_NAME " plugin: reader %s finalized", inst->tag);
899 static int lv_init(void) {
900 if (virInitialize() != 0)
903 if (lv_connect() != 0)
906 DEBUG(PLUGIN_NAME " plugin: starting %i instances", nr_instances);
908 for (int i = 0; i < nr_instances; ++i)
909 lv_init_instance(i, lv_read);
915 * returns 0 on success and <0 on error
917 static int lv_domain_get_tag(xmlXPathContextPtr xpath_ctx, const char *dom_name,
919 char xpath_str[BUFFER_MAX_LEN] = {'\0'};
920 xmlXPathObjectPtr xpath_obj = NULL;
921 xmlNodePtr xml_node = NULL;
925 err = xmlXPathRegisterNs(xpath_ctx,
926 (const xmlChar *)METADATA_VM_PARTITION_PREFIX,
927 (const xmlChar *)METADATA_VM_PARTITION_URI);
929 ERROR(PLUGIN_NAME " plugin: xmlXpathRegisterNs(%s, %s) failed on domain %s",
930 METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_URI, dom_name);
934 ssnprintf(xpath_str, sizeof(xpath_str), "/domain/metadata/%s:%s/text()",
935 METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_ELEMENT);
936 xpath_obj = xmlXPathEvalExpression((xmlChar *)xpath_str, xpath_ctx);
937 if (xpath_obj == NULL) {
938 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) failed on domain %s",
939 xpath_str, dom_name);
943 if (xpath_obj->type != XPATH_NODESET) {
944 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) unexpected return type %d "
945 "(wanted %d) on domain %s",
946 xpath_str, xpath_obj->type, XPATH_NODESET, dom_name);
951 * from now on there is no real error, it's ok if a domain
952 * doesn't have the metadata partition tag.
955 if (xpath_obj->nodesetval == NULL || xpath_obj->nodesetval->nodeNr != 1) {
956 DEBUG(PLUGIN_NAME " plugin: xmlXPathEval(%s) return nodeset size=%i "
957 "expected=1 on domain %s",
959 (xpath_obj->nodesetval == NULL) ? 0 : xpath_obj->nodesetval->nodeNr,
962 xml_node = xpath_obj->nodesetval->nodeTab[0];
963 sstrncpy(dom_tag, (const char *)xml_node->content, PARTITION_TAG_MAX_LEN);
967 /* deregister to clean up */
968 err = xmlXPathRegisterNs(xpath_ctx,
969 (const xmlChar *)METADATA_VM_PARTITION_PREFIX, NULL);
971 /* we can't really recover here */
973 " plugin: deregistration of namespace %s failed for domain %s",
974 METADATA_VM_PARTITION_PREFIX, dom_name);
977 xmlXPathFreeObject(xpath_obj);
982 static int is_known_tag(const char *dom_tag) {
983 for (int i = 0; i < nr_instances; ++i)
984 if (!strcmp(dom_tag, lv_read_user_data[i].inst.tag))
989 static int lv_instance_include_domain(struct lv_read_instance *inst,
990 const char *dom_name,
991 const char *dom_tag) {
992 if ((dom_tag[0] != '\0') && (strcmp(dom_tag, inst->tag) == 0))
995 /* instance#0 will always be there, so it is in charge of extra duties */
997 if (dom_tag[0] == '\0' || !is_known_tag(dom_tag)) {
998 DEBUG(PLUGIN_NAME " plugin#%s: refreshing domain %s "
999 "with unknown tag '%s'",
1000 inst->tag, dom_name, dom_tag);
1008 static int refresh_lists(struct lv_read_instance *inst) {
1009 struct lv_read_state *state = &inst->read_state;
1012 n = virConnectNumOfDomains(conn);
1014 VIRT_ERROR(conn, "reading number of domains");
1018 lv_clean_read_state(state);
1023 /* Get list of domains. */
1024 domids = malloc(sizeof(*domids) * n);
1025 if (domids == NULL) {
1026 ERROR(PLUGIN_NAME " plugin: malloc failed.");
1030 n = virConnectListDomains(conn, domids, n);
1032 VIRT_ERROR(conn, "reading list of domains");
1037 /* Fetch each domain and add it to the list, unless ignore. */
1038 for (int i = 0; i < n; ++i) {
1039 virDomainPtr dom = NULL;
1042 xmlDocPtr xml_doc = NULL;
1043 xmlXPathContextPtr xpath_ctx = NULL;
1044 xmlXPathObjectPtr xpath_obj = NULL;
1045 char tag[PARTITION_TAG_MAX_LEN] = {'\0'};
1047 dom = virDomainLookupByID(conn, domids[i]);
1049 VIRT_ERROR(conn, "virDomainLookupByID");
1050 /* Could be that the domain went away -- ignore it anyway. */
1054 name = virDomainGetName(dom);
1056 VIRT_ERROR(conn, "virDomainGetName");
1060 if (il_domains && ignorelist_match(il_domains, name) != 0)
1063 /* Get a list of devices for this domain. */
1064 xml = virDomainGetXMLDesc(dom, 0);
1066 VIRT_ERROR(conn, "virDomainGetXMLDesc");
1070 /* Yuck, XML. Parse out the devices. */
1071 xml_doc = xmlReadDoc((xmlChar *)xml, NULL, NULL, XML_PARSE_NONET);
1072 if (xml_doc == NULL) {
1073 VIRT_ERROR(conn, "xmlReadDoc");
1077 xpath_ctx = xmlXPathNewContext(xml_doc);
1079 if (lv_domain_get_tag(xpath_ctx, name, tag) < 0) {
1080 ERROR(PLUGIN_NAME " plugin: lv_domain_get_tag failed.");
1084 if (!lv_instance_include_domain(inst, name, tag))
1087 if (add_domain(state, dom) < 0) {
1088 ERROR(PLUGIN_NAME " plugin: malloc failed.");
1092 /* Block devices. */
1093 const char *bd_xmlpath = "/domain/devices/disk/target[@dev]";
1094 if (blockdevice_format == source)
1095 bd_xmlpath = "/domain/devices/disk/source[@dev]";
1096 xpath_obj = xmlXPathEval((const xmlChar *)bd_xmlpath, xpath_ctx);
1098 if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
1099 xpath_obj->nodesetval == NULL)
1102 for (int j = 0; j < xpath_obj->nodesetval->nodeNr; ++j) {
1106 node = xpath_obj->nodesetval->nodeTab[j];
1109 path = (char *)xmlGetProp(node, (xmlChar *)"dev");
1113 if (il_block_devices &&
1114 ignore_device_match(il_block_devices, name, path) != 0)
1117 add_block_device(state, dom, path);
1122 xmlXPathFreeObject(xpath_obj);
1124 /* Network interfaces. */
1125 xpath_obj = xmlXPathEval(
1126 (xmlChar *)"/domain/devices/interface[target[@dev]]", xpath_ctx);
1127 if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
1128 xpath_obj->nodesetval == NULL)
1131 xmlNodeSetPtr xml_interfaces = xpath_obj->nodesetval;
1133 for (int j = 0; j < xml_interfaces->nodeNr; ++j) {
1135 char *address = NULL;
1136 xmlNodePtr xml_interface;
1138 xml_interface = xml_interfaces->nodeTab[j];
1142 for (xmlNodePtr child = xml_interface->children; child;
1143 child = child->next) {
1144 if (child->type != XML_ELEMENT_NODE)
1147 if (xmlStrEqual(child->name, (const xmlChar *)"target")) {
1148 path = (char *)xmlGetProp(child, (const xmlChar *)"dev");
1151 } else if (xmlStrEqual(child->name, (const xmlChar *)"mac")) {
1152 address = (char *)xmlGetProp(child, (const xmlChar *)"address");
1158 if (il_interface_devices &&
1159 (ignore_device_match(il_interface_devices, name, path) != 0 ||
1160 ignore_device_match(il_interface_devices, name, address) != 0))
1163 add_interface_device(state, dom, path, address, j + 1);
1173 xmlXPathFreeObject(xpath_obj);
1175 xmlXPathFreeContext(xpath_ctx);
1177 xmlFreeDoc(xml_doc);
1184 DEBUG(PLUGIN_NAME " plugin#%s: refreshing"
1185 " domains=%i block_devices=%i iface_devices=%i",
1186 inst->tag, state->nr_domains, state->nr_block_devices,
1187 state->nr_interface_devices);
1192 static void free_domains(struct lv_read_state *state) {
1193 if (state->domains) {
1194 for (int i = 0; i < state->nr_domains; ++i)
1195 virDomainFree(state->domains[i]);
1196 sfree(state->domains);
1198 state->domains = NULL;
1199 state->nr_domains = 0;
1202 static int add_domain(struct lv_read_state *state, virDomainPtr dom) {
1203 virDomainPtr *new_ptr;
1204 int new_size = sizeof(state->domains[0]) * (state->nr_domains + 1);
1207 new_ptr = realloc(state->domains, new_size);
1209 new_ptr = malloc(new_size);
1211 if (new_ptr == NULL)
1214 state->domains = new_ptr;
1215 state->domains[state->nr_domains] = dom;
1216 return state->nr_domains++;
1219 static void free_block_devices(struct lv_read_state *state) {
1220 if (state->block_devices) {
1221 for (int i = 0; i < state->nr_block_devices; ++i)
1222 sfree(state->block_devices[i].path);
1223 sfree(state->block_devices);
1225 state->block_devices = NULL;
1226 state->nr_block_devices = 0;
1229 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
1231 struct block_device *new_ptr;
1233 sizeof(state->block_devices[0]) * (state->nr_block_devices + 1);
1236 path_copy = strdup(path);
1240 if (state->block_devices)
1241 new_ptr = realloc(state->block_devices, new_size);
1243 new_ptr = malloc(new_size);
1245 if (new_ptr == NULL) {
1249 state->block_devices = new_ptr;
1250 state->block_devices[state->nr_block_devices].dom = dom;
1251 state->block_devices[state->nr_block_devices].path = path_copy;
1252 return state->nr_block_devices++;
1255 static void free_interface_devices(struct lv_read_state *state) {
1256 if (state->interface_devices) {
1257 for (int i = 0; i < state->nr_interface_devices; ++i) {
1258 sfree(state->interface_devices[i].path);
1259 sfree(state->interface_devices[i].address);
1260 sfree(state->interface_devices[i].number);
1262 sfree(state->interface_devices);
1264 state->interface_devices = NULL;
1265 state->nr_interface_devices = 0;
1268 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
1269 const char *path, const char *address,
1270 unsigned int number) {
1271 struct interface_device *new_ptr;
1273 sizeof(state->interface_devices[0]) * (state->nr_interface_devices + 1);
1274 char *path_copy, *address_copy, number_string[15];
1276 if ((path == NULL) || (address == NULL))
1279 path_copy = strdup(path);
1283 address_copy = strdup(address);
1284 if (!address_copy) {
1289 snprintf(number_string, sizeof(number_string), "interface-%u", number);
1291 if (state->interface_devices)
1292 new_ptr = realloc(state->interface_devices, new_size);
1294 new_ptr = malloc(new_size);
1296 if (new_ptr == NULL) {
1298 sfree(address_copy);
1301 state->interface_devices = new_ptr;
1302 state->interface_devices[state->nr_interface_devices].dom = dom;
1303 state->interface_devices[state->nr_interface_devices].path = path_copy;
1304 state->interface_devices[state->nr_interface_devices].address = address_copy;
1305 state->interface_devices[state->nr_interface_devices].number =
1306 strdup(number_string);
1307 return state->nr_interface_devices++;
1310 static int ignore_device_match(ignorelist_t *il, const char *domname,
1311 const char *devpath) {
1315 if ((domname == NULL) || (devpath == NULL))
1318 n = sizeof(char) * (strlen(domname) + strlen(devpath) + 2);
1321 ERROR(PLUGIN_NAME " plugin: malloc failed.");
1324 ssnprintf(name, n, "%s:%s", domname, devpath);
1325 r = ignorelist_match(il, name);
1330 static int lv_shutdown(void) {
1331 for (int i = 0; i < nr_instances; ++i) {
1332 lv_fini_instance(i);
1337 ignorelist_free(il_domains);
1339 ignorelist_free(il_block_devices);
1340 il_block_devices = NULL;
1341 ignorelist_free(il_interface_devices);
1342 il_interface_devices = NULL;
1347 void module_register(void) {
1348 plugin_register_config(PLUGIN_NAME, lv_config, config_keys, NR_CONFIG_KEYS);
1349 plugin_register_init(PLUGIN_NAME, lv_init);
1350 plugin_register_shutdown(PLUGIN_NAME, lv_shutdown);