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
42 #if LIBVIR_CHECK_VERSION(0, 9, 5)
43 #define HAVE_BLOCK_STATS_FLAGS 1
46 #if LIBVIR_CHECK_VERSION(0, 9, 11)
47 #define HAVE_CPU_STATS 1
50 #endif /* LIBVIR_CHECK_VERSION */
52 static const char *config_keys[] = {"Connection",
59 "BlockDeviceFormatBasename",
66 "PluginInstanceFormat",
72 #define NR_CONFIG_KEYS ((sizeof config_keys / sizeof config_keys[0]) - 1)
75 static virConnectPtr conn = 0;
76 static char *conn_string = NULL;
77 static c_complain_t conn_complain = C_COMPLAIN_INIT_STATIC;
79 /* Seconds between list refreshes, 0 disables completely. */
80 static int interval = 60;
82 /* List of domains, if specified. */
83 static ignorelist_t *il_domains = NULL;
84 /* List of block devices, if specified. */
85 static ignorelist_t *il_block_devices = NULL;
86 /* List of network interface devices, if specified. */
87 static ignorelist_t *il_interface_devices = NULL;
89 static int ignore_device_match(ignorelist_t *, const char *domname,
92 /* Actual list of block devices found on last refresh. */
94 virDomainPtr dom; /* domain */
95 char *path; /* name of block device */
98 /* Actual list of network interfaces found on last refresh. */
99 struct interface_device {
100 virDomainPtr dom; /* domain */
101 char *path; /* name of interface device */
102 char *address; /* mac address of interface device */
103 char *number; /* interface device number */
106 struct lv_read_state {
107 /* Actual list of domains found on last refresh. */
108 virDomainPtr *domains;
111 struct block_device *block_devices;
112 int nr_block_devices;
114 struct interface_device *interface_devices;
115 int nr_interface_devices;
118 static void free_domains(struct lv_read_state *state);
119 static int add_domain(struct lv_read_state *state, virDomainPtr dom);
121 static void free_block_devices(struct lv_read_state *state);
122 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
125 static void free_interface_devices(struct lv_read_state *state);
126 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
127 const char *path, const char *address,
128 unsigned int number);
130 #define METADATA_VM_PARTITION_URI "http://ovirt.org/ovirtmap/tag/1.0"
131 #define METADATA_VM_PARTITION_ELEMENT "tag"
132 #define METADATA_VM_PARTITION_PREFIX "ovirtmap"
134 #define BUFFER_MAX_LEN 256
135 #define PARTITION_TAG_MAX_LEN 32
137 struct lv_read_instance {
138 struct lv_read_state read_state;
139 char tag[PARTITION_TAG_MAX_LEN];
143 struct lv_user_data {
144 struct lv_read_instance inst;
148 #define NR_INSTANCES_DEFAULT 1
149 #define NR_INSTANCES_MAX 128
150 static int nr_instances = NR_INSTANCES_DEFAULT;
151 static struct lv_user_data lv_read_user_data[NR_INSTANCES_MAX];
153 /* HostnameFormat. */
154 #define HF_MAX_FIELDS 3
156 enum hf_field { hf_none = 0, hf_hostname, hf_name, hf_uuid };
158 static enum hf_field hostname_format[HF_MAX_FIELDS] = {hf_name};
160 /* PluginInstanceFormat */
161 #define PLGINST_MAX_FIELDS 2
163 enum plginst_field { plginst_none = 0, plginst_name, plginst_uuid };
165 static enum plginst_field plugin_instance_format[PLGINST_MAX_FIELDS] = {
168 /* BlockDeviceFormat */
169 enum bd_field { target, source };
171 /* InterfaceFormat. */
172 enum if_field { if_address, if_name, if_number };
175 #define EX_STATS_MAX_FIELDS 8
176 enum ex_stats { ex_stats_none = 0, ex_stats_disk = 1, ex_stats_pcpu = 2 };
177 static unsigned int extra_stats = ex_stats_none;
179 struct ex_stats_item {
183 static const struct ex_stats_item ex_stats_table[] = {
184 {"disk", ex_stats_disk}, {"pcpu", ex_stats_pcpu}, {NULL, ex_stats_none},
187 /* BlockDeviceFormatBasename */
188 _Bool blockdevice_format_basename = 0;
189 static enum bd_field blockdevice_format = target;
190 static enum if_field interface_format = if_name;
192 /* Time that we last refreshed. */
193 static time_t last_refresh = (time_t)0;
195 static int refresh_lists(struct lv_read_instance *inst);
199 unsigned long long total_user_cpu_time;
200 unsigned long long total_syst_cpu_time;
203 struct lv_block_info {
204 virDomainBlockStatsStruct bi;
206 long long rd_total_times;
207 long long wr_total_times;
210 long long fl_total_times;
213 static void init_block_info(struct lv_block_info *binfo) {
217 binfo->bi.rd_req = -1;
218 binfo->bi.wr_req = -1;
219 binfo->bi.rd_bytes = -1;
220 binfo->bi.wr_bytes = -1;
222 binfo->rd_total_times = -1;
223 binfo->wr_total_times = -1;
225 binfo->fl_total_times = -1;
228 #ifdef HAVE_BLOCK_STATS_FLAGS
230 #define GET_BLOCK_INFO_VALUE(NAME, FIELD) \
232 if (!strcmp(param[i].field, NAME)) { \
233 binfo->FIELD = param[i].value.l; \
238 static int get_block_info(struct lv_block_info *binfo,
239 virTypedParameterPtr param, int nparams) {
240 if (binfo == NULL || param == NULL)
243 for (int i = 0; i < nparams; ++i) {
244 /* ignore type. Everything must be LLONG anyway. */
245 GET_BLOCK_INFO_VALUE("rd_operations", bi.rd_req);
246 GET_BLOCK_INFO_VALUE("wr_operations", bi.wr_req);
247 GET_BLOCK_INFO_VALUE("rd_bytes", bi.rd_bytes);
248 GET_BLOCK_INFO_VALUE("wr_bytes", bi.wr_bytes);
249 GET_BLOCK_INFO_VALUE("rd_total_times", rd_total_times);
250 GET_BLOCK_INFO_VALUE("wr_total_times", wr_total_times);
251 GET_BLOCK_INFO_VALUE("flush_operations", fl_req);
252 GET_BLOCK_INFO_VALUE("flush_total_times", fl_total_times);
258 #undef GET_BLOCK_INFO_VALUE
260 #endif /* HAVE_BLOCK_STATS_FLAGS */
262 /* ERROR(...) macro for virterrors. */
263 #define VIRT_ERROR(conn, s) \
266 err = (conn) ? virConnGetLastError((conn)) : virGetLastError(); \
268 ERROR("%s: %s", (s), err->message); \
271 static void init_lv_info(struct lv_info *info) {
273 memset(info, 0, sizeof(*info));
276 static int lv_domain_info(virDomainPtr dom, struct lv_info *info) {
277 #ifdef HAVE_CPU_STATS
278 virTypedParameterPtr param = NULL;
280 #endif /* HAVE_CPU_STATS */
281 int ret = virDomainGetInfo(dom, &(info->di));
286 #ifdef HAVE_CPU_STATS
287 nparams = virDomainGetCPUStats(dom, NULL, 0, -1, 1, 0);
289 VIRT_ERROR(conn, "getting the CPU params count");
293 param = calloc(nparams, sizeof(virTypedParameter));
295 ERROR("virt plugin: alloc(%i) for cpu parameters failed.", nparams);
299 ret = virDomainGetCPUStats(dom, param, nparams, -1, 1, 0); // total stats.
301 virTypedParamsFree(param, nparams);
302 VIRT_ERROR(conn, "getting the disk params values");
306 for (int i = 0; i < nparams; ++i) {
307 if (!strcmp(param[i].field, "user_time"))
308 info->total_user_cpu_time = param[i].value.ul;
309 else if (!strcmp(param[i].field, "system_time"))
310 info->total_syst_cpu_time = param[i].value.ul;
313 virTypedParamsFree(param, nparams);
314 #endif /* HAVE_CPU_STATS */
319 static void init_value_list(value_list_t *vl, virDomainPtr dom) {
322 char uuid[VIR_UUID_STRING_BUFLEN];
324 sstrncpy(vl->plugin, PLUGIN_NAME, sizeof(vl->plugin));
328 /* Construct the hostname field according to HostnameFormat. */
329 for (int i = 0; i < HF_MAX_FIELDS; ++i) {
330 if (hostname_format[i] == hf_none)
333 n = DATA_MAX_NAME_LEN - strlen(vl->host) - 2;
335 if (i > 0 && n >= 1) {
336 strncat(vl->host, ":", 1);
340 switch (hostname_format[i]) {
344 strncat(vl->host, hostname_g, n);
347 name = virDomainGetName(dom);
349 strncat(vl->host, name, n);
352 if (virDomainGetUUIDString(dom, uuid) == 0)
353 strncat(vl->host, uuid, n);
358 vl->host[sizeof(vl->host) - 1] = '\0';
360 /* Construct the plugin instance field according to PluginInstanceFormat. */
361 for (int i = 0; i < PLGINST_MAX_FIELDS; ++i) {
362 if (plugin_instance_format[i] == plginst_none)
365 n = sizeof(vl->plugin_instance) - strlen(vl->plugin_instance) - 2;
367 if (i > 0 && n >= 1) {
368 strncat(vl->plugin_instance, ":", 1);
372 switch (plugin_instance_format[i]) {
376 name = virDomainGetName(dom);
378 strncat(vl->plugin_instance, name, n);
381 if (virDomainGetUUIDString(dom, uuid) == 0)
382 strncat(vl->plugin_instance, uuid, n);
387 vl->plugin_instance[sizeof(vl->plugin_instance) - 1] = '\0';
389 } /* void init_value_list */
391 static void submit(virDomainPtr dom, char const *type,
392 char const *type_instance, value_t *values,
394 value_list_t vl = VALUE_LIST_INIT;
395 init_value_list(&vl, dom);
398 vl.values_len = values_len;
400 sstrncpy(vl.type, type, sizeof(vl.type));
401 if (type_instance != NULL)
402 sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
404 plugin_dispatch_values(&vl);
407 static void memory_submit(gauge_t value, virDomainPtr dom) {
408 submit(dom, "memory", "total", &(value_t){.gauge = value}, 1);
411 static void memory_stats_submit(gauge_t value, virDomainPtr dom,
413 static const char *tags[] = {"swap_in", "swap_out", "major_fault",
414 "minor_fault", "unused", "available",
415 "actual_balloon", "rss"};
417 if ((tag_index < 0) || (tag_index >= STATIC_ARRAY_SIZE(tags))) {
418 ERROR("virt plugin: Array index out of bounds: tag_index = %d", tag_index);
422 submit(dom, "memory", tags[tag_index], &(value_t){.gauge = value}, 1);
425 static void submit_derive2(const char *type, derive_t v0, derive_t v1,
426 virDomainPtr dom, const char *devname) {
428 {.derive = v0}, {.derive = v1},
431 submit(dom, type, devname, values, STATIC_ARRAY_SIZE(values));
432 } /* void submit_derive2 */
434 static void pcpu_submit(virDomainPtr dom, struct lv_info *info) {
435 #ifdef HAVE_CPU_STATS
436 if (extra_stats & ex_stats_pcpu)
437 submit_derive2("ps_cputime", info->total_user_cpu_time,
438 info->total_syst_cpu_time, dom, NULL);
439 #endif /* HAVE_CPU_STATS */
442 static void cpu_submit(unsigned long long value, virDomainPtr dom,
444 submit(dom, type, NULL, &(value_t){.derive = (derive_t)value}, 1);
447 static void vcpu_submit(derive_t value, virDomainPtr dom, int vcpu_nr,
449 char type_instance[DATA_MAX_NAME_LEN];
451 ssnprintf(type_instance, sizeof(type_instance), "%d", vcpu_nr);
453 submit(dom, type, type_instance, &(value_t){.derive = value}, 1);
456 static void disk_submit(struct lv_block_info *binfo, virDomainPtr dom,
457 const char *type_instance) {
458 char flush_type_instance[DATA_MAX_NAME_LEN];
460 ssnprintf(flush_type_instance, sizeof(flush_type_instance), "flush-%s",
463 if ((binfo->bi.rd_req != -1) && (binfo->bi.wr_req != -1))
464 submit_derive2("disk_ops", (derive_t)binfo->bi.rd_req,
465 (derive_t)binfo->bi.wr_req, dom, type_instance);
467 if ((binfo->bi.rd_bytes != -1) && (binfo->bi.wr_bytes != -1))
468 submit_derive2("disk_octets", (derive_t)binfo->bi.rd_bytes,
469 (derive_t)binfo->bi.wr_bytes, dom, type_instance);
471 if (extra_stats & ex_stats_disk) {
472 if ((binfo->rd_total_times != -1) && (binfo->wr_total_times != -1))
473 submit_derive2("disk_time", (derive_t)binfo->rd_total_times,
474 (derive_t)binfo->wr_total_times, dom, type_instance);
476 if (binfo->fl_req != -1)
477 submit(dom, "total_requests", flush_type_instance,
478 &(value_t){.derive = (derive_t)binfo->fl_req}, 1);
479 if (binfo->fl_total_times != -1) {
480 derive_t value = binfo->fl_total_times / 1000; // ns -> ms
481 submit(dom, "total_time_in_ms", flush_type_instance,
482 &(value_t){.derive = value}, 1);
487 static unsigned int parse_ex_stats_flags(char **exstats, int numexstats) {
488 unsigned int ex_stats_flags = ex_stats_none;
489 for (int i = 0; i < numexstats; i++) {
490 for (int j = 0; ex_stats_table[j].name != NULL; j++) {
491 if (strcasecmp(exstats[i], ex_stats_table[j].name) == 0) {
492 DEBUG(PLUGIN_NAME " plugin: enabling extra stats for '%s'",
493 ex_stats_table[j].name);
494 ex_stats_flags |= ex_stats_table[j].flag;
499 return ex_stats_flags;
502 static int lv_config(const char *key, const char *value) {
503 if (virInitialize() != 0)
506 if (il_domains == NULL)
507 il_domains = ignorelist_create(1);
508 if (il_block_devices == NULL)
509 il_block_devices = ignorelist_create(1);
510 if (il_interface_devices == NULL)
511 il_interface_devices = ignorelist_create(1);
513 if (strcasecmp(key, "Connection") == 0) {
514 char *tmp = strdup(value);
516 ERROR(PLUGIN_NAME " plugin: Connection strdup failed.");
524 if (strcasecmp(key, "RefreshInterval") == 0) {
526 interval = strtol(value, &eptr, 10);
527 if (eptr == NULL || *eptr != '\0')
532 if (strcasecmp(key, "Domain") == 0) {
533 if (ignorelist_add(il_domains, value))
537 if (strcasecmp(key, "BlockDevice") == 0) {
538 if (ignorelist_add(il_block_devices, value))
543 if (strcasecmp(key, "BlockDeviceFormat") == 0) {
544 if (strcasecmp(value, "target") == 0)
545 blockdevice_format = target;
546 else if (strcasecmp(value, "source") == 0)
547 blockdevice_format = source;
549 ERROR(PLUGIN_NAME " plugin: unknown BlockDeviceFormat: %s", value);
554 if (strcasecmp(key, "BlockDeviceFormatBasename") == 0) {
555 blockdevice_format_basename = IS_TRUE(value);
558 if (strcasecmp(key, "InterfaceDevice") == 0) {
559 if (ignorelist_add(il_interface_devices, value))
564 if (strcasecmp(key, "IgnoreSelected") == 0) {
565 if (IS_TRUE(value)) {
566 ignorelist_set_invert(il_domains, 0);
567 ignorelist_set_invert(il_block_devices, 0);
568 ignorelist_set_invert(il_interface_devices, 0);
570 ignorelist_set_invert(il_domains, 1);
571 ignorelist_set_invert(il_block_devices, 1);
572 ignorelist_set_invert(il_interface_devices, 1);
577 if (strcasecmp(key, "HostnameFormat") == 0) {
579 char *fields[HF_MAX_FIELDS];
582 value_copy = strdup(value);
583 if (value_copy == NULL) {
584 ERROR(PLUGIN_NAME " plugin: strdup failed.");
588 n = strsplit(value_copy, fields, HF_MAX_FIELDS);
591 ERROR(PLUGIN_NAME " plugin: HostnameFormat: no fields");
595 for (int i = 0; i < n; ++i) {
596 if (strcasecmp(fields[i], "hostname") == 0)
597 hostname_format[i] = hf_hostname;
598 else if (strcasecmp(fields[i], "name") == 0)
599 hostname_format[i] = hf_name;
600 else if (strcasecmp(fields[i], "uuid") == 0)
601 hostname_format[i] = hf_uuid;
603 ERROR(PLUGIN_NAME " plugin: unknown HostnameFormat field: %s",
611 for (int i = n; i < HF_MAX_FIELDS; ++i)
612 hostname_format[i] = hf_none;
617 if (strcasecmp(key, "PluginInstanceFormat") == 0) {
619 char *fields[PLGINST_MAX_FIELDS];
622 value_copy = strdup(value);
623 if (value_copy == NULL) {
624 ERROR(PLUGIN_NAME " plugin: strdup failed.");
628 n = strsplit(value_copy, fields, PLGINST_MAX_FIELDS);
631 ERROR(PLUGIN_NAME " plugin: PluginInstanceFormat: no fields");
635 for (int i = 0; i < n; ++i) {
636 if (strcasecmp(fields[i], "none") == 0) {
637 plugin_instance_format[i] = plginst_none;
639 } else if (strcasecmp(fields[i], "name") == 0)
640 plugin_instance_format[i] = plginst_name;
641 else if (strcasecmp(fields[i], "uuid") == 0)
642 plugin_instance_format[i] = plginst_uuid;
644 ERROR(PLUGIN_NAME " plugin: unknown PluginInstanceFormat field: %s",
652 for (int i = n; i < PLGINST_MAX_FIELDS; ++i)
653 plugin_instance_format[i] = plginst_none;
658 if (strcasecmp(key, "InterfaceFormat") == 0) {
659 if (strcasecmp(value, "name") == 0)
660 interface_format = if_name;
661 else if (strcasecmp(value, "address") == 0)
662 interface_format = if_address;
663 else if (strcasecmp(value, "number") == 0)
664 interface_format = if_number;
666 ERROR(PLUGIN_NAME " plugin: unknown InterfaceFormat: %s", value);
672 if (strcasecmp(key, "Instances") == 0) {
674 double val = strtod(value, &eptr);
677 ERROR(PLUGIN_NAME " plugin: Invalid value for Instances = '%s'", value);
681 ERROR(PLUGIN_NAME " plugin: Instances <= 0 makes no sense.");
684 if (val > NR_INSTANCES_MAX) {
685 ERROR(PLUGIN_NAME " plugin: Instances=%f > NR_INSTANCES_MAX=%i"
686 " use a lower setting or recompile the plugin.",
687 val, NR_INSTANCES_MAX);
691 nr_instances = (int)val;
692 DEBUG(PLUGIN_NAME " plugin: configured %i instances", nr_instances);
696 if (strcasecmp(key, "ExtraStats") == 0) {
697 char *localvalue = strdup(value);
698 if (localvalue != NULL) {
699 char *exstats[EX_STATS_MAX_FIELDS];
701 strsplit(localvalue, exstats, STATIC_ARRAY_SIZE(exstats));
702 extra_stats = parse_ex_stats_flags(exstats, numexstats);
707 /* Unrecognised option. */
711 static int lv_connect(void) {
713 /* `conn_string == NULL' is acceptable. */
714 conn = virConnectOpenReadOnly(conn_string);
716 c_complain(LOG_ERR, &conn_complain,
717 PLUGIN_NAME " plugin: Unable to connect: "
718 "virConnectOpenReadOnly failed.");
722 c_release(LOG_NOTICE, &conn_complain,
723 PLUGIN_NAME " plugin: Connection established.");
727 static void lv_disconnect(void) {
729 virConnectClose(conn);
731 WARNING(PLUGIN_NAME " plugin: closed connection to libvirt");
734 static int lv_domain_block_info(virDomainPtr dom, const char *path,
735 struct lv_block_info *binfo) {
736 #ifdef HAVE_BLOCK_STATS_FLAGS
737 virTypedParameterPtr params = NULL;
740 int ret = virDomainBlockStatsFlags(dom, path, NULL, &nparams, 0);
741 if (ret < 0 || nparams == 0) {
742 VIRT_ERROR(conn, "getting the disk params count");
746 params = calloc(nparams, sizeof(virTypedParameter));
747 if (params == NULL) {
748 ERROR("virt plugin: alloc(%i) for block=%s parameters failed.", nparams,
752 ret = virDomainBlockStatsFlags(dom, path, params, &nparams, 0);
754 VIRT_ERROR(conn, "getting the disk params values");
758 rc = get_block_info(binfo, params, nparams);
761 virTypedParamsFree(params, nparams);
764 return virDomainBlockStats(dom, path, &(binfo->bi), sizeof(binfo->bi));
765 #endif /* HAVE_BLOCK_STATS_FLAGS */
768 static int lv_read(user_data_t *ud) {
770 struct lv_read_instance *inst = NULL;
771 struct lv_read_state *state = NULL;
773 if (ud->data == NULL) {
774 ERROR(PLUGIN_NAME " plugin: NULL userdata");
779 state = &inst->read_state;
782 if (lv_connect() < 0)
788 /* Need to refresh domain or device lists? */
789 if ((last_refresh == (time_t)0) ||
790 ((interval > 0) && ((last_refresh + interval) <= t))) {
791 if (refresh_lists(inst) != 0) {
800 for (int i = 0; i < nr_domains; ++i)
801 fprintf (stderr, "domain %s\n", virDomainGetName (domains[i]));
802 for (int i = 0; i < nr_block_devices; ++i)
803 fprintf (stderr, "block device %d %s:%s\n",
804 i, virDomainGetName (block_devices[i].dom),
805 block_devices[i].path);
806 for (int i = 0; i < nr_interface_devices; ++i)
807 fprintf (stderr, "interface device %d %s:%s\n",
808 i, virDomainGetName (interface_devices[i].dom),
809 interface_devices[i].path);
812 /* Get CPU usage, memory, VCPU usage for each domain. */
813 for (int i = 0; i < state->nr_domains; ++i) {
815 virVcpuInfoPtr vinfo = NULL;
816 virDomainMemoryStatPtr minfo = NULL;
820 status = lv_domain_info(state->domains[i], &info);
822 ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
827 if (info.di.state != VIR_DOMAIN_RUNNING) {
828 /* only gather stats for running domains */
832 pcpu_submit(state->domains[i], &info);
833 cpu_submit(info.di.cpuTime, state->domains[i], "virt_cpu_total");
834 memory_submit((gauge_t)info.di.memory * 1024, state->domains[i]);
836 vinfo = malloc(info.di.nrVirtCpu * sizeof(vinfo[0]));
838 ERROR(PLUGIN_NAME " plugin: malloc failed.");
842 status = virDomainGetVcpus(state->domains[i], vinfo, info.di.nrVirtCpu,
843 /* cpu map = */ NULL, /* cpu map length = */ 0);
845 ERROR(PLUGIN_NAME " plugin: virDomainGetVcpus failed with status %i.",
851 for (int j = 0; j < info.di.nrVirtCpu; ++j)
852 vcpu_submit(vinfo[j].cpuTime, state->domains[i], vinfo[j].number,
858 malloc(VIR_DOMAIN_MEMORY_STAT_NR * sizeof(virDomainMemoryStatStruct));
860 ERROR("virt plugin: malloc failed.");
864 status = virDomainMemoryStats(state->domains[i], minfo,
865 VIR_DOMAIN_MEMORY_STAT_NR, 0);
868 ERROR("virt plugin: virDomainMemoryStats failed with status %i.", status);
873 for (int j = 0; j < status; j++) {
874 memory_stats_submit((gauge_t)minfo[j].val * 1024, state->domains[i],
881 /* Get block device stats for each domain. */
882 for (int i = 0; i < state->nr_block_devices; ++i) {
883 struct block_device *bdev = &(state->block_devices[i]);
884 struct lv_block_info binfo;
885 init_block_info(&binfo);
887 if (lv_domain_block_info(bdev->dom, bdev->path, &binfo) < 0)
890 char *type_instance = bdev->path;
892 if (blockdevice_format_basename && blockdevice_format == source) {
893 path = strdup(bdev->path);
896 " plugin: error extracting the basename for '%s', skipped",
900 type_instance = basename(path);
903 disk_submit(&binfo, bdev->dom, type_instance);
906 } /* for (nr_block_devices) */
908 /* Get interface stats for each domain. */
909 for (int i = 0; i < state->nr_interface_devices; ++i) {
910 struct _virDomainInterfaceStats stats;
911 char *display_name = NULL;
913 switch (interface_format) {
915 display_name = state->interface_devices[i].address;
918 display_name = state->interface_devices[i].number;
922 display_name = state->interface_devices[i].path;
925 if (virDomainInterfaceStats(state->interface_devices[i].dom,
926 state->interface_devices[i].path, &stats,
930 if ((stats.rx_bytes != -1) && (stats.tx_bytes != -1))
931 submit_derive2("if_octets", (derive_t)stats.rx_bytes,
932 (derive_t)stats.tx_bytes, state->interface_devices[i].dom,
935 if ((stats.rx_packets != -1) && (stats.tx_packets != -1))
936 submit_derive2("if_packets", (derive_t)stats.rx_packets,
937 (derive_t)stats.tx_packets,
938 state->interface_devices[i].dom, display_name);
940 if ((stats.rx_errs != -1) && (stats.tx_errs != -1))
941 submit_derive2("if_errors", (derive_t)stats.rx_errs,
942 (derive_t)stats.tx_errs, state->interface_devices[i].dom,
945 if ((stats.rx_drop != -1) && (stats.tx_drop != -1))
946 submit_derive2("if_dropped", (derive_t)stats.rx_drop,
947 (derive_t)stats.tx_drop, state->interface_devices[i].dom,
949 } /* for (nr_interface_devices) */
954 static int lv_init_instance(size_t i, plugin_read_cb callback) {
955 struct lv_user_data *lv_ud = &(lv_read_user_data[i]);
956 struct lv_read_instance *inst = &(lv_ud->inst);
958 memset(lv_ud, 0, sizeof(*lv_ud));
960 ssnprintf(inst->tag, sizeof(inst->tag), "%s-%zu", PLUGIN_NAME, i);
963 user_data_t *ud = &(lv_ud->ud);
965 ud->free_func = NULL;
967 INFO(PLUGIN_NAME " plugin: reader %s initialized", inst->tag);
968 return plugin_register_complex_read(NULL, inst->tag, callback, 0, ud);
971 static void lv_clean_read_state(struct lv_read_state *state) {
972 free_block_devices(state);
973 free_interface_devices(state);
977 static void lv_fini_instance(size_t i) {
978 struct lv_read_instance *inst = &(lv_read_user_data[i].inst);
979 struct lv_read_state *state = &(inst->read_state);
981 lv_clean_read_state(state);
982 INFO(PLUGIN_NAME " plugin: reader %s finalized", inst->tag);
985 static int lv_init(void) {
986 if (virInitialize() != 0)
989 if (lv_connect() != 0)
992 DEBUG(PLUGIN_NAME " plugin: starting %i instances", nr_instances);
994 for (int i = 0; i < nr_instances; ++i)
995 lv_init_instance(i, lv_read);
1001 * returns 0 on success and <0 on error
1003 static int lv_domain_get_tag(xmlXPathContextPtr xpath_ctx, const char *dom_name,
1005 char xpath_str[BUFFER_MAX_LEN] = {'\0'};
1006 xmlXPathObjectPtr xpath_obj = NULL;
1007 xmlNodePtr xml_node = NULL;
1011 err = xmlXPathRegisterNs(xpath_ctx,
1012 (const xmlChar *)METADATA_VM_PARTITION_PREFIX,
1013 (const xmlChar *)METADATA_VM_PARTITION_URI);
1015 ERROR(PLUGIN_NAME " plugin: xmlXpathRegisterNs(%s, %s) failed on domain %s",
1016 METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_URI, dom_name);
1020 ssnprintf(xpath_str, sizeof(xpath_str), "/domain/metadata/%s:%s/text()",
1021 METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_ELEMENT);
1022 xpath_obj = xmlXPathEvalExpression((xmlChar *)xpath_str, xpath_ctx);
1023 if (xpath_obj == NULL) {
1024 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) failed on domain %s",
1025 xpath_str, dom_name);
1029 if (xpath_obj->type != XPATH_NODESET) {
1030 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) unexpected return type %d "
1031 "(wanted %d) on domain %s",
1032 xpath_str, xpath_obj->type, XPATH_NODESET, dom_name);
1037 * from now on there is no real error, it's ok if a domain
1038 * doesn't have the metadata partition tag.
1041 if (xpath_obj->nodesetval == NULL || xpath_obj->nodesetval->nodeNr != 1) {
1042 DEBUG(PLUGIN_NAME " plugin: xmlXPathEval(%s) return nodeset size=%i "
1043 "expected=1 on domain %s",
1045 (xpath_obj->nodesetval == NULL) ? 0 : xpath_obj->nodesetval->nodeNr,
1048 xml_node = xpath_obj->nodesetval->nodeTab[0];
1049 sstrncpy(dom_tag, (const char *)xml_node->content, PARTITION_TAG_MAX_LEN);
1053 /* deregister to clean up */
1054 err = xmlXPathRegisterNs(xpath_ctx,
1055 (const xmlChar *)METADATA_VM_PARTITION_PREFIX, NULL);
1057 /* we can't really recover here */
1059 " plugin: deregistration of namespace %s failed for domain %s",
1060 METADATA_VM_PARTITION_PREFIX, dom_name);
1063 xmlXPathFreeObject(xpath_obj);
1068 static int is_known_tag(const char *dom_tag) {
1069 for (int i = 0; i < nr_instances; ++i)
1070 if (!strcmp(dom_tag, lv_read_user_data[i].inst.tag))
1075 static int lv_instance_include_domain(struct lv_read_instance *inst,
1076 const char *dom_name,
1077 const char *dom_tag) {
1078 if ((dom_tag[0] != '\0') && (strcmp(dom_tag, inst->tag) == 0))
1081 /* instance#0 will always be there, so it is in charge of extra duties */
1082 if (inst->id == 0) {
1083 if (dom_tag[0] == '\0' || !is_known_tag(dom_tag)) {
1084 DEBUG(PLUGIN_NAME " plugin#%s: refreshing domain %s "
1085 "with unknown tag '%s'",
1086 inst->tag, dom_name, dom_tag);
1094 static int refresh_lists(struct lv_read_instance *inst) {
1095 struct lv_read_state *state = &inst->read_state;
1098 n = virConnectNumOfDomains(conn);
1100 VIRT_ERROR(conn, "reading number of domains");
1104 lv_clean_read_state(state);
1109 /* Get list of domains. */
1110 domids = malloc(sizeof(*domids) * n);
1111 if (domids == NULL) {
1112 ERROR(PLUGIN_NAME " plugin: malloc failed.");
1116 n = virConnectListDomains(conn, domids, n);
1118 VIRT_ERROR(conn, "reading list of domains");
1123 /* Fetch each domain and add it to the list, unless ignore. */
1124 for (int i = 0; i < n; ++i) {
1125 virDomainPtr dom = NULL;
1128 xmlDocPtr xml_doc = NULL;
1129 xmlXPathContextPtr xpath_ctx = NULL;
1130 xmlXPathObjectPtr xpath_obj = NULL;
1131 char tag[PARTITION_TAG_MAX_LEN] = {'\0'};
1133 dom = virDomainLookupByID(conn, domids[i]);
1135 VIRT_ERROR(conn, "virDomainLookupByID");
1136 /* Could be that the domain went away -- ignore it anyway. */
1140 name = virDomainGetName(dom);
1142 VIRT_ERROR(conn, "virDomainGetName");
1146 if (il_domains && ignorelist_match(il_domains, name) != 0)
1149 /* Get a list of devices for this domain. */
1150 xml = virDomainGetXMLDesc(dom, 0);
1152 VIRT_ERROR(conn, "virDomainGetXMLDesc");
1156 /* Yuck, XML. Parse out the devices. */
1157 xml_doc = xmlReadDoc((xmlChar *)xml, NULL, NULL, XML_PARSE_NONET);
1158 if (xml_doc == NULL) {
1159 VIRT_ERROR(conn, "xmlReadDoc");
1163 xpath_ctx = xmlXPathNewContext(xml_doc);
1165 if (lv_domain_get_tag(xpath_ctx, name, tag) < 0) {
1166 ERROR(PLUGIN_NAME " plugin: lv_domain_get_tag failed.");
1170 if (!lv_instance_include_domain(inst, name, tag))
1173 if (add_domain(state, dom) < 0) {
1174 ERROR(PLUGIN_NAME " plugin: malloc failed.");
1178 /* Block devices. */
1179 const char *bd_xmlpath = "/domain/devices/disk/target[@dev]";
1180 if (blockdevice_format == source)
1181 bd_xmlpath = "/domain/devices/disk/source[@dev]";
1182 xpath_obj = xmlXPathEval((const xmlChar *)bd_xmlpath, xpath_ctx);
1184 if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
1185 xpath_obj->nodesetval == NULL)
1188 for (int j = 0; j < xpath_obj->nodesetval->nodeNr; ++j) {
1192 node = xpath_obj->nodesetval->nodeTab[j];
1195 path = (char *)xmlGetProp(node, (xmlChar *)"dev");
1199 if (il_block_devices &&
1200 ignore_device_match(il_block_devices, name, path) != 0)
1203 add_block_device(state, dom, path);
1208 xmlXPathFreeObject(xpath_obj);
1210 /* Network interfaces. */
1211 xpath_obj = xmlXPathEval(
1212 (xmlChar *)"/domain/devices/interface[target[@dev]]", xpath_ctx);
1213 if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
1214 xpath_obj->nodesetval == NULL)
1217 xmlNodeSetPtr xml_interfaces = xpath_obj->nodesetval;
1219 for (int j = 0; j < xml_interfaces->nodeNr; ++j) {
1221 char *address = NULL;
1222 xmlNodePtr xml_interface;
1224 xml_interface = xml_interfaces->nodeTab[j];
1228 for (xmlNodePtr child = xml_interface->children; child;
1229 child = child->next) {
1230 if (child->type != XML_ELEMENT_NODE)
1233 if (xmlStrEqual(child->name, (const xmlChar *)"target")) {
1234 path = (char *)xmlGetProp(child, (const xmlChar *)"dev");
1237 } else if (xmlStrEqual(child->name, (const xmlChar *)"mac")) {
1238 address = (char *)xmlGetProp(child, (const xmlChar *)"address");
1244 if (il_interface_devices &&
1245 (ignore_device_match(il_interface_devices, name, path) != 0 ||
1246 ignore_device_match(il_interface_devices, name, address) != 0))
1249 add_interface_device(state, dom, path, address, j + 1);
1259 xmlXPathFreeObject(xpath_obj);
1261 xmlXPathFreeContext(xpath_ctx);
1263 xmlFreeDoc(xml_doc);
1270 DEBUG(PLUGIN_NAME " plugin#%s: refreshing"
1271 " domains=%i block_devices=%i iface_devices=%i",
1272 inst->tag, state->nr_domains, state->nr_block_devices,
1273 state->nr_interface_devices);
1278 static void free_domains(struct lv_read_state *state) {
1279 if (state->domains) {
1280 for (int i = 0; i < state->nr_domains; ++i)
1281 virDomainFree(state->domains[i]);
1282 sfree(state->domains);
1284 state->domains = NULL;
1285 state->nr_domains = 0;
1288 static int add_domain(struct lv_read_state *state, virDomainPtr dom) {
1289 virDomainPtr *new_ptr;
1290 int new_size = sizeof(state->domains[0]) * (state->nr_domains + 1);
1293 new_ptr = realloc(state->domains, new_size);
1295 new_ptr = malloc(new_size);
1297 if (new_ptr == NULL)
1300 state->domains = new_ptr;
1301 state->domains[state->nr_domains] = dom;
1302 return state->nr_domains++;
1305 static void free_block_devices(struct lv_read_state *state) {
1306 if (state->block_devices) {
1307 for (int i = 0; i < state->nr_block_devices; ++i)
1308 sfree(state->block_devices[i].path);
1309 sfree(state->block_devices);
1311 state->block_devices = NULL;
1312 state->nr_block_devices = 0;
1315 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
1317 struct block_device *new_ptr;
1319 sizeof(state->block_devices[0]) * (state->nr_block_devices + 1);
1322 path_copy = strdup(path);
1326 if (state->block_devices)
1327 new_ptr = realloc(state->block_devices, new_size);
1329 new_ptr = malloc(new_size);
1331 if (new_ptr == NULL) {
1335 state->block_devices = new_ptr;
1336 state->block_devices[state->nr_block_devices].dom = dom;
1337 state->block_devices[state->nr_block_devices].path = path_copy;
1338 return state->nr_block_devices++;
1341 static void free_interface_devices(struct lv_read_state *state) {
1342 if (state->interface_devices) {
1343 for (int i = 0; i < state->nr_interface_devices; ++i) {
1344 sfree(state->interface_devices[i].path);
1345 sfree(state->interface_devices[i].address);
1346 sfree(state->interface_devices[i].number);
1348 sfree(state->interface_devices);
1350 state->interface_devices = NULL;
1351 state->nr_interface_devices = 0;
1354 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
1355 const char *path, const char *address,
1356 unsigned int number) {
1357 struct interface_device *new_ptr;
1359 sizeof(state->interface_devices[0]) * (state->nr_interface_devices + 1);
1360 char *path_copy, *address_copy, number_string[15];
1362 if ((path == NULL) || (address == NULL))
1365 path_copy = strdup(path);
1369 address_copy = strdup(address);
1370 if (!address_copy) {
1375 snprintf(number_string, sizeof(number_string), "interface-%u", number);
1377 if (state->interface_devices)
1378 new_ptr = realloc(state->interface_devices, new_size);
1380 new_ptr = malloc(new_size);
1382 if (new_ptr == NULL) {
1384 sfree(address_copy);
1387 state->interface_devices = new_ptr;
1388 state->interface_devices[state->nr_interface_devices].dom = dom;
1389 state->interface_devices[state->nr_interface_devices].path = path_copy;
1390 state->interface_devices[state->nr_interface_devices].address = address_copy;
1391 state->interface_devices[state->nr_interface_devices].number =
1392 strdup(number_string);
1393 return state->nr_interface_devices++;
1396 static int ignore_device_match(ignorelist_t *il, const char *domname,
1397 const char *devpath) {
1401 if ((domname == NULL) || (devpath == NULL))
1404 n = sizeof(char) * (strlen(domname) + strlen(devpath) + 2);
1407 ERROR(PLUGIN_NAME " plugin: malloc failed.");
1410 ssnprintf(name, n, "%s:%s", domname, devpath);
1411 r = ignorelist_match(il, name);
1416 static int lv_shutdown(void) {
1417 for (int i = 0; i < nr_instances; ++i) {
1418 lv_fini_instance(i);
1423 ignorelist_free(il_domains);
1425 ignorelist_free(il_block_devices);
1426 il_block_devices = NULL;
1427 ignorelist_free(il_interface_devices);
1428 il_interface_devices = NULL;
1433 void module_register(void) {
1434 plugin_register_config(PLUGIN_NAME, lv_config, config_keys, NR_CONFIG_KEYS);
1435 plugin_register_init(PLUGIN_NAME, lv_init);
1436 plugin_register_shutdown(PLUGIN_NAME, lv_shutdown);