virt plugin: Support for multiple read callbacks
[collectd.git] / src / virt.c
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  **/
21
22 #include "collectd.h"
23
24 #include "common.h"
25 #include "plugin.h"
26 #include "utils_complain.h"
27 #include "utils_ignorelist.h"
28
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
36 /* Plugin name */
37 #define PLUGIN_NAME "virt"
38
39 static const char *config_keys[] = {"Connection",
40
41                                     "RefreshInterval",
42
43                                     "Domain",
44                                     "BlockDevice",
45                                     "BlockDeviceFormat",
46                                     "BlockDeviceFormatBasename",
47                                     "InterfaceDevice",
48                                     "IgnoreSelected",
49
50                                     "HostnameFormat",
51                                     "InterfaceFormat",
52
53                                     "PluginInstanceFormat",
54
55                                     "Instances",
56
57                                     NULL};
58 #define NR_CONFIG_KEYS ((sizeof config_keys / sizeof config_keys[0]) - 1)
59
60 /* Connection. */
61 static virConnectPtr conn = 0;
62 static char *conn_string = NULL;
63 static c_complain_t conn_complain = C_COMPLAIN_INIT_STATIC;
64
65 /* Seconds between list refreshes, 0 disables completely. */
66 static int interval = 60;
67
68 /* List of domains, if specified. */
69 static ignorelist_t *il_domains = NULL;
70 /* List of block devices, if specified. */
71 static ignorelist_t *il_block_devices = NULL;
72 /* List of network interface devices, if specified. */
73 static ignorelist_t *il_interface_devices = NULL;
74
75 static int ignore_device_match(ignorelist_t *, const char *domname,
76                                const char *devpath);
77
78 /* Actual list of block devices found on last refresh. */
79 struct block_device {
80   virDomainPtr dom; /* domain */
81   char *path;       /* name of block device */
82 };
83
84 /* Actual list of network interfaces found on last refresh. */
85 struct interface_device {
86   virDomainPtr dom; /* domain */
87   char *path;       /* name of interface device */
88   char *address;    /* mac address of interface device */
89   char *number;     /* interface device number */
90 };
91
92 struct lv_read_state {
93   /* Actual list of domains found on last refresh. */
94   virDomainPtr *domains;
95   int nr_domains;
96
97   struct block_device *block_devices;
98   int nr_block_devices;
99
100   struct interface_device *interface_devices;
101   int nr_interface_devices;
102 };
103
104 static void free_domains(struct lv_read_state *state);
105 static int add_domain(struct lv_read_state *state, virDomainPtr dom);
106
107 static void free_block_devices(struct lv_read_state *state);
108 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
109                             const char *path);
110
111 static void free_interface_devices(struct lv_read_state *state);
112 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
113                                 const char *path, const char *address,
114                                 unsigned int number);
115
116 #define PARTITION_TAG_MAX_LEN 32
117 struct lv_read_instance {
118   struct lv_read_state read_state;
119   char tag[PARTITION_TAG_MAX_LEN];
120   size_t id;
121 };
122
123 struct lv_user_data {
124   struct lv_read_instance inst;
125   user_data_t ud;
126 };
127
128 #define NR_INSTANCES_DEFAULT 1
129 #define NR_INSTANCES_MAX 128
130 static size_t nr_instances = NR_INSTANCES_DEFAULT;
131 static struct lv_user_data lv_read_user_data[NR_INSTANCES_MAX];
132
133 /* HostnameFormat. */
134 #define HF_MAX_FIELDS 3
135
136 enum hf_field { hf_none = 0, hf_hostname, hf_name, hf_uuid };
137
138 static enum hf_field hostname_format[HF_MAX_FIELDS] = {hf_name};
139
140 /* PluginInstanceFormat */
141 #define PLGINST_MAX_FIELDS 2
142
143 enum plginst_field { plginst_none = 0, plginst_name, plginst_uuid };
144
145 static enum plginst_field plugin_instance_format[PLGINST_MAX_FIELDS] = {
146     plginst_none};
147
148 /* BlockDeviceFormat */
149 enum bd_field { target, source };
150
151 /* InterfaceFormat. */
152 enum if_field { if_address, if_name, if_number };
153
154 /* BlockDeviceFormatBasename */
155 _Bool blockdevice_format_basename = 0;
156 static enum bd_field blockdevice_format = target;
157 static enum if_field interface_format = if_name;
158
159 /* Time that we last refreshed. */
160 static time_t last_refresh = (time_t)0;
161
162 static int refresh_lists(struct lv_read_state *state);
163
164 /* ERROR(...) macro for virterrors. */
165 #define VIRT_ERROR(conn, s)                                                    \
166   do {                                                                         \
167     virErrorPtr err;                                                           \
168     err = (conn) ? virConnGetLastError((conn)) : virGetLastError();            \
169     if (err)                                                                   \
170       ERROR("%s: %s", (s), err->message);                                      \
171   } while (0)
172
173 static void init_value_list(value_list_t *vl, virDomainPtr dom) {
174   int n;
175   const char *name;
176   char uuid[VIR_UUID_STRING_BUFLEN];
177
178   sstrncpy(vl->plugin, PLUGIN_NAME, sizeof(vl->plugin));
179
180   vl->host[0] = '\0';
181
182   /* Construct the hostname field according to HostnameFormat. */
183   for (int i = 0; i < HF_MAX_FIELDS; ++i) {
184     if (hostname_format[i] == hf_none)
185       continue;
186
187     n = DATA_MAX_NAME_LEN - strlen(vl->host) - 2;
188
189     if (i > 0 && n >= 1) {
190       strncat(vl->host, ":", 1);
191       n--;
192     }
193
194     switch (hostname_format[i]) {
195     case hf_none:
196       break;
197     case hf_hostname:
198       strncat(vl->host, hostname_g, n);
199       break;
200     case hf_name:
201       name = virDomainGetName(dom);
202       if (name)
203         strncat(vl->host, name, n);
204       break;
205     case hf_uuid:
206       if (virDomainGetUUIDString(dom, uuid) == 0)
207         strncat(vl->host, uuid, n);
208       break;
209     }
210   }
211
212   vl->host[sizeof(vl->host) - 1] = '\0';
213
214   /* Construct the plugin instance field according to PluginInstanceFormat. */
215   for (int i = 0; i < PLGINST_MAX_FIELDS; ++i) {
216     if (plugin_instance_format[i] == plginst_none)
217       continue;
218
219     n = sizeof(vl->plugin_instance) - strlen(vl->plugin_instance) - 2;
220
221     if (i > 0 && n >= 1) {
222       strncat(vl->plugin_instance, ":", 1);
223       n--;
224     }
225
226     switch (plugin_instance_format[i]) {
227     case plginst_none:
228       break;
229     case plginst_name:
230       name = virDomainGetName(dom);
231       if (name)
232         strncat(vl->plugin_instance, name, n);
233       break;
234     case plginst_uuid:
235       if (virDomainGetUUIDString(dom, uuid) == 0)
236         strncat(vl->plugin_instance, uuid, n);
237       break;
238     }
239   }
240
241   vl->plugin_instance[sizeof(vl->plugin_instance) - 1] = '\0';
242
243 } /* void init_value_list */
244
245 static void submit(virDomainPtr dom, char const *type,
246                    char const *type_instance, value_t *values,
247                    size_t values_len) {
248   value_list_t vl = VALUE_LIST_INIT;
249   init_value_list(&vl, dom);
250
251   vl.values = values;
252   vl.values_len = values_len;
253
254   sstrncpy(vl.type, type, sizeof(vl.type));
255   if (type_instance != NULL)
256     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
257
258   plugin_dispatch_values(&vl);
259 }
260
261 static void memory_submit(gauge_t value, virDomainPtr dom) {
262   submit(dom, "memory", "total", &(value_t){.gauge = value}, 1);
263 }
264
265 static void memory_stats_submit(gauge_t value, virDomainPtr dom,
266                                 int tag_index) {
267   static const char *tags[] = {"swap_in",        "swap_out", "major_fault",
268                                "minor_fault",    "unused",   "available",
269                                "actual_balloon", "rss"};
270
271   if ((tag_index < 0) || (tag_index >= STATIC_ARRAY_SIZE(tags))) {
272     ERROR("virt plugin: Array index out of bounds: tag_index = %d", tag_index);
273     return;
274   }
275
276   submit(dom, "memory", tags[tag_index], &(value_t){.gauge = value}, 1);
277 }
278
279 static void cpu_submit(unsigned long long value, virDomainPtr dom,
280                        const char *type) {
281   submit(dom, type, NULL, &(value_t){.derive = (derive_t)value}, 1);
282 }
283
284 static void vcpu_submit(derive_t value, virDomainPtr dom, int vcpu_nr,
285                         const char *type) {
286   char type_instance[DATA_MAX_NAME_LEN];
287
288   ssnprintf(type_instance, sizeof(type_instance), "%d", vcpu_nr);
289
290   submit(dom, type, type_instance, &(value_t){.derive = value}, 1);
291 }
292
293 static void submit_derive2(const char *type, derive_t v0, derive_t v1,
294                            virDomainPtr dom, const char *devname) {
295   value_t values[] = {
296       {.derive = v0}, {.derive = v1},
297   };
298
299   submit(dom, type, devname, values, STATIC_ARRAY_SIZE(values));
300 } /* void submit_derive2 */
301
302 static int lv_config(const char *key, const char *value) {
303   if (virInitialize() != 0)
304     return 1;
305
306   if (il_domains == NULL)
307     il_domains = ignorelist_create(1);
308   if (il_block_devices == NULL)
309     il_block_devices = ignorelist_create(1);
310   if (il_interface_devices == NULL)
311     il_interface_devices = ignorelist_create(1);
312
313   if (strcasecmp(key, "Connection") == 0) {
314     char *tmp = strdup(value);
315     if (tmp == NULL) {
316       ERROR(PLUGIN_NAME " plugin: Connection strdup failed.");
317       return 1;
318     }
319     sfree(conn_string);
320     conn_string = tmp;
321     return 0;
322   }
323
324   if (strcasecmp(key, "RefreshInterval") == 0) {
325     char *eptr = NULL;
326     interval = strtol(value, &eptr, 10);
327     if (eptr == NULL || *eptr != '\0')
328       return 1;
329     return 0;
330   }
331
332   if (strcasecmp(key, "Domain") == 0) {
333     if (ignorelist_add(il_domains, value))
334       return 1;
335     return 0;
336   }
337   if (strcasecmp(key, "BlockDevice") == 0) {
338     if (ignorelist_add(il_block_devices, value))
339       return 1;
340     return 0;
341   }
342
343   if (strcasecmp(key, "BlockDeviceFormat") == 0) {
344     if (strcasecmp(value, "target") == 0)
345       blockdevice_format = target;
346     else if (strcasecmp(value, "source") == 0)
347       blockdevice_format = source;
348     else {
349       ERROR(PLUGIN_NAME " plugin: unknown BlockDeviceFormat: %s", value);
350       return -1;
351     }
352     return 0;
353   }
354   if (strcasecmp(key, "BlockDeviceFormatBasename") == 0) {
355     blockdevice_format_basename = IS_TRUE(value);
356     return 0;
357   }
358   if (strcasecmp(key, "InterfaceDevice") == 0) {
359     if (ignorelist_add(il_interface_devices, value))
360       return 1;
361     return 0;
362   }
363
364   if (strcasecmp(key, "IgnoreSelected") == 0) {
365     if (IS_TRUE(value)) {
366       ignorelist_set_invert(il_domains, 0);
367       ignorelist_set_invert(il_block_devices, 0);
368       ignorelist_set_invert(il_interface_devices, 0);
369     } else {
370       ignorelist_set_invert(il_domains, 1);
371       ignorelist_set_invert(il_block_devices, 1);
372       ignorelist_set_invert(il_interface_devices, 1);
373     }
374     return 0;
375   }
376
377   if (strcasecmp(key, "HostnameFormat") == 0) {
378     char *value_copy;
379     char *fields[HF_MAX_FIELDS];
380     int n;
381
382     value_copy = strdup(value);
383     if (value_copy == NULL) {
384       ERROR(PLUGIN_NAME " plugin: strdup failed.");
385       return -1;
386     }
387
388     n = strsplit(value_copy, fields, HF_MAX_FIELDS);
389     if (n < 1) {
390       sfree(value_copy);
391       ERROR(PLUGIN_NAME " plugin: HostnameFormat: no fields");
392       return -1;
393     }
394
395     for (int i = 0; i < n; ++i) {
396       if (strcasecmp(fields[i], "hostname") == 0)
397         hostname_format[i] = hf_hostname;
398       else if (strcasecmp(fields[i], "name") == 0)
399         hostname_format[i] = hf_name;
400       else if (strcasecmp(fields[i], "uuid") == 0)
401         hostname_format[i] = hf_uuid;
402       else {
403         ERROR(PLUGIN_NAME " plugin: unknown HostnameFormat field: %s",
404               fields[i]);
405         sfree(value_copy);
406         return -1;
407       }
408     }
409     sfree(value_copy);
410
411     for (int i = n; i < HF_MAX_FIELDS; ++i)
412       hostname_format[i] = hf_none;
413
414     return 0;
415   }
416
417   if (strcasecmp(key, "PluginInstanceFormat") == 0) {
418     char *value_copy;
419     char *fields[PLGINST_MAX_FIELDS];
420     int n;
421
422     value_copy = strdup(value);
423     if (value_copy == NULL) {
424       ERROR(PLUGIN_NAME " plugin: strdup failed.");
425       return -1;
426     }
427
428     n = strsplit(value_copy, fields, PLGINST_MAX_FIELDS);
429     if (n < 1) {
430       sfree(value_copy);
431       ERROR(PLUGIN_NAME " plugin: PluginInstanceFormat: no fields");
432       return -1;
433     }
434
435     for (int i = 0; i < n; ++i) {
436       if (strcasecmp(fields[i], "none") == 0) {
437         plugin_instance_format[i] = plginst_none;
438         break;
439       } else if (strcasecmp(fields[i], "name") == 0)
440         plugin_instance_format[i] = plginst_name;
441       else if (strcasecmp(fields[i], "uuid") == 0)
442         plugin_instance_format[i] = plginst_uuid;
443       else {
444         ERROR(PLUGIN_NAME " plugin: unknown PluginInstanceFormat field: %s",
445               fields[i]);
446         sfree(value_copy);
447         return -1;
448       }
449     }
450     sfree(value_copy);
451
452     for (int i = n; i < PLGINST_MAX_FIELDS; ++i)
453       plugin_instance_format[i] = plginst_none;
454
455     return 0;
456   }
457
458   if (strcasecmp(key, "InterfaceFormat") == 0) {
459     if (strcasecmp(value, "name") == 0)
460       interface_format = if_name;
461     else if (strcasecmp(value, "address") == 0)
462       interface_format = if_address;
463     else if (strcasecmp(value, "number") == 0)
464       interface_format = if_number;
465     else {
466       ERROR(PLUGIN_NAME " plugin: unknown InterfaceFormat: %s", value);
467       return -1;
468     }
469     return 0;
470   }
471
472   if (strcasecmp(key, "Instances") == 0) {
473     char *eptr = NULL;
474     long val = strtol(value, &eptr, 10);
475     if (eptr == NULL || *eptr != '\0')
476       return 1;
477     if (val <= 0) {
478       ERROR(PLUGIN_NAME " plugin: Instances <= 0 makes no sense.");
479       return 1;
480     }
481     if (val > NR_INSTANCES_MAX) {
482       ERROR(PLUGIN_NAME " plugin: Instances=%li > NR_INSTANCES_MAX=%i"
483                         " use a lower setting or recompile the plugin.",
484             val, NR_INSTANCES_MAX);
485       return 1;
486     }
487     nr_instances = (size_t)val;
488     return 0;
489   }
490
491   /* Unrecognised option. */
492   return -1;
493 }
494
495 static int lv_read(user_data_t *ud) {
496   time_t t;
497   struct lv_read_instance *inst = ud->data;
498   struct lv_read_state *state = &inst->read_state;
499   if (!inst) {
500     ERROR(PLUGIN_NAME " plugin: NULL userdata");
501     return -1;
502   }
503
504   if (inst->id == 0 && conn == NULL) {
505     /* `conn_string == NULL' is acceptable. */
506     conn = virConnectOpenReadOnly(conn_string);
507     if (conn == NULL) {
508       c_complain(LOG_ERR, &conn_complain,
509                  PLUGIN_NAME " plugin: Unable to connect: "
510                              "virConnectOpenReadOnly failed.");
511       return -1;
512     }
513   }
514   c_release(LOG_NOTICE, &conn_complain,
515             PLUGIN_NAME " plugin: Connection established.");
516
517   time(&t);
518
519   /* Need to refresh domain or device lists? */
520   if ((last_refresh == (time_t)0) ||
521       ((interval > 0) && ((last_refresh + interval) <= t))) {
522     if (refresh_lists(state) != 0) {
523       if (conn != NULL)
524         virConnectClose(conn);
525       conn = NULL;
526       return -1;
527     }
528     last_refresh = t;
529   }
530
531 #if 0
532     for (int i = 0; i < nr_domains; ++i)
533         fprintf (stderr, "domain %s\n", virDomainGetName (domains[i]));
534     for (int i = 0; i < nr_block_devices; ++i)
535         fprintf  (stderr, "block device %d %s:%s\n",
536                   i, virDomainGetName (block_devices[i].dom),
537                   block_devices[i].path);
538     for (int i = 0; i < nr_interface_devices; ++i)
539         fprintf (stderr, "interface device %d %s:%s\n",
540                  i, virDomainGetName (interface_devices[i].dom),
541                  interface_devices[i].path);
542 #endif
543
544   /* Get CPU usage, memory, VCPU usage for each domain. */
545   for (int i = 0; i < state->nr_domains; ++i) {
546     virDomainInfo info;
547     virVcpuInfoPtr vinfo = NULL;
548     virDomainMemoryStatPtr minfo = NULL;
549     int status;
550
551     status = virDomainGetInfo(state->domains[i], &info);
552     if (status != 0) {
553       ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
554             status);
555       continue;
556     }
557
558     if (info.state != VIR_DOMAIN_RUNNING) {
559       /* only gather stats for running domains */
560       continue;
561     }
562
563     cpu_submit(info.cpuTime, state->domains[i], "virt_cpu_total");
564     memory_submit((gauge_t)info.memory * 1024, state->domains[i]);
565
566     vinfo = malloc(info.nrVirtCpu * sizeof(vinfo[0]));
567     if (vinfo == NULL) {
568       ERROR(PLUGIN_NAME " plugin: malloc failed.");
569       continue;
570     }
571
572     status = virDomainGetVcpus(state->domains[i], vinfo, info.nrVirtCpu,
573                                /* cpu map = */ NULL, /* cpu map length = */ 0);
574     if (status < 0) {
575       ERROR(PLUGIN_NAME " plugin: virDomainGetVcpus failed with status %i.",
576             status);
577       sfree(vinfo);
578       continue;
579     }
580
581     for (int j = 0; j < info.nrVirtCpu; ++j)
582       vcpu_submit(vinfo[j].cpuTime, state->domains[i], vinfo[j].number,
583                   "virt_vcpu");
584
585     sfree(vinfo);
586
587     minfo =
588         malloc(VIR_DOMAIN_MEMORY_STAT_NR * sizeof(virDomainMemoryStatStruct));
589     if (minfo == NULL) {
590       ERROR("virt plugin: malloc failed.");
591       continue;
592     }
593
594     status = virDomainMemoryStats(state->domains[i], minfo,
595                                   VIR_DOMAIN_MEMORY_STAT_NR, 0);
596
597     if (status < 0) {
598       ERROR("virt plugin: virDomainMemoryStats failed with status %i.", status);
599       sfree(minfo);
600       continue;
601     }
602
603     for (int j = 0; j < status; j++) {
604       memory_stats_submit((gauge_t)minfo[j].val * 1024, state->domains[i],
605                           minfo[j].tag);
606     }
607
608     sfree(minfo);
609   }
610
611   /* Get block device stats for each domain. */
612   for (int i = 0; i < state->nr_block_devices; ++i) {
613     struct _virDomainBlockStats stats;
614
615     if (virDomainBlockStats(state->block_devices[i].dom,
616                             state->block_devices[i].path, &stats,
617                             sizeof stats) != 0)
618       continue;
619
620     char *type_instance = NULL;
621     if (blockdevice_format_basename && blockdevice_format == source)
622       type_instance = strdup(basename(state->block_devices[i].path));
623     else
624       type_instance = strdup(state->block_devices[i].path);
625
626     if ((stats.rd_req != -1) && (stats.wr_req != -1))
627       submit_derive2("disk_ops", (derive_t)stats.rd_req, (derive_t)stats.wr_req,
628                      state->block_devices[i].dom, type_instance);
629
630     if ((stats.rd_bytes != -1) && (stats.wr_bytes != -1))
631       submit_derive2("disk_octets", (derive_t)stats.rd_bytes,
632                      (derive_t)stats.wr_bytes, state->block_devices[i].dom,
633                      type_instance);
634
635     sfree(type_instance);
636   } /* for (nr_block_devices) */
637
638   /* Get interface stats for each domain. */
639   for (int i = 0; i < state->nr_interface_devices; ++i) {
640     struct _virDomainInterfaceStats stats;
641     char *display_name = NULL;
642
643     switch (interface_format) {
644     case if_address:
645       display_name = state->interface_devices[i].address;
646       break;
647     case if_number:
648       display_name = state->interface_devices[i].number;
649       break;
650     case if_name:
651     default:
652       display_name = state->interface_devices[i].path;
653     }
654
655     if (virDomainInterfaceStats(state->interface_devices[i].dom,
656                                 state->interface_devices[i].path, &stats,
657                                 sizeof stats) != 0)
658       continue;
659
660     if ((stats.rx_bytes != -1) && (stats.tx_bytes != -1))
661       submit_derive2("if_octets", (derive_t)stats.rx_bytes,
662                      (derive_t)stats.tx_bytes, state->interface_devices[i].dom,
663                      display_name);
664
665     if ((stats.rx_packets != -1) && (stats.tx_packets != -1))
666       submit_derive2("if_packets", (derive_t)stats.rx_packets,
667                      (derive_t)stats.tx_packets,
668                      state->interface_devices[i].dom, display_name);
669
670     if ((stats.rx_errs != -1) && (stats.tx_errs != -1))
671       submit_derive2("if_errors", (derive_t)stats.rx_errs,
672                      (derive_t)stats.tx_errs, state->interface_devices[i].dom,
673                      display_name);
674
675     if ((stats.rx_drop != -1) && (stats.tx_drop != -1))
676       submit_derive2("if_dropped", (derive_t)stats.rx_drop,
677                      (derive_t)stats.tx_drop, state->interface_devices[i].dom,
678                      display_name);
679   } /* for (nr_interface_devices) */
680
681   return 0;
682 }
683
684 static int lv_init_instance(size_t i, plugin_read_cb callback) {
685   struct lv_user_data *lv_ud = &(lv_read_user_data[i]);
686   struct lv_read_instance *inst = &lv_ud->inst;
687
688   memset(lv_ud, 0, sizeof(*lv_ud));
689
690   ssnprintf(inst->tag, sizeof(inst->tag), "%s-%zu", PLUGIN_NAME, i);
691   inst->id = i;
692
693   user_data_t *ud = &lv_ud->ud;
694   ud->data = inst;
695   ud->free_func = NULL;
696
697   INFO(PLUGIN_NAME "plugin: reader %s initialized", inst->tag);
698   return plugin_register_complex_read(NULL, inst->tag, callback, 0, ud);
699 }
700
701 static int lv_init(void) {
702   if (virInitialize() != 0)
703     return -1;
704
705   for (size_t i = 0; i < nr_instances; ++i)
706     lv_init_instance(i, lv_read);
707
708   return 0;
709 }
710
711 static int refresh_lists(struct lv_read_state *state) {
712   int n;
713
714   n = virConnectNumOfDomains(conn);
715   if (n < 0) {
716     VIRT_ERROR(conn, "reading number of domains");
717     return -1;
718   }
719
720   if (n > 0) {
721     int *domids;
722
723     /* Get list of domains. */
724     domids = malloc(sizeof(*domids) * n);
725     if (domids == NULL) {
726       ERROR(PLUGIN_NAME " plugin: malloc failed.");
727       return -1;
728     }
729
730     n = virConnectListDomains(conn, domids, n);
731     if (n < 0) {
732       VIRT_ERROR(conn, "reading list of domains");
733       sfree(domids);
734       return -1;
735     }
736
737     free_block_devices(state);
738     free_interface_devices(state);
739     free_domains(state);
740
741     /* Fetch each domain and add it to the list, unless ignore. */
742     for (int i = 0; i < n; ++i) {
743       virDomainPtr dom = NULL;
744       const char *name;
745       char *xml = NULL;
746       xmlDocPtr xml_doc = NULL;
747       xmlXPathContextPtr xpath_ctx = NULL;
748       xmlXPathObjectPtr xpath_obj = NULL;
749
750       dom = virDomainLookupByID(conn, domids[i]);
751       if (dom == NULL) {
752         VIRT_ERROR(conn, "virDomainLookupByID");
753         /* Could be that the domain went away -- ignore it anyway. */
754         continue;
755       }
756
757       name = virDomainGetName(dom);
758       if (name == NULL) {
759         VIRT_ERROR(conn, "virDomainGetName");
760         goto cont;
761       }
762
763       if (il_domains && ignorelist_match(il_domains, name) != 0)
764         goto cont;
765
766       if (add_domain(state, dom) < 0) {
767         ERROR(PLUGIN_NAME " plugin: malloc failed.");
768         goto cont;
769       }
770
771       /* Get a list of devices for this domain. */
772       xml = virDomainGetXMLDesc(dom, 0);
773       if (!xml) {
774         VIRT_ERROR(conn, "virDomainGetXMLDesc");
775         goto cont;
776       }
777
778       /* Yuck, XML.  Parse out the devices. */
779       xml_doc = xmlReadDoc((xmlChar *)xml, NULL, NULL, XML_PARSE_NONET);
780       if (xml_doc == NULL) {
781         VIRT_ERROR(conn, "xmlReadDoc");
782         goto cont;
783       }
784
785       xpath_ctx = xmlXPathNewContext(xml_doc);
786
787       /* Block devices. */
788       char *bd_xmlpath = "/domain/devices/disk/target[@dev]";
789       if (blockdevice_format == source)
790         bd_xmlpath = "/domain/devices/disk/source[@dev]";
791       xpath_obj = xmlXPathEval((xmlChar *)bd_xmlpath, xpath_ctx);
792
793       if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
794           xpath_obj->nodesetval == NULL)
795         goto cont;
796
797       for (int j = 0; j < xpath_obj->nodesetval->nodeNr; ++j) {
798         xmlNodePtr node;
799         char *path = NULL;
800
801         node = xpath_obj->nodesetval->nodeTab[j];
802         if (!node)
803           continue;
804         path = (char *)xmlGetProp(node, (xmlChar *)"dev");
805         if (!path)
806           continue;
807
808         if (il_block_devices &&
809             ignore_device_match(il_block_devices, name, path) != 0)
810           goto cont2;
811
812         add_block_device(state, dom, path);
813       cont2:
814         if (path)
815           xmlFree(path);
816       }
817       xmlXPathFreeObject(xpath_obj);
818
819       /* Network interfaces. */
820       xpath_obj = xmlXPathEval(
821           (xmlChar *)"/domain/devices/interface[target[@dev]]", xpath_ctx);
822       if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
823           xpath_obj->nodesetval == NULL)
824         goto cont;
825
826       xmlNodeSetPtr xml_interfaces = xpath_obj->nodesetval;
827
828       for (int j = 0; j < xml_interfaces->nodeNr; ++j) {
829         char *path = NULL;
830         char *address = NULL;
831         xmlNodePtr xml_interface;
832
833         xml_interface = xml_interfaces->nodeTab[j];
834         if (!xml_interface)
835           continue;
836
837         for (xmlNodePtr child = xml_interface->children; child;
838              child = child->next) {
839           if (child->type != XML_ELEMENT_NODE)
840             continue;
841
842           if (xmlStrEqual(child->name, (const xmlChar *)"target")) {
843             path = (char *)xmlGetProp(child, (const xmlChar *)"dev");
844             if (!path)
845               continue;
846           } else if (xmlStrEqual(child->name, (const xmlChar *)"mac")) {
847             address = (char *)xmlGetProp(child, (const xmlChar *)"address");
848             if (!address)
849               continue;
850           }
851         }
852
853         if (il_interface_devices &&
854             (ignore_device_match(il_interface_devices, name, path) != 0 ||
855              ignore_device_match(il_interface_devices, name, address) != 0))
856           goto cont3;
857
858         add_interface_device(state, dom, path, address, j + 1);
859       cont3:
860         if (path)
861           xmlFree(path);
862         if (address)
863           xmlFree(address);
864       }
865
866     cont:
867       if (xpath_obj)
868         xmlXPathFreeObject(xpath_obj);
869       if (xpath_ctx)
870         xmlXPathFreeContext(xpath_ctx);
871       if (xml_doc)
872         xmlFreeDoc(xml_doc);
873       sfree(xml);
874     }
875
876     sfree(domids);
877   }
878
879   return 0;
880 }
881
882 static void free_domains(struct lv_read_state *state) {
883   if (state->domains) {
884     for (int i = 0; i < state->nr_domains; ++i)
885       virDomainFree(state->domains[i]);
886     sfree(state->domains);
887   }
888   state->domains = NULL;
889   state->nr_domains = 0;
890 }
891
892 static int add_domain(struct lv_read_state *state, virDomainPtr dom) {
893   virDomainPtr *new_ptr;
894   int new_size = sizeof(state->domains[0]) * (state->nr_domains + 1);
895
896   if (state->domains)
897     new_ptr = realloc(state->domains, new_size);
898   else
899     new_ptr = malloc(new_size);
900
901   if (new_ptr == NULL)
902     return -1;
903
904   state->domains = new_ptr;
905   state->domains[state->nr_domains] = dom;
906   return state->nr_domains++;
907 }
908
909 static void free_block_devices(struct lv_read_state *state) {
910   if (state->block_devices) {
911     for (int i = 0; i < state->nr_block_devices; ++i)
912       sfree(state->block_devices[i].path);
913     sfree(state->block_devices);
914   }
915   state->block_devices = NULL;
916   state->nr_block_devices = 0;
917 }
918
919 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
920                             const char *path) {
921   struct block_device *new_ptr;
922   int new_size =
923       sizeof(state->block_devices[0]) * (state->nr_block_devices + 1);
924   char *path_copy;
925
926   path_copy = strdup(path);
927   if (!path_copy)
928     return -1;
929
930   if (state->block_devices)
931     new_ptr = realloc(state->block_devices, new_size);
932   else
933     new_ptr = malloc(new_size);
934
935   if (new_ptr == NULL) {
936     sfree(path_copy);
937     return -1;
938   }
939   state->block_devices = new_ptr;
940   state->block_devices[state->nr_block_devices].dom = dom;
941   state->block_devices[state->nr_block_devices].path = path_copy;
942   return state->nr_block_devices++;
943 }
944
945 static void free_interface_devices(struct lv_read_state *state) {
946   if (state->interface_devices) {
947     for (int i = 0; i < state->nr_interface_devices; ++i) {
948       sfree(state->interface_devices[i].path);
949       sfree(state->interface_devices[i].address);
950       sfree(state->interface_devices[i].number);
951     }
952     sfree(state->interface_devices);
953   }
954   state->interface_devices = NULL;
955   state->nr_interface_devices = 0;
956 }
957
958 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
959                                 const char *path, const char *address,
960                                 unsigned int number) {
961   struct interface_device *new_ptr;
962   int new_size =
963       sizeof(state->interface_devices[0]) * (state->nr_interface_devices + 1);
964   char *path_copy, *address_copy, number_string[15];
965
966   if ((path == NULL) || (address == NULL))
967     return EINVAL;
968
969   path_copy = strdup(path);
970   if (!path_copy)
971     return -1;
972
973   address_copy = strdup(address);
974   if (!address_copy) {
975     sfree(path_copy);
976     return -1;
977   }
978
979   snprintf(number_string, sizeof(number_string), "interface-%u", number);
980
981   if (state->interface_devices)
982     new_ptr = realloc(state->interface_devices, new_size);
983   else
984     new_ptr = malloc(new_size);
985
986   if (new_ptr == NULL) {
987     sfree(path_copy);
988     sfree(address_copy);
989     return -1;
990   }
991   state->interface_devices = new_ptr;
992   state->interface_devices[state->nr_interface_devices].dom = dom;
993   state->interface_devices[state->nr_interface_devices].path = path_copy;
994   state->interface_devices[state->nr_interface_devices].address = address_copy;
995   state->interface_devices[state->nr_interface_devices].number =
996       strdup(number_string);
997   return state->nr_interface_devices++;
998 }
999
1000 static int ignore_device_match(ignorelist_t *il, const char *domname,
1001                                const char *devpath) {
1002   char *name;
1003   int n, r;
1004
1005   if ((domname == NULL) || (devpath == NULL))
1006     return 0;
1007
1008   n = sizeof(char) * (strlen(domname) + strlen(devpath) + 2);
1009   name = malloc(n);
1010   if (name == NULL) {
1011     ERROR(PLUGIN_NAME " plugin: malloc failed.");
1012     return 0;
1013   }
1014   ssnprintf(name, n, "%s:%s", domname, devpath);
1015   r = ignorelist_match(il, name);
1016   sfree(name);
1017   return r;
1018 }
1019
1020 static int lv_shutdown(void) {
1021   for (size_t i = 0; i < nr_instances; ++i) {
1022     struct lv_read_state *state = &(lv_read_user_data[i].inst.read_state);
1023     free_block_devices(state);
1024     free_interface_devices(state);
1025     free_domains(state);
1026   }
1027
1028   if (conn != NULL)
1029     virConnectClose(conn);
1030   conn = NULL;
1031
1032   ignorelist_free(il_domains);
1033   il_domains = NULL;
1034   ignorelist_free(il_block_devices);
1035   il_block_devices = NULL;
1036   ignorelist_free(il_interface_devices);
1037   il_interface_devices = NULL;
1038
1039   return 0;
1040 }
1041
1042 void module_register(void) {
1043   plugin_register_config(PLUGIN_NAME, lv_config, config_keys, NR_CONFIG_KEYS);
1044   plugin_register_init(PLUGIN_NAME, lv_init);
1045   plugin_register_complex_read(NULL, PLUGIN_NAME, lv_read, 0, NULL);
1046   plugin_register_shutdown(PLUGIN_NAME, lv_shutdown);
1047 }
1048
1049 /*
1050  * vim: shiftwidth=4 tabstop=8 softtabstop=4 expandtab fdm=marker
1051  */