1 /**
2 * collectd - src/virt.c
3 * Copyright (C) 2006-2008 Red Hat Inc.
4 *
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.
8 *
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.
13 *
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
17 *
18 * Authors:
19 * Richard W.M. Jones <rjones@redhat.com>
20 **/
22 #include "collectd.h"
24 #include "common.h"
25 #include "plugin.h"
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>
37 /* Plugin name */
38 #define PLUGIN_NAME "virt"
40 static const char *config_keys[] = {"Connection",
42 "RefreshInterval",
44 "Domain",
45 "BlockDevice",
46 "BlockDeviceFormat",
47 "BlockDeviceFormatBasename",
48 "InterfaceDevice",
49 "IgnoreSelected",
51 "HostnameFormat",
52 "InterfaceFormat",
54 "PluginInstanceFormat",
56 "Instances",
58 NULL};
59 #define NR_CONFIG_KEYS ((sizeof config_keys / sizeof config_keys[0]) - 1)
61 /* Connection. */
62 static virConnectPtr conn = 0;
63 static char *conn_string = NULL;
64 static c_complain_t conn_complain = C_COMPLAIN_INIT_STATIC;
66 /* Seconds between list refreshes, 0 disables completely. */
67 static int interval = 60;
69 /* List of domains, if specified. */
70 static ignorelist_t *il_domains = NULL;
71 /* List of block devices, if specified. */
72 static ignorelist_t *il_block_devices = NULL;
73 /* List of network interface devices, if specified. */
74 static ignorelist_t *il_interface_devices = NULL;
76 static int ignore_device_match(ignorelist_t *, const char *domname,
77 const char *devpath);
79 /* Actual list of block devices found on last refresh. */
80 struct block_device {
81 virDomainPtr dom; /* domain */
82 char *path; /* name of block device */
83 };
85 /* Actual list of network interfaces found on last refresh. */
86 struct interface_device {
87 virDomainPtr dom; /* domain */
88 char *path; /* name of interface device */
89 char *address; /* mac address of interface device */
90 char *number; /* interface device number */
91 };
93 struct lv_read_state {
94 /* Actual list of domains found on last refresh. */
95 virDomainPtr *domains;
96 int nr_domains;
98 struct block_device *block_devices;
99 int nr_block_devices;
101 struct interface_device *interface_devices;
102 int nr_interface_devices;
103 };
105 static void free_domains(struct lv_read_state *state);
106 static int add_domain(struct lv_read_state *state, virDomainPtr dom);
108 static void free_block_devices(struct lv_read_state *state);
109 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
110 const char *path);
112 static void free_interface_devices(struct lv_read_state *state);
113 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
114 const char *path, const char *address,
115 unsigned int number);
117 #define METADATA_VM_PARTITION_URI "http://ovirt.org/ovirtmap/tag/1.0"
118 #define METADATA_VM_PARTITION_ELEMENT "tag"
119 #define METADATA_VM_PARTITION_PREFIX "ovirtmap"
121 #define BUFFER_MAX_LEN 256
122 #define PARTITION_TAG_MAX_LEN 32
124 struct lv_read_instance {
125 struct lv_read_state read_state;
126 char tag[PARTITION_TAG_MAX_LEN];
127 size_t id;
128 };
130 struct lv_user_data {
131 struct lv_read_instance inst;
132 user_data_t ud;
133 };
135 #define NR_INSTANCES_DEFAULT 1
136 #define NR_INSTANCES_MAX 128
137 static int nr_instances = NR_INSTANCES_DEFAULT;
138 static struct lv_user_data lv_read_user_data[NR_INSTANCES_MAX];
140 /* HostnameFormat. */
141 #define HF_MAX_FIELDS 3
143 enum hf_field { hf_none = 0, hf_hostname, hf_name, hf_uuid };
145 static enum hf_field hostname_format[HF_MAX_FIELDS] = {hf_name};
147 /* PluginInstanceFormat */
148 #define PLGINST_MAX_FIELDS 2
150 enum plginst_field { plginst_none = 0, plginst_name, plginst_uuid };
152 static enum plginst_field plugin_instance_format[PLGINST_MAX_FIELDS] = {
153 plginst_none};
155 /* BlockDeviceFormat */
156 enum bd_field { target, source };
158 /* InterfaceFormat. */
159 enum if_field { if_address, if_name, if_number };
161 /* BlockDeviceFormatBasename */
162 _Bool blockdevice_format_basename = 0;
163 static enum bd_field blockdevice_format = target;
164 static enum if_field interface_format = if_name;
166 /* Time that we last refreshed. */
167 static time_t last_refresh = (time_t)0;
169 static int refresh_lists(struct lv_read_instance *inst);
171 /* ERROR(...) macro for virterrors. */
172 #define VIRT_ERROR(conn, s) \
173 do { \
174 virErrorPtr err; \
175 err = (conn) ? virConnGetLastError((conn)) : virGetLastError(); \
176 if (err) \
177 ERROR("%s: %s", (s), err->message); \
178 } while (0)
180 static void init_value_list(value_list_t *vl, virDomainPtr dom) {
181 int n;
182 const char *name;
183 char uuid[VIR_UUID_STRING_BUFLEN];
185 sstrncpy(vl->plugin, PLUGIN_NAME, sizeof(vl->plugin));
187 vl->host[0] = '\0';
189 /* Construct the hostname field according to HostnameFormat. */
190 for (int i = 0; i < HF_MAX_FIELDS; ++i) {
191 if (hostname_format[i] == hf_none)
192 continue;
194 n = DATA_MAX_NAME_LEN - strlen(vl->host) - 2;
196 if (i > 0 && n >= 1) {
197 strncat(vl->host, ":", 1);
198 n--;
199 }
201 switch (hostname_format[i]) {
202 case hf_none:
203 break;
204 case hf_hostname:
205 strncat(vl->host, hostname_g, n);
206 break;
207 case hf_name:
208 name = virDomainGetName(dom);
209 if (name)
210 strncat(vl->host, name, n);
211 break;
212 case hf_uuid:
213 if (virDomainGetUUIDString(dom, uuid) == 0)
214 strncat(vl->host, uuid, n);
215 break;
216 }
217 }
219 vl->host[sizeof(vl->host) - 1] = '\0';
221 /* Construct the plugin instance field according to PluginInstanceFormat. */
222 for (int i = 0; i < PLGINST_MAX_FIELDS; ++i) {
223 if (plugin_instance_format[i] == plginst_none)
224 continue;
226 n = sizeof(vl->plugin_instance) - strlen(vl->plugin_instance) - 2;
228 if (i > 0 && n >= 1) {
229 strncat(vl->plugin_instance, ":", 1);
230 n--;
231 }
233 switch (plugin_instance_format[i]) {
234 case plginst_none:
235 break;
236 case plginst_name:
237 name = virDomainGetName(dom);
238 if (name)
239 strncat(vl->plugin_instance, name, n);
240 break;
241 case plginst_uuid:
242 if (virDomainGetUUIDString(dom, uuid) == 0)
243 strncat(vl->plugin_instance, uuid, n);
244 break;
245 }
246 }
248 vl->plugin_instance[sizeof(vl->plugin_instance) - 1] = '\0';
250 } /* void init_value_list */
252 static void submit(virDomainPtr dom, char const *type,
253 char const *type_instance, value_t *values,
254 size_t values_len) {
255 value_list_t vl = VALUE_LIST_INIT;
256 init_value_list(&vl, dom);
258 vl.values = values;
259 vl.values_len = values_len;
261 sstrncpy(vl.type, type, sizeof(vl.type));
262 if (type_instance != NULL)
263 sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
265 plugin_dispatch_values(&vl);
266 }
268 static void memory_submit(gauge_t value, virDomainPtr dom) {
269 submit(dom, "memory", "total", &(value_t){.gauge = value}, 1);
270 }
272 static void memory_stats_submit(gauge_t value, virDomainPtr dom,
273 int tag_index) {
274 static const char *tags[] = {"swap_in", "swap_out", "major_fault",
275 "minor_fault", "unused", "available",
276 "actual_balloon", "rss"};
278 if ((tag_index < 0) || (tag_index >= STATIC_ARRAY_SIZE(tags))) {
279 ERROR("virt plugin: Array index out of bounds: tag_index = %d", tag_index);
280 return;
281 }
283 submit(dom, "memory", tags[tag_index], &(value_t){.gauge = value}, 1);
284 }
286 static void cpu_submit(unsigned long long value, virDomainPtr dom,
287 const char *type) {
288 submit(dom, type, NULL, &(value_t){.derive = (derive_t)value}, 1);
289 }
291 static void vcpu_submit(derive_t value, virDomainPtr dom, int vcpu_nr,
292 const char *type) {
293 char type_instance[DATA_MAX_NAME_LEN];
295 ssnprintf(type_instance, sizeof(type_instance), "%d", vcpu_nr);
297 submit(dom, type, type_instance, &(value_t){.derive = value}, 1);
298 }
300 static void submit_derive2(const char *type, derive_t v0, derive_t v1,
301 virDomainPtr dom, const char *devname) {
302 value_t values[] = {
303 {.derive = v0}, {.derive = v1},
304 };
306 submit(dom, type, devname, values, STATIC_ARRAY_SIZE(values));
307 } /* void submit_derive2 */
309 static int lv_config(const char *key, const char *value) {
310 if (virInitialize() != 0)
311 return 1;
313 if (il_domains == NULL)
314 il_domains = ignorelist_create(1);
315 if (il_block_devices == NULL)
316 il_block_devices = ignorelist_create(1);
317 if (il_interface_devices == NULL)
318 il_interface_devices = ignorelist_create(1);
320 if (strcasecmp(key, "Connection") == 0) {
321 char *tmp = strdup(value);
322 if (tmp == NULL) {
323 ERROR(PLUGIN_NAME " plugin: Connection strdup failed.");
324 return 1;
325 }
326 sfree(conn_string);
327 conn_string = tmp;
328 return 0;
329 }
331 if (strcasecmp(key, "RefreshInterval") == 0) {
332 char *eptr = NULL;
333 interval = strtol(value, &eptr, 10);
334 if (eptr == NULL || *eptr != '\0')
335 return 1;
336 return 0;
337 }
339 if (strcasecmp(key, "Domain") == 0) {
340 if (ignorelist_add(il_domains, value))
341 return 1;
342 return 0;
343 }
344 if (strcasecmp(key, "BlockDevice") == 0) {
345 if (ignorelist_add(il_block_devices, value))
346 return 1;
347 return 0;
348 }
350 if (strcasecmp(key, "BlockDeviceFormat") == 0) {
351 if (strcasecmp(value, "target") == 0)
352 blockdevice_format = target;
353 else if (strcasecmp(value, "source") == 0)
354 blockdevice_format = source;
355 else {
356 ERROR(PLUGIN_NAME " plugin: unknown BlockDeviceFormat: %s", value);
357 return -1;
358 }
359 return 0;
360 }
361 if (strcasecmp(key, "BlockDeviceFormatBasename") == 0) {
362 blockdevice_format_basename = IS_TRUE(value);
363 return 0;
364 }
365 if (strcasecmp(key, "InterfaceDevice") == 0) {
366 if (ignorelist_add(il_interface_devices, value))
367 return 1;
368 return 0;
369 }
371 if (strcasecmp(key, "IgnoreSelected") == 0) {
372 if (IS_TRUE(value)) {
373 ignorelist_set_invert(il_domains, 0);
374 ignorelist_set_invert(il_block_devices, 0);
375 ignorelist_set_invert(il_interface_devices, 0);
376 } else {
377 ignorelist_set_invert(il_domains, 1);
378 ignorelist_set_invert(il_block_devices, 1);
379 ignorelist_set_invert(il_interface_devices, 1);
380 }
381 return 0;
382 }
384 if (strcasecmp(key, "HostnameFormat") == 0) {
385 char *value_copy;
386 char *fields[HF_MAX_FIELDS];
387 int n;
389 value_copy = strdup(value);
390 if (value_copy == NULL) {
391 ERROR(PLUGIN_NAME " plugin: strdup failed.");
392 return -1;
393 }
395 n = strsplit(value_copy, fields, HF_MAX_FIELDS);
396 if (n < 1) {
397 sfree(value_copy);
398 ERROR(PLUGIN_NAME " plugin: HostnameFormat: no fields");
399 return -1;
400 }
402 for (int i = 0; i < n; ++i) {
403 if (strcasecmp(fields[i], "hostname") == 0)
404 hostname_format[i] = hf_hostname;
405 else if (strcasecmp(fields[i], "name") == 0)
406 hostname_format[i] = hf_name;
407 else if (strcasecmp(fields[i], "uuid") == 0)
408 hostname_format[i] = hf_uuid;
409 else {
410 ERROR(PLUGIN_NAME " plugin: unknown HostnameFormat field: %s",
411 fields[i]);
412 sfree(value_copy);
413 return -1;
414 }
415 }
416 sfree(value_copy);
418 for (int i = n; i < HF_MAX_FIELDS; ++i)
419 hostname_format[i] = hf_none;
421 return 0;
422 }
424 if (strcasecmp(key, "PluginInstanceFormat") == 0) {
425 char *value_copy;
426 char *fields[PLGINST_MAX_FIELDS];
427 int n;
429 value_copy = strdup(value);
430 if (value_copy == NULL) {
431 ERROR(PLUGIN_NAME " plugin: strdup failed.");
432 return -1;
433 }
435 n = strsplit(value_copy, fields, PLGINST_MAX_FIELDS);
436 if (n < 1) {
437 sfree(value_copy);
438 ERROR(PLUGIN_NAME " plugin: PluginInstanceFormat: no fields");
439 return -1;
440 }
442 for (int i = 0; i < n; ++i) {
443 if (strcasecmp(fields[i], "none") == 0) {
444 plugin_instance_format[i] = plginst_none;
445 break;
446 } else if (strcasecmp(fields[i], "name") == 0)
447 plugin_instance_format[i] = plginst_name;
448 else if (strcasecmp(fields[i], "uuid") == 0)
449 plugin_instance_format[i] = plginst_uuid;
450 else {
451 ERROR(PLUGIN_NAME " plugin: unknown PluginInstanceFormat field: %s",
452 fields[i]);
453 sfree(value_copy);
454 return -1;
455 }
456 }
457 sfree(value_copy);
459 for (int i = n; i < PLGINST_MAX_FIELDS; ++i)
460 plugin_instance_format[i] = plginst_none;
462 return 0;
463 }
465 if (strcasecmp(key, "InterfaceFormat") == 0) {
466 if (strcasecmp(value, "name") == 0)
467 interface_format = if_name;
468 else if (strcasecmp(value, "address") == 0)
469 interface_format = if_address;
470 else if (strcasecmp(value, "number") == 0)
471 interface_format = if_number;
472 else {
473 ERROR(PLUGIN_NAME " plugin: unknown InterfaceFormat: %s", value);
474 return -1;
475 }
476 return 0;
477 }
479 if (strcasecmp(key, "Instances") == 0) {
480 char *eptr = NULL;
481 double val = strtod(value, &eptr);
483 if (*eptr != '\0') {
484 ERROR(PLUGIN_NAME " plugin: Invalid value for Instances = '%s'", value);
485 return 1;
486 }
487 if (val <= 0) {
488 ERROR(PLUGIN_NAME " plugin: Instances <= 0 makes no sense.");
489 return 1;
490 }
491 if (val > NR_INSTANCES_MAX) {
492 ERROR(PLUGIN_NAME " plugin: Instances=%f > NR_INSTANCES_MAX=%i"
493 " use a lower setting or recompile the plugin.",
494 val, NR_INSTANCES_MAX);
495 return 1;
496 }
498 nr_instances = (int)val;
499 DEBUG(PLUGIN_NAME " plugin: configured %i instances", nr_instances);
500 return 0;
501 }
503 /* Unrecognised option. */
504 return -1;
505 }
507 static int lv_read(user_data_t *ud) {
508 time_t t;
509 struct lv_read_instance *inst = NULL;
510 struct lv_read_state *state = NULL;
512 if (ud->data == NULL) {
513 ERROR(PLUGIN_NAME " plugin: NULL userdata");
514 return -1;
515 }
517 inst = ud->data;
518 state = &inst->read_state;
520 if (inst->id == 0 && conn == NULL) {
521 /* `conn_string == NULL' is acceptable. */
522 conn = virConnectOpenReadOnly(conn_string);
523 if (conn == NULL) {
524 c_complain(LOG_ERR, &conn_complain,
525 PLUGIN_NAME " plugin: Unable to connect: "
526 "virConnectOpenReadOnly failed.");
527 return -1;
528 }
529 }
530 c_release(LOG_NOTICE, &conn_complain,
531 PLUGIN_NAME " plugin: Connection established.");
533 time(&t);
535 /* Need to refresh domain or device lists? */
536 if ((last_refresh == (time_t)0) ||
537 ((interval > 0) && ((last_refresh + interval) <= t))) {
538 if (refresh_lists(inst) != 0) {
539 if (conn != NULL)
540 virConnectClose(conn);
541 conn = NULL;
542 return -1;
543 }
544 last_refresh = t;
545 }
547 #if 0
548 for (int i = 0; i < nr_domains; ++i)
549 fprintf (stderr, "domain %s\n", virDomainGetName (domains[i]));
550 for (int i = 0; i < nr_block_devices; ++i)
551 fprintf (stderr, "block device %d %s:%s\n",
552 i, virDomainGetName (block_devices[i].dom),
553 block_devices[i].path);
554 for (int i = 0; i < nr_interface_devices; ++i)
555 fprintf (stderr, "interface device %d %s:%s\n",
556 i, virDomainGetName (interface_devices[i].dom),
557 interface_devices[i].path);
558 #endif
560 /* Get CPU usage, memory, VCPU usage for each domain. */
561 for (int i = 0; i < state->nr_domains; ++i) {
562 virDomainInfo info;
563 virVcpuInfoPtr vinfo = NULL;
564 virDomainMemoryStatPtr minfo = NULL;
565 int status;
567 status = virDomainGetInfo(state->domains[i], &info);
568 if (status != 0) {
569 ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
570 status);
571 continue;
572 }
574 if (info.state != VIR_DOMAIN_RUNNING) {
575 /* only gather stats for running domains */
576 continue;
577 }
579 cpu_submit(info.cpuTime, state->domains[i], "virt_cpu_total");
580 memory_submit((gauge_t)info.memory * 1024, state->domains[i]);
582 vinfo = malloc(info.nrVirtCpu * sizeof(vinfo[0]));
583 if (vinfo == NULL) {
584 ERROR(PLUGIN_NAME " plugin: malloc failed.");
585 continue;
586 }
588 status = virDomainGetVcpus(state->domains[i], vinfo, info.nrVirtCpu,
589 /* cpu map = */ NULL, /* cpu map length = */ 0);
590 if (status < 0) {
591 ERROR(PLUGIN_NAME " plugin: virDomainGetVcpus failed with status %i.",
592 status);
593 sfree(vinfo);
594 continue;
595 }
597 for (int j = 0; j < info.nrVirtCpu; ++j)
598 vcpu_submit(vinfo[j].cpuTime, state->domains[i], vinfo[j].number,
599 "virt_vcpu");
601 sfree(vinfo);
603 minfo =
604 malloc(VIR_DOMAIN_MEMORY_STAT_NR * sizeof(virDomainMemoryStatStruct));
605 if (minfo == NULL) {
606 ERROR("virt plugin: malloc failed.");
607 continue;
608 }
610 status = virDomainMemoryStats(state->domains[i], minfo,
611 VIR_DOMAIN_MEMORY_STAT_NR, 0);
613 if (status < 0) {
614 ERROR("virt plugin: virDomainMemoryStats failed with status %i.", status);
615 sfree(minfo);
616 continue;
617 }
619 for (int j = 0; j < status; j++) {
620 memory_stats_submit((gauge_t)minfo[j].val * 1024, state->domains[i],
621 minfo[j].tag);
622 }
624 sfree(minfo);
625 }
627 /* Get block device stats for each domain. */
628 for (int i = 0; i < state->nr_block_devices; ++i) {
629 struct _virDomainBlockStats stats;
631 if (virDomainBlockStats(state->block_devices[i].dom,
632 state->block_devices[i].path, &stats,
633 sizeof stats) != 0)
634 continue;
636 char *type_instance = NULL;
637 if (blockdevice_format_basename && blockdevice_format == source)
638 type_instance = strdup(basename(state->block_devices[i].path));
639 else
640 type_instance = strdup(state->block_devices[i].path);
642 if ((stats.rd_req != -1) && (stats.wr_req != -1))
643 submit_derive2("disk_ops", (derive_t)stats.rd_req, (derive_t)stats.wr_req,
644 state->block_devices[i].dom, type_instance);
646 if ((stats.rd_bytes != -1) && (stats.wr_bytes != -1))
647 submit_derive2("disk_octets", (derive_t)stats.rd_bytes,
648 (derive_t)stats.wr_bytes, state->block_devices[i].dom,
649 type_instance);
651 sfree(type_instance);
652 } /* for (nr_block_devices) */
654 /* Get interface stats for each domain. */
655 for (int i = 0; i < state->nr_interface_devices; ++i) {
656 struct _virDomainInterfaceStats stats;
657 char *display_name = NULL;
659 switch (interface_format) {
660 case if_address:
661 display_name = state->interface_devices[i].address;
662 break;
663 case if_number:
664 display_name = state->interface_devices[i].number;
665 break;
666 case if_name:
667 default:
668 display_name = state->interface_devices[i].path;
669 }
671 if (virDomainInterfaceStats(state->interface_devices[i].dom,
672 state->interface_devices[i].path, &stats,
673 sizeof stats) != 0)
674 continue;
676 if ((stats.rx_bytes != -1) && (stats.tx_bytes != -1))
677 submit_derive2("if_octets", (derive_t)stats.rx_bytes,
678 (derive_t)stats.tx_bytes, state->interface_devices[i].dom,
679 display_name);
681 if ((stats.rx_packets != -1) && (stats.tx_packets != -1))
682 submit_derive2("if_packets", (derive_t)stats.rx_packets,
683 (derive_t)stats.tx_packets,
684 state->interface_devices[i].dom, display_name);
686 if ((stats.rx_errs != -1) && (stats.tx_errs != -1))
687 submit_derive2("if_errors", (derive_t)stats.rx_errs,
688 (derive_t)stats.tx_errs, state->interface_devices[i].dom,
689 display_name);
691 if ((stats.rx_drop != -1) && (stats.tx_drop != -1))
692 submit_derive2("if_dropped", (derive_t)stats.rx_drop,
693 (derive_t)stats.tx_drop, state->interface_devices[i].dom,
694 display_name);
695 } /* for (nr_interface_devices) */
697 return 0;
698 }
700 static int lv_init_instance(size_t i, plugin_read_cb callback) {
701 struct lv_user_data *lv_ud = &(lv_read_user_data[i]);
702 struct lv_read_instance *inst = &(lv_ud->inst);
704 memset(lv_ud, 0, sizeof(*lv_ud));
706 ssnprintf(inst->tag, sizeof(inst->tag), "%s-%zu", PLUGIN_NAME, i);
707 inst->id = i;
709 user_data_t *ud = &(lv_ud->ud);
710 ud->data = inst;
711 ud->free_func = NULL;
713 INFO(PLUGIN_NAME " plugin: reader %s initialized", inst->tag);
714 return plugin_register_complex_read(NULL, inst->tag, callback, 0, ud);
715 }
717 static void lv_clean_read_state(struct lv_read_state *state) {
718 free_block_devices(state);
719 free_interface_devices(state);
720 free_domains(state);
721 }
723 static void lv_fini_instance(size_t i) {
724 struct lv_read_instance *inst = &(lv_read_user_data[i].inst);
725 struct lv_read_state *state = &(inst->read_state);
727 lv_clean_read_state(state);
728 INFO(PLUGIN_NAME " plugin: reader %s finalized", inst->tag);
729 }
731 static int lv_init(void) {
732 if (virInitialize() != 0)
733 return -1;
735 DEBUG(PLUGIN_NAME " plugin: starting %i instances", nr_instances);
737 for (int i = 0; i < nr_instances; ++i)
738 lv_init_instance(i, lv_read);
740 return 0;
741 }
743 /*
744 * returns 0 on success and <0 on error
745 */
746 static int lv_domain_get_tag(xmlXPathContextPtr xpath_ctx, const char *dom_name,
747 char *dom_tag) {
748 char xpath_str[BUFFER_MAX_LEN] = {'\0'};
749 xmlXPathObjectPtr xpath_obj = NULL;
750 xmlNodePtr xml_node = NULL;
751 int ret = -1;
752 int err;
754 err = xmlXPathRegisterNs(xpath_ctx,
755 (const xmlChar *)METADATA_VM_PARTITION_PREFIX,
756 (const xmlChar *)METADATA_VM_PARTITION_URI);
757 if (err) {
758 ERROR(PLUGIN_NAME " plugin: xmlXpathRegisterNs(%s, %s) failed on domain %s",
759 METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_URI, dom_name);
760 goto done;
761 }
763 ssnprintf(xpath_str, sizeof(xpath_str), "/domain/metadata/%s:%s/text()",
764 METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_ELEMENT);
765 xpath_obj = xmlXPathEvalExpression((xmlChar *)xpath_str, xpath_ctx);
766 if (xpath_obj == NULL) {
767 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) failed on domain %s",
768 xpath_str, dom_name);
769 goto done;
770 }
772 if (xpath_obj->type != XPATH_NODESET) {
773 ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) unexpected return type %d "
774 "(wanted %d) on domain %s",
775 xpath_str, xpath_obj->type, XPATH_NODESET, dom_name);
776 goto done;
777 }
779 /*
780 * from now on there is no real error, it's ok if a domain
781 * doesn't have the metadata partition tag.
782 */
783 ret = 0;
784 if (xpath_obj->nodesetval == NULL || xpath_obj->nodesetval->nodeNr != 1) {
785 DEBUG(PLUGIN_NAME " plugin: xmlXPathEval(%s) return nodeset size=%i "
786 "expected=1 on domain %s",
787 xpath_str,
788 (xpath_obj->nodesetval == NULL) ? 0 : xpath_obj->nodesetval->nodeNr,
789 dom_name);
790 } else {
791 xml_node = xpath_obj->nodesetval->nodeTab[0];
792 sstrncpy(dom_tag, (const char *)xml_node->content, PARTITION_TAG_MAX_LEN);
793 }
795 done:
796 /* deregister to clean up */
797 err = xmlXPathRegisterNs(xpath_ctx,
798 (const xmlChar *)METADATA_VM_PARTITION_PREFIX, NULL);
799 if (err) {
800 /* we can't really recover here */
801 ERROR(PLUGIN_NAME
802 " plugin: deregistration of namespace %s failed for domain %s",
803 METADATA_VM_PARTITION_PREFIX, dom_name);
804 }
805 if (xpath_obj)
806 xmlXPathFreeObject(xpath_obj);
808 return ret;
809 }
811 static int is_known_tag(const char *dom_tag) {
812 for (int i = 0; i < nr_instances; ++i)
813 if (!strcmp(dom_tag, lv_read_user_data[i].inst.tag))
814 return 1;
815 return 0;
816 }
818 static int lv_instance_include_domain(struct lv_read_instance *inst,
819 const char *dom_name,
820 const char *dom_tag) {
821 if ((dom_tag[0] != '\0') && (strcmp(dom_tag, inst->tag) == 0))
822 return 1;
824 /* instance#0 will always be there, so it is in charge of extra duties */
825 if (inst->id == 0) {
826 if (dom_tag[0] == '\0' || !is_known_tag(dom_tag)) {
827 DEBUG(PLUGIN_NAME " plugin#%s: refreshing domain %s "
828 "with unknown tag '%s'",
829 inst->tag, dom_name, dom_tag);
830 return 1;
831 }
832 }
834 return 0;
835 }
837 static int refresh_lists(struct lv_read_instance *inst) {
838 struct lv_read_state *state = &inst->read_state;
839 int n;
841 n = virConnectNumOfDomains(conn);
842 if (n < 0) {
843 VIRT_ERROR(conn, "reading number of domains");
844 return -1;
845 }
847 lv_clean_read_state(state);
849 if (n > 0) {
850 int *domids;
852 /* Get list of domains. */
853 domids = malloc(sizeof(*domids) * n);
854 if (domids == NULL) {
855 ERROR(PLUGIN_NAME " plugin: malloc failed.");
856 return -1;
857 }
859 n = virConnectListDomains(conn, domids, n);
860 if (n < 0) {
861 VIRT_ERROR(conn, "reading list of domains");
862 sfree(domids);
863 return -1;
864 }
866 /* Fetch each domain and add it to the list, unless ignore. */
867 for (int i = 0; i < n; ++i) {
868 virDomainPtr dom = NULL;
869 const char *name;
870 char *xml = NULL;
871 xmlDocPtr xml_doc = NULL;
872 xmlXPathContextPtr xpath_ctx = NULL;
873 xmlXPathObjectPtr xpath_obj = NULL;
874 char tag[PARTITION_TAG_MAX_LEN] = {'\0'};
876 dom = virDomainLookupByID(conn, domids[i]);
877 if (dom == NULL) {
878 VIRT_ERROR(conn, "virDomainLookupByID");
879 /* Could be that the domain went away -- ignore it anyway. */
880 continue;
881 }
883 name = virDomainGetName(dom);
884 if (name == NULL) {
885 VIRT_ERROR(conn, "virDomainGetName");
886 goto cont;
887 }
889 if (il_domains && ignorelist_match(il_domains, name) != 0)
890 goto cont;
892 /* Get a list of devices for this domain. */
893 xml = virDomainGetXMLDesc(dom, 0);
894 if (!xml) {
895 VIRT_ERROR(conn, "virDomainGetXMLDesc");
896 goto cont;
897 }
899 /* Yuck, XML. Parse out the devices. */
900 xml_doc = xmlReadDoc((xmlChar *)xml, NULL, NULL, XML_PARSE_NONET);
901 if (xml_doc == NULL) {
902 VIRT_ERROR(conn, "xmlReadDoc");
903 goto cont;
904 }
906 xpath_ctx = xmlXPathNewContext(xml_doc);
908 if (lv_domain_get_tag(xpath_ctx, name, tag) < 0) {
909 ERROR(PLUGIN_NAME " plugin: lv_domain_get_tag failed.");
910 goto cont;
911 }
913 if (!lv_instance_include_domain(inst, name, tag))
914 goto cont;
916 if (add_domain(state, dom) < 0) {
917 ERROR(PLUGIN_NAME " plugin: malloc failed.");
918 goto cont;
919 }
921 /* Block devices. */
922 char *bd_xmlpath = "/domain/devices/disk/target[@dev]";
923 if (blockdevice_format == source)
924 bd_xmlpath = "/domain/devices/disk/source[@dev]";
925 xpath_obj = xmlXPathEval((xmlChar *)bd_xmlpath, xpath_ctx);
927 if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
928 xpath_obj->nodesetval == NULL)
929 goto cont;
931 for (int j = 0; j < xpath_obj->nodesetval->nodeNr; ++j) {
932 xmlNodePtr node;
933 char *path = NULL;
935 node = xpath_obj->nodesetval->nodeTab[j];
936 if (!node)
937 continue;
938 path = (char *)xmlGetProp(node, (xmlChar *)"dev");
939 if (!path)
940 continue;
942 if (il_block_devices &&
943 ignore_device_match(il_block_devices, name, path) != 0)
944 goto cont2;
946 add_block_device(state, dom, path);
947 cont2:
948 if (path)
949 xmlFree(path);
950 }
951 xmlXPathFreeObject(xpath_obj);
953 /* Network interfaces. */
954 xpath_obj = xmlXPathEval(
955 (xmlChar *)"/domain/devices/interface[target[@dev]]", xpath_ctx);
956 if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
957 xpath_obj->nodesetval == NULL)
958 goto cont;
960 xmlNodeSetPtr xml_interfaces = xpath_obj->nodesetval;
962 for (int j = 0; j < xml_interfaces->nodeNr; ++j) {
963 char *path = NULL;
964 char *address = NULL;
965 xmlNodePtr xml_interface;
967 xml_interface = xml_interfaces->nodeTab[j];
968 if (!xml_interface)
969 continue;
971 for (xmlNodePtr child = xml_interface->children; child;
972 child = child->next) {
973 if (child->type != XML_ELEMENT_NODE)
974 continue;
976 if (xmlStrEqual(child->name, (const xmlChar *)"target")) {
977 path = (char *)xmlGetProp(child, (const xmlChar *)"dev");
978 if (!path)
979 continue;
980 } else if (xmlStrEqual(child->name, (const xmlChar *)"mac")) {
981 address = (char *)xmlGetProp(child, (const xmlChar *)"address");
982 if (!address)
983 continue;
984 }
985 }
987 if (il_interface_devices &&
988 (ignore_device_match(il_interface_devices, name, path) != 0 ||
989 ignore_device_match(il_interface_devices, name, address) != 0))
990 goto cont3;
992 add_interface_device(state, dom, path, address, j + 1);
993 cont3:
994 if (path)
995 xmlFree(path);
996 if (address)
997 xmlFree(address);
998 }
1000 cont:
1001 if (xpath_obj)
1002 xmlXPathFreeObject(xpath_obj);
1003 if (xpath_ctx)
1004 xmlXPathFreeContext(xpath_ctx);
1005 if (xml_doc)
1006 xmlFreeDoc(xml_doc);
1007 sfree(xml);
1008 }
1010 sfree(domids);
1011 }
1013 DEBUG(PLUGIN_NAME " plugin#%s: refreshing"
1014 " domains=%i block_devices=%i iface_devices=%i",
1015 inst->tag, state->nr_domains, state->nr_block_devices,
1016 state->nr_interface_devices);
1018 return 0;
1019 }
1021 static void free_domains(struct lv_read_state *state) {
1022 if (state->domains) {
1023 for (int i = 0; i < state->nr_domains; ++i)
1024 virDomainFree(state->domains[i]);
1025 sfree(state->domains);
1026 }
1027 state->domains = NULL;
1028 state->nr_domains = 0;
1029 }
1031 static int add_domain(struct lv_read_state *state, virDomainPtr dom) {
1032 virDomainPtr *new_ptr;
1033 int new_size = sizeof(state->domains[0]) * (state->nr_domains + 1);
1035 if (state->domains)
1036 new_ptr = realloc(state->domains, new_size);
1037 else
1038 new_ptr = malloc(new_size);
1040 if (new_ptr == NULL)
1041 return -1;
1043 state->domains = new_ptr;
1044 state->domains[state->nr_domains] = dom;
1045 return state->nr_domains++;
1046 }
1048 static void free_block_devices(struct lv_read_state *state) {
1049 if (state->block_devices) {
1050 for (int i = 0; i < state->nr_block_devices; ++i)
1051 sfree(state->block_devices[i].path);
1052 sfree(state->block_devices);
1053 }
1054 state->block_devices = NULL;
1055 state->nr_block_devices = 0;
1056 }
1058 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
1059 const char *path) {
1060 struct block_device *new_ptr;
1061 int new_size =
1062 sizeof(state->block_devices[0]) * (state->nr_block_devices + 1);
1063 char *path_copy;
1065 path_copy = strdup(path);
1066 if (!path_copy)
1067 return -1;
1069 if (state->block_devices)
1070 new_ptr = realloc(state->block_devices, new_size);
1071 else
1072 new_ptr = malloc(new_size);
1074 if (new_ptr == NULL) {
1075 sfree(path_copy);
1076 return -1;
1077 }
1078 state->block_devices = new_ptr;
1079 state->block_devices[state->nr_block_devices].dom = dom;
1080 state->block_devices[state->nr_block_devices].path = path_copy;
1081 return state->nr_block_devices++;
1082 }
1084 static void free_interface_devices(struct lv_read_state *state) {
1085 if (state->interface_devices) {
1086 for (int i = 0; i < state->nr_interface_devices; ++i) {
1087 sfree(state->interface_devices[i].path);
1088 sfree(state->interface_devices[i].address);
1089 sfree(state->interface_devices[i].number);
1090 }
1091 sfree(state->interface_devices);
1092 }
1093 state->interface_devices = NULL;
1094 state->nr_interface_devices = 0;
1095 }
1097 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
1098 const char *path, const char *address,
1099 unsigned int number) {
1100 struct interface_device *new_ptr;
1101 int new_size =
1102 sizeof(state->interface_devices[0]) * (state->nr_interface_devices + 1);
1103 char *path_copy, *address_copy, number_string[15];
1105 if ((path == NULL) || (address == NULL))
1106 return EINVAL;
1108 path_copy = strdup(path);
1109 if (!path_copy)
1110 return -1;
1112 address_copy = strdup(address);
1113 if (!address_copy) {
1114 sfree(path_copy);
1115 return -1;
1116 }
1118 snprintf(number_string, sizeof(number_string), "interface-%u", number);
1120 if (state->interface_devices)
1121 new_ptr = realloc(state->interface_devices, new_size);
1122 else
1123 new_ptr = malloc(new_size);
1125 if (new_ptr == NULL) {
1126 sfree(path_copy);
1127 sfree(address_copy);
1128 return -1;
1129 }
1130 state->interface_devices = new_ptr;
1131 state->interface_devices[state->nr_interface_devices].dom = dom;
1132 state->interface_devices[state->nr_interface_devices].path = path_copy;
1133 state->interface_devices[state->nr_interface_devices].address = address_copy;
1134 state->interface_devices[state->nr_interface_devices].number =
1135 strdup(number_string);
1136 return state->nr_interface_devices++;
1137 }
1139 static int ignore_device_match(ignorelist_t *il, const char *domname,
1140 const char *devpath) {
1141 char *name;
1142 int n, r;
1144 if ((domname == NULL) || (devpath == NULL))
1145 return 0;
1147 n = sizeof(char) * (strlen(domname) + strlen(devpath) + 2);
1148 name = malloc(n);
1149 if (name == NULL) {
1150 ERROR(PLUGIN_NAME " plugin: malloc failed.");
1151 return 0;
1152 }
1153 ssnprintf(name, n, "%s:%s", domname, devpath);
1154 r = ignorelist_match(il, name);
1155 sfree(name);
1156 return r;
1157 }
1159 static int lv_shutdown(void) {
1160 for (int i = 0; i < nr_instances; ++i) {
1161 lv_fini_instance(i);
1162 }
1164 if (conn != NULL)
1165 virConnectClose(conn);
1166 conn = NULL;
1168 ignorelist_free(il_domains);
1169 il_domains = NULL;
1170 ignorelist_free(il_block_devices);
1171 il_block_devices = NULL;
1172 ignorelist_free(il_interface_devices);
1173 il_interface_devices = NULL;
1175 return 0;
1176 }
1178 void module_register(void) {
1179 plugin_register_config(PLUGIN_NAME, lv_config, config_keys, NR_CONFIG_KEYS);
1180 plugin_register_init(PLUGIN_NAME, lv_init);
1181 plugin_register_shutdown(PLUGIN_NAME, lv_shutdown);
1182 }