Merge pull request #2051 from dsilakov/virt_list_domains
[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 #include <libxml/xpathInternals.h>
36
37 /* Plugin name */
38 #define PLUGIN_NAME "virt"
39
40 #ifdef LIBVIR_CHECK_VERSION
41
42 #if LIBVIR_CHECK_VERSION(0, 9, 5)
43 #define HAVE_BLOCK_STATS_FLAGS 1
44 #endif
45
46 #if LIBVIR_CHECK_VERSION(0, 9, 11)
47 #define HAVE_CPU_STATS 1
48 #endif
49
50 #endif /* LIBVIR_CHECK_VERSION */
51
52 static const char *config_keys[] = {"Connection",
53
54                                     "RefreshInterval",
55
56                                     "Domain",
57                                     "BlockDevice",
58                                     "BlockDeviceFormat",
59                                     "BlockDeviceFormatBasename",
60                                     "InterfaceDevice",
61                                     "IgnoreSelected",
62
63                                     "HostnameFormat",
64                                     "InterfaceFormat",
65
66                                     "PluginInstanceFormat",
67
68                                     "Instances",
69                                     "ExtraStats",
70
71                                     NULL};
72 #define NR_CONFIG_KEYS ((sizeof config_keys / sizeof config_keys[0]) - 1)
73
74 /* Connection. */
75 static virConnectPtr conn = 0;
76 static char *conn_string = NULL;
77 static c_complain_t conn_complain = C_COMPLAIN_INIT_STATIC;
78
79 /* Seconds between list refreshes, 0 disables completely. */
80 static int interval = 60;
81
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;
88
89 static int ignore_device_match(ignorelist_t *, const char *domname,
90                                const char *devpath);
91
92 /* Actual list of block devices found on last refresh. */
93 struct block_device {
94   virDomainPtr dom; /* domain */
95   char *path;       /* name of block device */
96 };
97
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 */
104 };
105
106 struct lv_read_state {
107   /* Actual list of domains found on last refresh. */
108   virDomainPtr *domains;
109   int nr_domains;
110
111   struct block_device *block_devices;
112   int nr_block_devices;
113
114   struct interface_device *interface_devices;
115   int nr_interface_devices;
116 };
117
118 static void free_domains(struct lv_read_state *state);
119 static int add_domain(struct lv_read_state *state, virDomainPtr dom);
120
121 static void free_block_devices(struct lv_read_state *state);
122 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
123                             const char *path);
124
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);
129
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"
133
134 #define BUFFER_MAX_LEN 256
135 #define PARTITION_TAG_MAX_LEN 32
136
137 struct lv_read_instance {
138   struct lv_read_state read_state;
139   char tag[PARTITION_TAG_MAX_LEN];
140   size_t id;
141 };
142
143 struct lv_user_data {
144   struct lv_read_instance inst;
145   user_data_t ud;
146 };
147
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];
152
153 /* HostnameFormat. */
154 #define HF_MAX_FIELDS 3
155
156 enum hf_field { hf_none = 0, hf_hostname, hf_name, hf_uuid };
157
158 static enum hf_field hostname_format[HF_MAX_FIELDS] = {hf_name};
159
160 /* PluginInstanceFormat */
161 #define PLGINST_MAX_FIELDS 2
162
163 enum plginst_field { plginst_none = 0, plginst_name, plginst_uuid };
164
165 static enum plginst_field plugin_instance_format[PLGINST_MAX_FIELDS] = {
166     plginst_none};
167
168 /* BlockDeviceFormat */
169 enum bd_field { target, source };
170
171 /* InterfaceFormat. */
172 enum if_field { if_address, if_name, if_number };
173
174 /* ExtraStats */
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;
178
179 struct ex_stats_item {
180   const char *name;
181   enum ex_stats flag;
182 };
183 static const struct ex_stats_item ex_stats_table[] = {
184     {"disk", ex_stats_disk}, {"pcpu", ex_stats_pcpu}, {NULL, ex_stats_none},
185 };
186
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;
191
192 /* Time that we last refreshed. */
193 static time_t last_refresh = (time_t)0;
194
195 static int refresh_lists(struct lv_read_instance *inst);
196
197 struct lv_info {
198   virDomainInfo di;
199   unsigned long long total_user_cpu_time;
200   unsigned long long total_syst_cpu_time;
201 };
202
203 struct lv_block_info {
204   virDomainBlockStatsStruct bi;
205
206   long long rd_total_times;
207   long long wr_total_times;
208
209   long long fl_req;
210   long long fl_total_times;
211 };
212
213 static void init_block_info(struct lv_block_info *binfo) {
214   if (binfo == NULL)
215     return;
216
217   binfo->bi.rd_req = -1;
218   binfo->bi.wr_req = -1;
219   binfo->bi.rd_bytes = -1;
220   binfo->bi.wr_bytes = -1;
221
222   binfo->rd_total_times = -1;
223   binfo->wr_total_times = -1;
224   binfo->fl_req = -1;
225   binfo->fl_total_times = -1;
226 }
227
228 #ifdef HAVE_BLOCK_STATS_FLAGS
229
230 #define GET_BLOCK_INFO_VALUE(NAME, FIELD)                                      \
231   do {                                                                         \
232     if (!strcmp(param[i].field, NAME)) {                                       \
233       binfo->FIELD = param[i].value.l;                                         \
234       continue;                                                                \
235     }                                                                          \
236   } while (0)
237
238 static int get_block_info(struct lv_block_info *binfo,
239                           virTypedParameterPtr param, int nparams) {
240   if (binfo == NULL || param == NULL)
241     return -1;
242
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);
253   }
254
255   return 0;
256 }
257
258 #undef GET_BLOCK_INFO_VALUE
259
260 #endif /* HAVE_BLOCK_STATS_FLAGS */
261
262 /* ERROR(...) macro for virterrors. */
263 #define VIRT_ERROR(conn, s)                                                    \
264   do {                                                                         \
265     virErrorPtr err;                                                           \
266     err = (conn) ? virConnGetLastError((conn)) : virGetLastError();            \
267     if (err)                                                                   \
268       ERROR("%s: %s", (s), err->message);                                      \
269   } while (0)
270
271 static void init_lv_info(struct lv_info *info) {
272   if (info != NULL)
273     memset(info, 0, sizeof(*info));
274 }
275
276 static int lv_domain_info(virDomainPtr dom, struct lv_info *info) {
277 #ifdef HAVE_CPU_STATS
278   virTypedParameterPtr param = NULL;
279   int nparams = 0;
280 #endif /* HAVE_CPU_STATS */
281   int ret = virDomainGetInfo(dom, &(info->di));
282   if (ret != 0) {
283     return ret;
284   }
285
286 #ifdef HAVE_CPU_STATS
287   nparams = virDomainGetCPUStats(dom, NULL, 0, -1, 1, 0);
288   if (nparams < 0) {
289     VIRT_ERROR(conn, "getting the CPU params count");
290     return -1;
291   }
292
293   param = calloc(nparams, sizeof(virTypedParameter));
294   if (param == NULL) {
295     ERROR("virt plugin: alloc(%i) for cpu parameters failed.", nparams);
296     return -1;
297   }
298
299   ret = virDomainGetCPUStats(dom, param, nparams, -1, 1, 0); // total stats.
300   if (ret < 0) {
301     virTypedParamsFree(param, nparams);
302     VIRT_ERROR(conn, "getting the disk params values");
303     return -1;
304   }
305
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;
311   }
312
313   virTypedParamsFree(param, nparams);
314 #endif /* HAVE_CPU_STATS */
315
316   return 0;
317 }
318
319 static void init_value_list(value_list_t *vl, virDomainPtr dom) {
320   int n;
321   const char *name;
322   char uuid[VIR_UUID_STRING_BUFLEN];
323
324   sstrncpy(vl->plugin, PLUGIN_NAME, sizeof(vl->plugin));
325
326   vl->host[0] = '\0';
327
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)
331       continue;
332
333     n = DATA_MAX_NAME_LEN - strlen(vl->host) - 2;
334
335     if (i > 0 && n >= 1) {
336       strncat(vl->host, ":", 1);
337       n--;
338     }
339
340     switch (hostname_format[i]) {
341     case hf_none:
342       break;
343     case hf_hostname:
344       strncat(vl->host, hostname_g, n);
345       break;
346     case hf_name:
347       name = virDomainGetName(dom);
348       if (name)
349         strncat(vl->host, name, n);
350       break;
351     case hf_uuid:
352       if (virDomainGetUUIDString(dom, uuid) == 0)
353         strncat(vl->host, uuid, n);
354       break;
355     }
356   }
357
358   vl->host[sizeof(vl->host) - 1] = '\0';
359
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)
363       continue;
364
365     n = sizeof(vl->plugin_instance) - strlen(vl->plugin_instance) - 2;
366
367     if (i > 0 && n >= 1) {
368       strncat(vl->plugin_instance, ":", 1);
369       n--;
370     }
371
372     switch (plugin_instance_format[i]) {
373     case plginst_none:
374       break;
375     case plginst_name:
376       name = virDomainGetName(dom);
377       if (name)
378         strncat(vl->plugin_instance, name, n);
379       break;
380     case plginst_uuid:
381       if (virDomainGetUUIDString(dom, uuid) == 0)
382         strncat(vl->plugin_instance, uuid, n);
383       break;
384     }
385   }
386
387   vl->plugin_instance[sizeof(vl->plugin_instance) - 1] = '\0';
388
389 } /* void init_value_list */
390
391 static void submit(virDomainPtr dom, char const *type,
392                    char const *type_instance, value_t *values,
393                    size_t values_len) {
394   value_list_t vl = VALUE_LIST_INIT;
395   init_value_list(&vl, dom);
396
397   vl.values = values;
398   vl.values_len = values_len;
399
400   sstrncpy(vl.type, type, sizeof(vl.type));
401   if (type_instance != NULL)
402     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
403
404   plugin_dispatch_values(&vl);
405 }
406
407 static void memory_submit(gauge_t value, virDomainPtr dom) {
408   submit(dom, "memory", "total", &(value_t){.gauge = value}, 1);
409 }
410
411 static void memory_stats_submit(gauge_t value, virDomainPtr dom,
412                                 int tag_index) {
413   static const char *tags[] = {"swap_in",        "swap_out", "major_fault",
414                                "minor_fault",    "unused",   "available",
415                                "actual_balloon", "rss"};
416
417   if ((tag_index < 0) || (tag_index >= (int)STATIC_ARRAY_SIZE(tags))) {
418     ERROR("virt plugin: Array index out of bounds: tag_index = %d", tag_index);
419     return;
420   }
421
422   submit(dom, "memory", tags[tag_index], &(value_t){.gauge = value}, 1);
423 }
424
425 static void submit_derive2(const char *type, derive_t v0, derive_t v1,
426                            virDomainPtr dom, const char *devname) {
427   value_t values[] = {
428       {.derive = v0}, {.derive = v1},
429   };
430
431   submit(dom, type, devname, values, STATIC_ARRAY_SIZE(values));
432 } /* void submit_derive2 */
433
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 */
440 }
441
442 static void cpu_submit(unsigned long long value, virDomainPtr dom,
443                        const char *type) {
444   submit(dom, type, NULL, &(value_t){.derive = (derive_t)value}, 1);
445 }
446
447 static void vcpu_submit(derive_t value, virDomainPtr dom, int vcpu_nr,
448                         const char *type) {
449   char type_instance[DATA_MAX_NAME_LEN];
450
451   ssnprintf(type_instance, sizeof(type_instance), "%d", vcpu_nr);
452
453   submit(dom, type, type_instance, &(value_t){.derive = value}, 1);
454 }
455
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];
459
460   ssnprintf(flush_type_instance, sizeof(flush_type_instance), "flush-%s",
461             type_instance);
462
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);
466
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);
470
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);
475
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);
483     }
484   }
485 }
486
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;
495         break;
496       }
497     }
498   }
499   return ex_stats_flags;
500 }
501
502 static int lv_config(const char *key, const char *value) {
503   if (virInitialize() != 0)
504     return 1;
505
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);
512
513   if (strcasecmp(key, "Connection") == 0) {
514     char *tmp = strdup(value);
515     if (tmp == NULL) {
516       ERROR(PLUGIN_NAME " plugin: Connection strdup failed.");
517       return 1;
518     }
519     sfree(conn_string);
520     conn_string = tmp;
521     return 0;
522   }
523
524   if (strcasecmp(key, "RefreshInterval") == 0) {
525     char *eptr = NULL;
526     interval = strtol(value, &eptr, 10);
527     if (eptr == NULL || *eptr != '\0')
528       return 1;
529     return 0;
530   }
531
532   if (strcasecmp(key, "Domain") == 0) {
533     if (ignorelist_add(il_domains, value))
534       return 1;
535     return 0;
536   }
537   if (strcasecmp(key, "BlockDevice") == 0) {
538     if (ignorelist_add(il_block_devices, value))
539       return 1;
540     return 0;
541   }
542
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;
548     else {
549       ERROR(PLUGIN_NAME " plugin: unknown BlockDeviceFormat: %s", value);
550       return -1;
551     }
552     return 0;
553   }
554   if (strcasecmp(key, "BlockDeviceFormatBasename") == 0) {
555     blockdevice_format_basename = IS_TRUE(value);
556     return 0;
557   }
558   if (strcasecmp(key, "InterfaceDevice") == 0) {
559     if (ignorelist_add(il_interface_devices, value))
560       return 1;
561     return 0;
562   }
563
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);
569     } else {
570       ignorelist_set_invert(il_domains, 1);
571       ignorelist_set_invert(il_block_devices, 1);
572       ignorelist_set_invert(il_interface_devices, 1);
573     }
574     return 0;
575   }
576
577   if (strcasecmp(key, "HostnameFormat") == 0) {
578     char *value_copy;
579     char *fields[HF_MAX_FIELDS];
580     int n;
581
582     value_copy = strdup(value);
583     if (value_copy == NULL) {
584       ERROR(PLUGIN_NAME " plugin: strdup failed.");
585       return -1;
586     }
587
588     n = strsplit(value_copy, fields, HF_MAX_FIELDS);
589     if (n < 1) {
590       sfree(value_copy);
591       ERROR(PLUGIN_NAME " plugin: HostnameFormat: no fields");
592       return -1;
593     }
594
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;
602       else {
603         ERROR(PLUGIN_NAME " plugin: unknown HostnameFormat field: %s",
604               fields[i]);
605         sfree(value_copy);
606         return -1;
607       }
608     }
609     sfree(value_copy);
610
611     for (int i = n; i < HF_MAX_FIELDS; ++i)
612       hostname_format[i] = hf_none;
613
614     return 0;
615   }
616
617   if (strcasecmp(key, "PluginInstanceFormat") == 0) {
618     char *value_copy;
619     char *fields[PLGINST_MAX_FIELDS];
620     int n;
621
622     value_copy = strdup(value);
623     if (value_copy == NULL) {
624       ERROR(PLUGIN_NAME " plugin: strdup failed.");
625       return -1;
626     }
627
628     n = strsplit(value_copy, fields, PLGINST_MAX_FIELDS);
629     if (n < 1) {
630       sfree(value_copy);
631       ERROR(PLUGIN_NAME " plugin: PluginInstanceFormat: no fields");
632       return -1;
633     }
634
635     for (int i = 0; i < n; ++i) {
636       if (strcasecmp(fields[i], "none") == 0) {
637         plugin_instance_format[i] = plginst_none;
638         break;
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;
643       else {
644         ERROR(PLUGIN_NAME " plugin: unknown PluginInstanceFormat field: %s",
645               fields[i]);
646         sfree(value_copy);
647         return -1;
648       }
649     }
650     sfree(value_copy);
651
652     for (int i = n; i < PLGINST_MAX_FIELDS; ++i)
653       plugin_instance_format[i] = plginst_none;
654
655     return 0;
656   }
657
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;
665     else {
666       ERROR(PLUGIN_NAME " plugin: unknown InterfaceFormat: %s", value);
667       return -1;
668     }
669     return 0;
670   }
671
672   if (strcasecmp(key, "Instances") == 0) {
673     char *eptr = NULL;
674     double val = strtod(value, &eptr);
675
676     if (*eptr != '\0') {
677       ERROR(PLUGIN_NAME " plugin: Invalid value for Instances = '%s'", value);
678       return 1;
679     }
680     if (val <= 0) {
681       ERROR(PLUGIN_NAME " plugin: Instances <= 0 makes no sense.");
682       return 1;
683     }
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);
688       return 1;
689     }
690
691     nr_instances = (int)val;
692     DEBUG(PLUGIN_NAME " plugin: configured %i instances", nr_instances);
693     return 0;
694   }
695
696   if (strcasecmp(key, "ExtraStats") == 0) {
697     char *localvalue = strdup(value);
698     if (localvalue != NULL) {
699       char *exstats[EX_STATS_MAX_FIELDS];
700       int numexstats =
701           strsplit(localvalue, exstats, STATIC_ARRAY_SIZE(exstats));
702       extra_stats = parse_ex_stats_flags(exstats, numexstats);
703       sfree(localvalue);
704     }
705   }
706
707   /* Unrecognised option. */
708   return -1;
709 }
710
711 static int lv_connect(void) {
712   if (conn == NULL) {
713     /* `conn_string == NULL' is acceptable. */
714     conn = virConnectOpenReadOnly(conn_string);
715     if (conn == NULL) {
716       c_complain(LOG_ERR, &conn_complain,
717                  PLUGIN_NAME " plugin: Unable to connect: "
718                              "virConnectOpenReadOnly failed.");
719       return -1;
720     }
721   }
722   c_release(LOG_NOTICE, &conn_complain,
723             PLUGIN_NAME " plugin: Connection established.");
724   return 0;
725 }
726
727 static void lv_disconnect(void) {
728   if (conn != NULL)
729     virConnectClose(conn);
730   conn = NULL;
731   WARNING(PLUGIN_NAME " plugin: closed connection to libvirt");
732 }
733
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;
738   int nparams = 0;
739   int rc = -1;
740   int ret = virDomainBlockStatsFlags(dom, path, NULL, &nparams, 0);
741   if (ret < 0 || nparams == 0) {
742     VIRT_ERROR(conn, "getting the disk params count");
743     return -1;
744   }
745
746   params = calloc(nparams, sizeof(virTypedParameter));
747   if (params == NULL) {
748     ERROR("virt plugin: alloc(%i) for block=%s parameters failed.", nparams,
749           path);
750     return -1;
751   }
752   ret = virDomainBlockStatsFlags(dom, path, params, &nparams, 0);
753   if (ret < 0) {
754     VIRT_ERROR(conn, "getting the disk params values");
755     goto done;
756   }
757
758   rc = get_block_info(binfo, params, nparams);
759
760 done:
761   virTypedParamsFree(params, nparams);
762   return rc;
763 #else
764   return virDomainBlockStats(dom, path, &(binfo->bi), sizeof(binfo->bi));
765 #endif /* HAVE_BLOCK_STATS_FLAGS */
766 }
767
768 static int lv_read(user_data_t *ud) {
769   time_t t;
770   struct lv_read_instance *inst = NULL;
771   struct lv_read_state *state = NULL;
772
773   if (ud->data == NULL) {
774     ERROR(PLUGIN_NAME " plugin: NULL userdata");
775     return -1;
776   }
777
778   inst = ud->data;
779   state = &inst->read_state;
780
781   if (inst->id == 0) {
782     if (lv_connect() < 0)
783       return -1;
784   }
785
786   time(&t);
787
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) {
792       if (inst->id == 0)
793         lv_disconnect();
794       return -1;
795     }
796     last_refresh = t;
797   }
798
799 #if 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);
810 #endif
811
812   /* Get CPU usage, memory, VCPU usage for each domain. */
813   for (int i = 0; i < state->nr_domains; ++i) {
814     struct lv_info info;
815     virVcpuInfoPtr vinfo = NULL;
816     virDomainMemoryStatPtr minfo = NULL;
817     int status;
818
819     init_lv_info(&info);
820     status = lv_domain_info(state->domains[i], &info);
821     if (status != 0) {
822       ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
823             status);
824       continue;
825     }
826
827     pcpu_submit(state->domains[i], &info);
828     cpu_submit(info.di.cpuTime, state->domains[i], "virt_cpu_total");
829     memory_submit((gauge_t)info.di.memory * 1024, state->domains[i]);
830
831     vinfo = malloc(info.di.nrVirtCpu * sizeof(vinfo[0]));
832     if (vinfo == NULL) {
833       ERROR(PLUGIN_NAME " plugin: malloc failed.");
834       continue;
835     }
836
837     status = virDomainGetVcpus(state->domains[i], vinfo, info.di.nrVirtCpu,
838                                /* cpu map = */ NULL, /* cpu map length = */ 0);
839     if (status < 0) {
840       ERROR(PLUGIN_NAME " plugin: virDomainGetVcpus failed with status %i.",
841             status);
842       sfree(vinfo);
843       continue;
844     }
845
846     for (int j = 0; j < info.di.nrVirtCpu; ++j)
847       vcpu_submit(vinfo[j].cpuTime, state->domains[i], vinfo[j].number,
848                   "virt_vcpu");
849
850     sfree(vinfo);
851
852     minfo =
853         malloc(VIR_DOMAIN_MEMORY_STAT_NR * sizeof(virDomainMemoryStatStruct));
854     if (minfo == NULL) {
855       ERROR("virt plugin: malloc failed.");
856       continue;
857     }
858
859     status = virDomainMemoryStats(state->domains[i], minfo,
860                                   VIR_DOMAIN_MEMORY_STAT_NR, 0);
861
862     if (status < 0) {
863       ERROR("virt plugin: virDomainMemoryStats failed with status %i.", status);
864       sfree(minfo);
865       continue;
866     }
867
868     for (int j = 0; j < status; j++) {
869       memory_stats_submit((gauge_t)minfo[j].val * 1024, state->domains[i],
870                           minfo[j].tag);
871     }
872
873     sfree(minfo);
874   }
875
876   /* Get block device stats for each domain. */
877   for (int i = 0; i < state->nr_block_devices; ++i) {
878     struct block_device *bdev = &(state->block_devices[i]);
879     struct lv_block_info binfo;
880     init_block_info(&binfo);
881
882     if (lv_domain_block_info(bdev->dom, bdev->path, &binfo) < 0)
883       continue;
884
885     char *type_instance = bdev->path;
886     char *path = NULL;
887     if (blockdevice_format_basename && blockdevice_format == source) {
888       path = strdup(bdev->path);
889       if (path == NULL) {
890         WARNING(PLUGIN_NAME
891                 " plugin: error extracting the basename for '%s', skipped",
892                 bdev->path);
893         continue;
894       }
895       type_instance = basename(path);
896     }
897
898     disk_submit(&binfo, bdev->dom, type_instance);
899
900     sfree(path);
901   } /* for (nr_block_devices) */
902
903   /* Get interface stats for each domain. */
904   for (int i = 0; i < state->nr_interface_devices; ++i) {
905     struct _virDomainInterfaceStats stats;
906     char *display_name = NULL;
907
908     switch (interface_format) {
909     case if_address:
910       display_name = state->interface_devices[i].address;
911       break;
912     case if_number:
913       display_name = state->interface_devices[i].number;
914       break;
915     case if_name:
916     default:
917       display_name = state->interface_devices[i].path;
918     }
919
920     if (virDomainInterfaceStats(state->interface_devices[i].dom,
921                                 state->interface_devices[i].path, &stats,
922                                 sizeof stats) != 0)
923       continue;
924
925     if ((stats.rx_bytes != -1) && (stats.tx_bytes != -1))
926       submit_derive2("if_octets", (derive_t)stats.rx_bytes,
927                      (derive_t)stats.tx_bytes, state->interface_devices[i].dom,
928                      display_name);
929
930     if ((stats.rx_packets != -1) && (stats.tx_packets != -1))
931       submit_derive2("if_packets", (derive_t)stats.rx_packets,
932                      (derive_t)stats.tx_packets,
933                      state->interface_devices[i].dom, display_name);
934
935     if ((stats.rx_errs != -1) && (stats.tx_errs != -1))
936       submit_derive2("if_errors", (derive_t)stats.rx_errs,
937                      (derive_t)stats.tx_errs, state->interface_devices[i].dom,
938                      display_name);
939
940     if ((stats.rx_drop != -1) && (stats.tx_drop != -1))
941       submit_derive2("if_dropped", (derive_t)stats.rx_drop,
942                      (derive_t)stats.tx_drop, state->interface_devices[i].dom,
943                      display_name);
944   } /* for (nr_interface_devices) */
945
946   return 0;
947 }
948
949 static int lv_init_instance(size_t i, plugin_read_cb callback) {
950   struct lv_user_data *lv_ud = &(lv_read_user_data[i]);
951   struct lv_read_instance *inst = &(lv_ud->inst);
952
953   memset(lv_ud, 0, sizeof(*lv_ud));
954
955   ssnprintf(inst->tag, sizeof(inst->tag), "%s-%zu", PLUGIN_NAME, i);
956   inst->id = i;
957
958   user_data_t *ud = &(lv_ud->ud);
959   ud->data = inst;
960   ud->free_func = NULL;
961
962   INFO(PLUGIN_NAME " plugin: reader %s initialized", inst->tag);
963   return plugin_register_complex_read(NULL, inst->tag, callback, 0, ud);
964 }
965
966 static void lv_clean_read_state(struct lv_read_state *state) {
967   free_block_devices(state);
968   free_interface_devices(state);
969   free_domains(state);
970 }
971
972 static void lv_fini_instance(size_t i) {
973   struct lv_read_instance *inst = &(lv_read_user_data[i].inst);
974   struct lv_read_state *state = &(inst->read_state);
975
976   lv_clean_read_state(state);
977   INFO(PLUGIN_NAME " plugin: reader %s finalized", inst->tag);
978 }
979
980 static int lv_init(void) {
981   if (virInitialize() != 0)
982     return -1;
983
984   if (lv_connect() != 0)
985     return -1;
986
987   DEBUG(PLUGIN_NAME " plugin: starting %i instances", nr_instances);
988
989   for (int i = 0; i < nr_instances; ++i)
990     lv_init_instance(i, lv_read);
991
992   return 0;
993 }
994
995 /*
996  * returns 0 on success and <0 on error
997  */
998 static int lv_domain_get_tag(xmlXPathContextPtr xpath_ctx, const char *dom_name,
999                              char *dom_tag) {
1000   char xpath_str[BUFFER_MAX_LEN] = {'\0'};
1001   xmlXPathObjectPtr xpath_obj = NULL;
1002   xmlNodePtr xml_node = NULL;
1003   int ret = -1;
1004   int err;
1005
1006   err = xmlXPathRegisterNs(xpath_ctx,
1007                            (const xmlChar *)METADATA_VM_PARTITION_PREFIX,
1008                            (const xmlChar *)METADATA_VM_PARTITION_URI);
1009   if (err) {
1010     ERROR(PLUGIN_NAME " plugin: xmlXpathRegisterNs(%s, %s) failed on domain %s",
1011           METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_URI, dom_name);
1012     goto done;
1013   }
1014
1015   ssnprintf(xpath_str, sizeof(xpath_str), "/domain/metadata/%s:%s/text()",
1016             METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_ELEMENT);
1017   xpath_obj = xmlXPathEvalExpression((xmlChar *)xpath_str, xpath_ctx);
1018   if (xpath_obj == NULL) {
1019     ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) failed on domain %s",
1020           xpath_str, dom_name);
1021     goto done;
1022   }
1023
1024   if (xpath_obj->type != XPATH_NODESET) {
1025     ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) unexpected return type %d "
1026                       "(wanted %d) on domain %s",
1027           xpath_str, xpath_obj->type, XPATH_NODESET, dom_name);
1028     goto done;
1029   }
1030
1031   /*
1032    * from now on there is no real error, it's ok if a domain
1033    * doesn't have the metadata partition tag.
1034    */
1035   ret = 0;
1036   if (xpath_obj->nodesetval == NULL || xpath_obj->nodesetval->nodeNr != 1) {
1037     DEBUG(PLUGIN_NAME " plugin: xmlXPathEval(%s) return nodeset size=%i "
1038                       "expected=1 on domain %s",
1039           xpath_str,
1040           (xpath_obj->nodesetval == NULL) ? 0 : xpath_obj->nodesetval->nodeNr,
1041           dom_name);
1042   } else {
1043     xml_node = xpath_obj->nodesetval->nodeTab[0];
1044     sstrncpy(dom_tag, (const char *)xml_node->content, PARTITION_TAG_MAX_LEN);
1045   }
1046
1047 done:
1048   /* deregister to clean up */
1049   err = xmlXPathRegisterNs(xpath_ctx,
1050                            (const xmlChar *)METADATA_VM_PARTITION_PREFIX, NULL);
1051   if (err) {
1052     /* we can't really recover here */
1053     ERROR(PLUGIN_NAME
1054           " plugin: deregistration of namespace %s failed for domain %s",
1055           METADATA_VM_PARTITION_PREFIX, dom_name);
1056   }
1057   if (xpath_obj)
1058     xmlXPathFreeObject(xpath_obj);
1059
1060   return ret;
1061 }
1062
1063 static int is_known_tag(const char *dom_tag) {
1064   for (int i = 0; i < nr_instances; ++i)
1065     if (!strcmp(dom_tag, lv_read_user_data[i].inst.tag))
1066       return 1;
1067   return 0;
1068 }
1069
1070 static int lv_instance_include_domain(struct lv_read_instance *inst,
1071                                       const char *dom_name,
1072                                       const char *dom_tag) {
1073   if ((dom_tag[0] != '\0') && (strcmp(dom_tag, inst->tag) == 0))
1074     return 1;
1075
1076   /* instance#0 will always be there, so it is in charge of extra duties */
1077   if (inst->id == 0) {
1078     if (dom_tag[0] == '\0' || !is_known_tag(dom_tag)) {
1079       DEBUG(PLUGIN_NAME " plugin#%s: refreshing domain %s "
1080                         "with unknown tag '%s'",
1081             inst->tag, dom_name, dom_tag);
1082       return 1;
1083     }
1084   }
1085
1086   return 0;
1087 }
1088
1089 /*
1090   virConnectListAllDomains() appeared in 0.10.2
1091   Note that LIBVIR_CHECK_VERSION appeared a year later, so
1092   in some systems which actually have virConnectListAllDomains()
1093   we can't detect this.
1094  */
1095 #ifdef LIBVIR_CHECK_VERSION
1096 # if LIBVIR_CHECK_VERSION(0,10,2)
1097 #  define HAVE_LIST_ALL_DOMAINS 1
1098 # endif
1099 #endif
1100
1101 static int refresh_lists(struct lv_read_instance *inst) {
1102   struct lv_read_state *state = &inst->read_state;
1103   int n;
1104
1105   n = virConnectNumOfDomains(conn);
1106   if (n < 0) {
1107     VIRT_ERROR(conn, "reading number of domains");
1108     return -1;
1109   }
1110
1111   lv_clean_read_state(state);
1112
1113   if (n > 0) {
1114 #ifdef HAVE_LIST_ALL_DOMAINS
1115     virDomainPtr *domains;
1116     n = virConnectListAllDomains (conn, &domains, VIR_CONNECT_LIST_DOMAINS_ACTIVE);
1117 #else
1118     int *domids;
1119
1120     /* Get list of domains. */
1121     domids = malloc(sizeof(*domids) * n);
1122     if (domids == NULL) {
1123       ERROR(PLUGIN_NAME " plugin: malloc failed.");
1124       return -1;
1125     }
1126
1127     n = virConnectListDomains(conn, domids, n);
1128 #endif
1129
1130     if (n < 0) {
1131       VIRT_ERROR(conn, "reading list of domains");
1132 #ifndef HAVE_LIST_ALL_DOMAINS
1133       sfree(domids);
1134 #endif
1135       return -1;
1136     }
1137
1138     /* Fetch each domain and add it to the list, unless ignore. */
1139     for (int i = 0; i < n; ++i) {
1140       const char *name;
1141       char *xml = NULL;
1142       xmlDocPtr xml_doc = NULL;
1143       xmlXPathContextPtr xpath_ctx = NULL;
1144       xmlXPathObjectPtr xpath_obj = NULL;
1145       char tag[PARTITION_TAG_MAX_LEN] = {'\0'};
1146       virDomainInfo info;
1147       int status;
1148
1149 #ifdef HAVE_LIST_ALL_DOMAINS
1150       virDomainPtr dom = domains[i];
1151 #else
1152       virDomainPtr dom = NULL;
1153       dom = virDomainLookupByID(conn, domids[i]);
1154       if (dom == NULL) {
1155         VIRT_ERROR(conn, "virDomainLookupByID");
1156         /* Could be that the domain went away -- ignore it anyway. */
1157         continue;
1158       }
1159 #endif
1160
1161       name = virDomainGetName(dom);
1162       if (name == NULL) {
1163         VIRT_ERROR(conn, "virDomainGetName");
1164         goto cont;
1165       }
1166
1167       status = virDomainGetInfo(dom, &info);
1168       if (status != 0) {
1169         ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
1170               status);
1171         continue;
1172       }
1173
1174       if (info.state != VIR_DOMAIN_RUNNING) {
1175         DEBUG(PLUGIN_NAME " plugin: skipping inactive domain %s", name);
1176         continue;
1177       }
1178
1179       if (il_domains && ignorelist_match(il_domains, name) != 0)
1180         goto cont;
1181
1182       /* Get a list of devices for this domain. */
1183       xml = virDomainGetXMLDesc(dom, 0);
1184       if (!xml) {
1185         VIRT_ERROR(conn, "virDomainGetXMLDesc");
1186         goto cont;
1187       }
1188
1189       /* Yuck, XML.  Parse out the devices. */
1190       xml_doc = xmlReadDoc((xmlChar *)xml, NULL, NULL, XML_PARSE_NONET);
1191       if (xml_doc == NULL) {
1192         VIRT_ERROR(conn, "xmlReadDoc");
1193         goto cont;
1194       }
1195
1196       xpath_ctx = xmlXPathNewContext(xml_doc);
1197
1198       if (lv_domain_get_tag(xpath_ctx, name, tag) < 0) {
1199         ERROR(PLUGIN_NAME " plugin: lv_domain_get_tag failed.");
1200         goto cont;
1201       }
1202
1203       if (!lv_instance_include_domain(inst, name, tag))
1204         goto cont;
1205
1206       if (add_domain(state, dom) < 0) {
1207         ERROR(PLUGIN_NAME " plugin: malloc failed.");
1208         goto cont;
1209       }
1210
1211       /* Block devices. */
1212       const char *bd_xmlpath = "/domain/devices/disk/target[@dev]";
1213       if (blockdevice_format == source)
1214         bd_xmlpath = "/domain/devices/disk/source[@dev]";
1215       xpath_obj = xmlXPathEval((const xmlChar *)bd_xmlpath, xpath_ctx);
1216
1217       if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
1218           xpath_obj->nodesetval == NULL)
1219         goto cont;
1220
1221       for (int j = 0; j < xpath_obj->nodesetval->nodeNr; ++j) {
1222         xmlNodePtr node;
1223         char *path = NULL;
1224
1225         node = xpath_obj->nodesetval->nodeTab[j];
1226         if (!node)
1227           continue;
1228         path = (char *)xmlGetProp(node, (xmlChar *)"dev");
1229         if (!path)
1230           continue;
1231
1232         if (il_block_devices &&
1233             ignore_device_match(il_block_devices, name, path) != 0)
1234           goto cont2;
1235
1236         add_block_device(state, dom, path);
1237       cont2:
1238         if (path)
1239           xmlFree(path);
1240       }
1241       xmlXPathFreeObject(xpath_obj);
1242
1243       /* Network interfaces. */
1244       xpath_obj = xmlXPathEval(
1245           (xmlChar *)"/domain/devices/interface[target[@dev]]", xpath_ctx);
1246       if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
1247           xpath_obj->nodesetval == NULL)
1248         goto cont;
1249
1250       xmlNodeSetPtr xml_interfaces = xpath_obj->nodesetval;
1251
1252       for (int j = 0; j < xml_interfaces->nodeNr; ++j) {
1253         char *path = NULL;
1254         char *address = NULL;
1255         xmlNodePtr xml_interface;
1256
1257         xml_interface = xml_interfaces->nodeTab[j];
1258         if (!xml_interface)
1259           continue;
1260
1261         for (xmlNodePtr child = xml_interface->children; child;
1262              child = child->next) {
1263           if (child->type != XML_ELEMENT_NODE)
1264             continue;
1265
1266           if (xmlStrEqual(child->name, (const xmlChar *)"target")) {
1267             path = (char *)xmlGetProp(child, (const xmlChar *)"dev");
1268             if (!path)
1269               continue;
1270           } else if (xmlStrEqual(child->name, (const xmlChar *)"mac")) {
1271             address = (char *)xmlGetProp(child, (const xmlChar *)"address");
1272             if (!address)
1273               continue;
1274           }
1275         }
1276
1277         if (il_interface_devices &&
1278             (ignore_device_match(il_interface_devices, name, path) != 0 ||
1279              ignore_device_match(il_interface_devices, name, address) != 0))
1280           goto cont3;
1281
1282         add_interface_device(state, dom, path, address, j + 1);
1283       cont3:
1284         if (path)
1285           xmlFree(path);
1286         if (address)
1287           xmlFree(address);
1288       }
1289
1290     cont:
1291       if (xpath_obj)
1292         xmlXPathFreeObject(xpath_obj);
1293       if (xpath_ctx)
1294         xmlXPathFreeContext(xpath_ctx);
1295       if (xml_doc)
1296         xmlFreeDoc(xml_doc);
1297       sfree(xml);
1298     }
1299
1300 #ifdef HAVE_LIST_ALL_DOMAINS
1301     sfree (domains);
1302 #else
1303     sfree(domids);
1304 #endif
1305   }
1306
1307   DEBUG(PLUGIN_NAME " plugin#%s: refreshing"
1308                     " domains=%i block_devices=%i iface_devices=%i",
1309         inst->tag, state->nr_domains, state->nr_block_devices,
1310         state->nr_interface_devices);
1311
1312   return 0;
1313 }
1314
1315 static void free_domains(struct lv_read_state *state) {
1316   if (state->domains) {
1317     for (int i = 0; i < state->nr_domains; ++i)
1318       virDomainFree(state->domains[i]);
1319     sfree(state->domains);
1320   }
1321   state->domains = NULL;
1322   state->nr_domains = 0;
1323 }
1324
1325 static int add_domain(struct lv_read_state *state, virDomainPtr dom) {
1326   virDomainPtr *new_ptr;
1327   int new_size = sizeof(state->domains[0]) * (state->nr_domains + 1);
1328
1329   if (state->domains)
1330     new_ptr = realloc(state->domains, new_size);
1331   else
1332     new_ptr = malloc(new_size);
1333
1334   if (new_ptr == NULL)
1335     return -1;
1336
1337   state->domains = new_ptr;
1338   state->domains[state->nr_domains] = dom;
1339   return state->nr_domains++;
1340 }
1341
1342 static void free_block_devices(struct lv_read_state *state) {
1343   if (state->block_devices) {
1344     for (int i = 0; i < state->nr_block_devices; ++i)
1345       sfree(state->block_devices[i].path);
1346     sfree(state->block_devices);
1347   }
1348   state->block_devices = NULL;
1349   state->nr_block_devices = 0;
1350 }
1351
1352 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
1353                             const char *path) {
1354   struct block_device *new_ptr;
1355   int new_size =
1356       sizeof(state->block_devices[0]) * (state->nr_block_devices + 1);
1357   char *path_copy;
1358
1359   path_copy = strdup(path);
1360   if (!path_copy)
1361     return -1;
1362
1363   if (state->block_devices)
1364     new_ptr = realloc(state->block_devices, new_size);
1365   else
1366     new_ptr = malloc(new_size);
1367
1368   if (new_ptr == NULL) {
1369     sfree(path_copy);
1370     return -1;
1371   }
1372   state->block_devices = new_ptr;
1373   state->block_devices[state->nr_block_devices].dom = dom;
1374   state->block_devices[state->nr_block_devices].path = path_copy;
1375   return state->nr_block_devices++;
1376 }
1377
1378 static void free_interface_devices(struct lv_read_state *state) {
1379   if (state->interface_devices) {
1380     for (int i = 0; i < state->nr_interface_devices; ++i) {
1381       sfree(state->interface_devices[i].path);
1382       sfree(state->interface_devices[i].address);
1383       sfree(state->interface_devices[i].number);
1384     }
1385     sfree(state->interface_devices);
1386   }
1387   state->interface_devices = NULL;
1388   state->nr_interface_devices = 0;
1389 }
1390
1391 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
1392                                 const char *path, const char *address,
1393                                 unsigned int number) {
1394   struct interface_device *new_ptr;
1395   int new_size =
1396       sizeof(state->interface_devices[0]) * (state->nr_interface_devices + 1);
1397   char *path_copy, *address_copy, number_string[15];
1398
1399   if ((path == NULL) || (address == NULL))
1400     return EINVAL;
1401
1402   path_copy = strdup(path);
1403   if (!path_copy)
1404     return -1;
1405
1406   address_copy = strdup(address);
1407   if (!address_copy) {
1408     sfree(path_copy);
1409     return -1;
1410   }
1411
1412   snprintf(number_string, sizeof(number_string), "interface-%u", number);
1413
1414   if (state->interface_devices)
1415     new_ptr = realloc(state->interface_devices, new_size);
1416   else
1417     new_ptr = malloc(new_size);
1418
1419   if (new_ptr == NULL) {
1420     sfree(path_copy);
1421     sfree(address_copy);
1422     return -1;
1423   }
1424   state->interface_devices = new_ptr;
1425   state->interface_devices[state->nr_interface_devices].dom = dom;
1426   state->interface_devices[state->nr_interface_devices].path = path_copy;
1427   state->interface_devices[state->nr_interface_devices].address = address_copy;
1428   state->interface_devices[state->nr_interface_devices].number =
1429       strdup(number_string);
1430   return state->nr_interface_devices++;
1431 }
1432
1433 static int ignore_device_match(ignorelist_t *il, const char *domname,
1434                                const char *devpath) {
1435   char *name;
1436   int n, r;
1437
1438   if ((domname == NULL) || (devpath == NULL))
1439     return 0;
1440
1441   n = sizeof(char) * (strlen(domname) + strlen(devpath) + 2);
1442   name = malloc(n);
1443   if (name == NULL) {
1444     ERROR(PLUGIN_NAME " plugin: malloc failed.");
1445     return 0;
1446   }
1447   ssnprintf(name, n, "%s:%s", domname, devpath);
1448   r = ignorelist_match(il, name);
1449   sfree(name);
1450   return r;
1451 }
1452
1453 static int lv_shutdown(void) {
1454   for (int i = 0; i < nr_instances; ++i) {
1455     lv_fini_instance(i);
1456   }
1457
1458   lv_disconnect();
1459
1460   ignorelist_free(il_domains);
1461   il_domains = NULL;
1462   ignorelist_free(il_block_devices);
1463   il_block_devices = NULL;
1464   ignorelist_free(il_interface_devices);
1465   il_interface_devices = NULL;
1466
1467   return 0;
1468 }
1469
1470 void module_register(void) {
1471   plugin_register_config(PLUGIN_NAME, lv_config, config_keys, NR_CONFIG_KEYS);
1472   plugin_register_init(PLUGIN_NAME, lv_init);
1473   plugin_register_shutdown(PLUGIN_NAME, lv_shutdown);
1474 }