Merge branch 'collectd-5.7'
[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 static const char *config_keys[] = {"Connection",
41
42                                     "RefreshInterval",
43
44                                     "Domain",
45                                     "BlockDevice",
46                                     "BlockDeviceFormat",
47                                     "BlockDeviceFormatBasename",
48                                     "InterfaceDevice",
49                                     "IgnoreSelected",
50
51                                     "HostnameFormat",
52                                     "InterfaceFormat",
53
54                                     "PluginInstanceFormat",
55
56                                     "Instances",
57
58                                     NULL};
59 #define NR_CONFIG_KEYS ((sizeof config_keys / sizeof config_keys[0]) - 1)
60
61 /* Connection. */
62 static virConnectPtr conn = 0;
63 static char *conn_string = NULL;
64 static c_complain_t conn_complain = C_COMPLAIN_INIT_STATIC;
65
66 /* Seconds between list refreshes, 0 disables completely. */
67 static int interval = 60;
68
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;
75
76 static int ignore_device_match(ignorelist_t *, const char *domname,
77                                const char *devpath);
78
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 };
84
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 };
92
93 struct lv_read_state {
94   /* Actual list of domains found on last refresh. */
95   virDomainPtr *domains;
96   int nr_domains;
97
98   struct block_device *block_devices;
99   int nr_block_devices;
100
101   struct interface_device *interface_devices;
102   int nr_interface_devices;
103 };
104
105 static void free_domains(struct lv_read_state *state);
106 static int add_domain(struct lv_read_state *state, virDomainPtr dom);
107
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);
111
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);
116
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"
120
121 #define BUFFER_MAX_LEN 256
122 #define PARTITION_TAG_MAX_LEN 32
123
124 struct lv_read_instance {
125   struct lv_read_state read_state;
126   char tag[PARTITION_TAG_MAX_LEN];
127   size_t id;
128 };
129
130 struct lv_user_data {
131   struct lv_read_instance inst;
132   user_data_t ud;
133 };
134
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];
139
140 /* HostnameFormat. */
141 #define HF_MAX_FIELDS 3
142
143 enum hf_field { hf_none = 0, hf_hostname, hf_name, hf_uuid };
144
145 static enum hf_field hostname_format[HF_MAX_FIELDS] = {hf_name};
146
147 /* PluginInstanceFormat */
148 #define PLGINST_MAX_FIELDS 2
149
150 enum plginst_field { plginst_none = 0, plginst_name, plginst_uuid };
151
152 static enum plginst_field plugin_instance_format[PLGINST_MAX_FIELDS] = {
153     plginst_none};
154
155 /* BlockDeviceFormat */
156 enum bd_field { target, source };
157
158 /* InterfaceFormat. */
159 enum if_field { if_address, if_name, if_number };
160
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;
165
166 /* Time that we last refreshed. */
167 static time_t last_refresh = (time_t)0;
168
169 static int refresh_lists(struct lv_read_instance *inst);
170
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)
179
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];
184
185   sstrncpy(vl->plugin, PLUGIN_NAME, sizeof(vl->plugin));
186
187   vl->host[0] = '\0';
188
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;
193
194     n = DATA_MAX_NAME_LEN - strlen(vl->host) - 2;
195
196     if (i > 0 && n >= 1) {
197       strncat(vl->host, ":", 1);
198       n--;
199     }
200
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   }
218
219   vl->host[sizeof(vl->host) - 1] = '\0';
220
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;
225
226     n = sizeof(vl->plugin_instance) - strlen(vl->plugin_instance) - 2;
227
228     if (i > 0 && n >= 1) {
229       strncat(vl->plugin_instance, ":", 1);
230       n--;
231     }
232
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   }
247
248   vl->plugin_instance[sizeof(vl->plugin_instance) - 1] = '\0';
249
250 } /* void init_value_list */
251
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);
257
258   vl.values = values;
259   vl.values_len = values_len;
260
261   sstrncpy(vl.type, type, sizeof(vl.type));
262   if (type_instance != NULL)
263     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
264
265   plugin_dispatch_values(&vl);
266 }
267
268 static void memory_submit(gauge_t value, virDomainPtr dom) {
269   submit(dom, "memory", "total", &(value_t){.gauge = value}, 1);
270 }
271
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"};
277
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   }
282
283   submit(dom, "memory", tags[tag_index], &(value_t){.gauge = value}, 1);
284 }
285
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 }
290
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];
294
295   ssnprintf(type_instance, sizeof(type_instance), "%d", vcpu_nr);
296
297   submit(dom, type, type_instance, &(value_t){.derive = value}, 1);
298 }
299
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   };
305
306   submit(dom, type, devname, values, STATIC_ARRAY_SIZE(values));
307 } /* void submit_derive2 */
308
309 static int lv_config(const char *key, const char *value) {
310   if (virInitialize() != 0)
311     return 1;
312
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);
319
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   }
330
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   }
338
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   }
349
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   }
370
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   }
383
384   if (strcasecmp(key, "HostnameFormat") == 0) {
385     char *value_copy;
386     char *fields[HF_MAX_FIELDS];
387     int n;
388
389     value_copy = strdup(value);
390     if (value_copy == NULL) {
391       ERROR(PLUGIN_NAME " plugin: strdup failed.");
392       return -1;
393     }
394
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     }
401
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);
417
418     for (int i = n; i < HF_MAX_FIELDS; ++i)
419       hostname_format[i] = hf_none;
420
421     return 0;
422   }
423
424   if (strcasecmp(key, "PluginInstanceFormat") == 0) {
425     char *value_copy;
426     char *fields[PLGINST_MAX_FIELDS];
427     int n;
428
429     value_copy = strdup(value);
430     if (value_copy == NULL) {
431       ERROR(PLUGIN_NAME " plugin: strdup failed.");
432       return -1;
433     }
434
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     }
441
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);
458
459     for (int i = n; i < PLGINST_MAX_FIELDS; ++i)
460       plugin_instance_format[i] = plginst_none;
461
462     return 0;
463   }
464
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   }
478
479   if (strcasecmp(key, "Instances") == 0) {
480     char *eptr = NULL;
481     double val = strtod(value, &eptr);
482
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     }
497
498     nr_instances = (int)val;
499     DEBUG(PLUGIN_NAME " plugin: configured %i instances", nr_instances);
500     return 0;
501   }
502
503   /* Unrecognised option. */
504   return -1;
505 }
506
507 static int lv_connect(void) {
508   if (conn == NULL) {
509     /* `conn_string == NULL' is acceptable. */
510     conn = virConnectOpenReadOnly(conn_string);
511     if (conn == NULL) {
512       c_complain(LOG_ERR, &conn_complain,
513                  PLUGIN_NAME " plugin: Unable to connect: "
514                              "virConnectOpenReadOnly failed.");
515       return -1;
516     }
517   }
518   c_release(LOG_NOTICE, &conn_complain,
519             PLUGIN_NAME " plugin: Connection established.");
520   return 0;
521 }
522
523 static void lv_disconnect(void) {
524   if (conn != NULL)
525     virConnectClose(conn);
526   conn = NULL;
527   WARNING(PLUGIN_NAME " plugin: closed connection to libvirt");
528 }
529
530 static int lv_read(user_data_t *ud) {
531   time_t t;
532   struct lv_read_instance *inst = NULL;
533   struct lv_read_state *state = NULL;
534
535   if (ud->data == NULL) {
536     ERROR(PLUGIN_NAME " plugin: NULL userdata");
537     return -1;
538   }
539
540   inst = ud->data;
541   state = &inst->read_state;
542
543   if (inst->id == 0) {
544     if (lv_connect() < 0)
545       return -1;
546   }
547
548   time(&t);
549
550   /* Need to refresh domain or device lists? */
551   if ((last_refresh == (time_t)0) ||
552       ((interval > 0) && ((last_refresh + interval) <= t))) {
553     if (refresh_lists(inst) != 0) {
554       if (inst->id == 0)
555         lv_disconnect();
556       return -1;
557     }
558     last_refresh = t;
559   }
560
561 #if 0
562     for (int i = 0; i < nr_domains; ++i)
563         fprintf (stderr, "domain %s\n", virDomainGetName (domains[i]));
564     for (int i = 0; i < nr_block_devices; ++i)
565         fprintf  (stderr, "block device %d %s:%s\n",
566                   i, virDomainGetName (block_devices[i].dom),
567                   block_devices[i].path);
568     for (int i = 0; i < nr_interface_devices; ++i)
569         fprintf (stderr, "interface device %d %s:%s\n",
570                  i, virDomainGetName (interface_devices[i].dom),
571                  interface_devices[i].path);
572 #endif
573
574   /* Get CPU usage, memory, VCPU usage for each domain. */
575   for (int i = 0; i < state->nr_domains; ++i) {
576     virDomainInfo info;
577     virVcpuInfoPtr vinfo = NULL;
578     virDomainMemoryStatPtr minfo = NULL;
579     int status;
580
581     status = virDomainGetInfo(state->domains[i], &info);
582     if (status != 0) {
583       ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
584             status);
585       continue;
586     }
587
588     if (info.state != VIR_DOMAIN_RUNNING) {
589       /* only gather stats for running domains */
590       continue;
591     }
592
593     cpu_submit(info.cpuTime, state->domains[i], "virt_cpu_total");
594     memory_submit((gauge_t)info.memory * 1024, state->domains[i]);
595
596     vinfo = malloc(info.nrVirtCpu * sizeof(vinfo[0]));
597     if (vinfo == NULL) {
598       ERROR(PLUGIN_NAME " plugin: malloc failed.");
599       continue;
600     }
601
602     status = virDomainGetVcpus(state->domains[i], vinfo, info.nrVirtCpu,
603                                /* cpu map = */ NULL, /* cpu map length = */ 0);
604     if (status < 0) {
605       ERROR(PLUGIN_NAME " plugin: virDomainGetVcpus failed with status %i.",
606             status);
607       sfree(vinfo);
608       continue;
609     }
610
611     for (int j = 0; j < info.nrVirtCpu; ++j)
612       vcpu_submit(vinfo[j].cpuTime, state->domains[i], vinfo[j].number,
613                   "virt_vcpu");
614
615     sfree(vinfo);
616
617     minfo =
618         malloc(VIR_DOMAIN_MEMORY_STAT_NR * sizeof(virDomainMemoryStatStruct));
619     if (minfo == NULL) {
620       ERROR("virt plugin: malloc failed.");
621       continue;
622     }
623
624     status = virDomainMemoryStats(state->domains[i], minfo,
625                                   VIR_DOMAIN_MEMORY_STAT_NR, 0);
626
627     if (status < 0) {
628       ERROR("virt plugin: virDomainMemoryStats failed with status %i.", status);
629       sfree(minfo);
630       continue;
631     }
632
633     for (int j = 0; j < status; j++) {
634       memory_stats_submit((gauge_t)minfo[j].val * 1024, state->domains[i],
635                           minfo[j].tag);
636     }
637
638     sfree(minfo);
639   }
640
641   /* Get block device stats for each domain. */
642   for (int i = 0; i < state->nr_block_devices; ++i) {
643     struct _virDomainBlockStats stats;
644
645     if (virDomainBlockStats(state->block_devices[i].dom,
646                             state->block_devices[i].path, &stats,
647                             sizeof stats) != 0)
648       continue;
649
650     char *type_instance = NULL;
651     if (blockdevice_format_basename && blockdevice_format == source)
652       type_instance = strdup(basename(state->block_devices[i].path));
653     else
654       type_instance = strdup(state->block_devices[i].path);
655
656     if ((stats.rd_req != -1) && (stats.wr_req != -1))
657       submit_derive2("disk_ops", (derive_t)stats.rd_req, (derive_t)stats.wr_req,
658                      state->block_devices[i].dom, type_instance);
659
660     if ((stats.rd_bytes != -1) && (stats.wr_bytes != -1))
661       submit_derive2("disk_octets", (derive_t)stats.rd_bytes,
662                      (derive_t)stats.wr_bytes, state->block_devices[i].dom,
663                      type_instance);
664
665     sfree(type_instance);
666   } /* for (nr_block_devices) */
667
668   /* Get interface stats for each domain. */
669   for (int i = 0; i < state->nr_interface_devices; ++i) {
670     struct _virDomainInterfaceStats stats;
671     char *display_name = NULL;
672
673     switch (interface_format) {
674     case if_address:
675       display_name = state->interface_devices[i].address;
676       break;
677     case if_number:
678       display_name = state->interface_devices[i].number;
679       break;
680     case if_name:
681     default:
682       display_name = state->interface_devices[i].path;
683     }
684
685     if (virDomainInterfaceStats(state->interface_devices[i].dom,
686                                 state->interface_devices[i].path, &stats,
687                                 sizeof stats) != 0)
688       continue;
689
690     if ((stats.rx_bytes != -1) && (stats.tx_bytes != -1))
691       submit_derive2("if_octets", (derive_t)stats.rx_bytes,
692                      (derive_t)stats.tx_bytes, state->interface_devices[i].dom,
693                      display_name);
694
695     if ((stats.rx_packets != -1) && (stats.tx_packets != -1))
696       submit_derive2("if_packets", (derive_t)stats.rx_packets,
697                      (derive_t)stats.tx_packets,
698                      state->interface_devices[i].dom, display_name);
699
700     if ((stats.rx_errs != -1) && (stats.tx_errs != -1))
701       submit_derive2("if_errors", (derive_t)stats.rx_errs,
702                      (derive_t)stats.tx_errs, state->interface_devices[i].dom,
703                      display_name);
704
705     if ((stats.rx_drop != -1) && (stats.tx_drop != -1))
706       submit_derive2("if_dropped", (derive_t)stats.rx_drop,
707                      (derive_t)stats.tx_drop, state->interface_devices[i].dom,
708                      display_name);
709   } /* for (nr_interface_devices) */
710
711   return 0;
712 }
713
714 static int lv_init_instance(size_t i, plugin_read_cb callback) {
715   struct lv_user_data *lv_ud = &(lv_read_user_data[i]);
716   struct lv_read_instance *inst = &(lv_ud->inst);
717
718   memset(lv_ud, 0, sizeof(*lv_ud));
719
720   ssnprintf(inst->tag, sizeof(inst->tag), "%s-%zu", PLUGIN_NAME, i);
721   inst->id = i;
722
723   user_data_t *ud = &(lv_ud->ud);
724   ud->data = inst;
725   ud->free_func = NULL;
726
727   INFO(PLUGIN_NAME " plugin: reader %s initialized", inst->tag);
728   return plugin_register_complex_read(NULL, inst->tag, callback, 0, ud);
729 }
730
731 static void lv_clean_read_state(struct lv_read_state *state) {
732   free_block_devices(state);
733   free_interface_devices(state);
734   free_domains(state);
735 }
736
737 static void lv_fini_instance(size_t i) {
738   struct lv_read_instance *inst = &(lv_read_user_data[i].inst);
739   struct lv_read_state *state = &(inst->read_state);
740
741   lv_clean_read_state(state);
742   INFO(PLUGIN_NAME " plugin: reader %s finalized", inst->tag);
743 }
744
745 static int lv_init(void) {
746   if (virInitialize() != 0)
747     return -1;
748
749   if (lv_connect() != 0)
750     return -1;
751
752   DEBUG(PLUGIN_NAME " plugin: starting %i instances", nr_instances);
753
754   for (int i = 0; i < nr_instances; ++i)
755     lv_init_instance(i, lv_read);
756
757   return 0;
758 }
759
760 /*
761  * returns 0 on success and <0 on error
762  */
763 static int lv_domain_get_tag(xmlXPathContextPtr xpath_ctx, const char *dom_name,
764                              char *dom_tag) {
765   char xpath_str[BUFFER_MAX_LEN] = {'\0'};
766   xmlXPathObjectPtr xpath_obj = NULL;
767   xmlNodePtr xml_node = NULL;
768   int ret = -1;
769   int err;
770
771   err = xmlXPathRegisterNs(xpath_ctx,
772                            (const xmlChar *)METADATA_VM_PARTITION_PREFIX,
773                            (const xmlChar *)METADATA_VM_PARTITION_URI);
774   if (err) {
775     ERROR(PLUGIN_NAME " plugin: xmlXpathRegisterNs(%s, %s) failed on domain %s",
776           METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_URI, dom_name);
777     goto done;
778   }
779
780   ssnprintf(xpath_str, sizeof(xpath_str), "/domain/metadata/%s:%s/text()",
781             METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_ELEMENT);
782   xpath_obj = xmlXPathEvalExpression((xmlChar *)xpath_str, xpath_ctx);
783   if (xpath_obj == NULL) {
784     ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) failed on domain %s",
785           xpath_str, dom_name);
786     goto done;
787   }
788
789   if (xpath_obj->type != XPATH_NODESET) {
790     ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) unexpected return type %d "
791                       "(wanted %d) on domain %s",
792           xpath_str, xpath_obj->type, XPATH_NODESET, dom_name);
793     goto done;
794   }
795
796   /*
797    * from now on there is no real error, it's ok if a domain
798    * doesn't have the metadata partition tag.
799    */
800   ret = 0;
801   if (xpath_obj->nodesetval == NULL || xpath_obj->nodesetval->nodeNr != 1) {
802     DEBUG(PLUGIN_NAME " plugin: xmlXPathEval(%s) return nodeset size=%i "
803                       "expected=1 on domain %s",
804           xpath_str,
805           (xpath_obj->nodesetval == NULL) ? 0 : xpath_obj->nodesetval->nodeNr,
806           dom_name);
807   } else {
808     xml_node = xpath_obj->nodesetval->nodeTab[0];
809     sstrncpy(dom_tag, (const char *)xml_node->content, PARTITION_TAG_MAX_LEN);
810   }
811
812 done:
813   /* deregister to clean up */
814   err = xmlXPathRegisterNs(xpath_ctx,
815                            (const xmlChar *)METADATA_VM_PARTITION_PREFIX, NULL);
816   if (err) {
817     /* we can't really recover here */
818     ERROR(PLUGIN_NAME
819           " plugin: deregistration of namespace %s failed for domain %s",
820           METADATA_VM_PARTITION_PREFIX, dom_name);
821   }
822   if (xpath_obj)
823     xmlXPathFreeObject(xpath_obj);
824
825   return ret;
826 }
827
828 static int is_known_tag(const char *dom_tag) {
829   for (int i = 0; i < nr_instances; ++i)
830     if (!strcmp(dom_tag, lv_read_user_data[i].inst.tag))
831       return 1;
832   return 0;
833 }
834
835 static int lv_instance_include_domain(struct lv_read_instance *inst,
836                                       const char *dom_name,
837                                       const char *dom_tag) {
838   if ((dom_tag[0] != '\0') && (strcmp(dom_tag, inst->tag) == 0))
839     return 1;
840
841   /* instance#0 will always be there, so it is in charge of extra duties */
842   if (inst->id == 0) {
843     if (dom_tag[0] == '\0' || !is_known_tag(dom_tag)) {
844       DEBUG(PLUGIN_NAME " plugin#%s: refreshing domain %s "
845                         "with unknown tag '%s'",
846             inst->tag, dom_name, dom_tag);
847       return 1;
848     }
849   }
850
851   return 0;
852 }
853
854 static int refresh_lists(struct lv_read_instance *inst) {
855   struct lv_read_state *state = &inst->read_state;
856   int n;
857
858   n = virConnectNumOfDomains(conn);
859   if (n < 0) {
860     VIRT_ERROR(conn, "reading number of domains");
861     return -1;
862   }
863
864   lv_clean_read_state(state);
865
866   if (n > 0) {
867     int *domids;
868
869     /* Get list of domains. */
870     domids = malloc(sizeof(*domids) * n);
871     if (domids == NULL) {
872       ERROR(PLUGIN_NAME " plugin: malloc failed.");
873       return -1;
874     }
875
876     n = virConnectListDomains(conn, domids, n);
877     if (n < 0) {
878       VIRT_ERROR(conn, "reading list of domains");
879       sfree(domids);
880       return -1;
881     }
882
883     /* Fetch each domain and add it to the list, unless ignore. */
884     for (int i = 0; i < n; ++i) {
885       virDomainPtr dom = NULL;
886       const char *name;
887       char *xml = NULL;
888       xmlDocPtr xml_doc = NULL;
889       xmlXPathContextPtr xpath_ctx = NULL;
890       xmlXPathObjectPtr xpath_obj = NULL;
891       char tag[PARTITION_TAG_MAX_LEN] = {'\0'};
892
893       dom = virDomainLookupByID(conn, domids[i]);
894       if (dom == NULL) {
895         VIRT_ERROR(conn, "virDomainLookupByID");
896         /* Could be that the domain went away -- ignore it anyway. */
897         continue;
898       }
899
900       name = virDomainGetName(dom);
901       if (name == NULL) {
902         VIRT_ERROR(conn, "virDomainGetName");
903         goto cont;
904       }
905
906       if (il_domains && ignorelist_match(il_domains, name) != 0)
907         goto cont;
908
909       /* Get a list of devices for this domain. */
910       xml = virDomainGetXMLDesc(dom, 0);
911       if (!xml) {
912         VIRT_ERROR(conn, "virDomainGetXMLDesc");
913         goto cont;
914       }
915
916       /* Yuck, XML.  Parse out the devices. */
917       xml_doc = xmlReadDoc((xmlChar *)xml, NULL, NULL, XML_PARSE_NONET);
918       if (xml_doc == NULL) {
919         VIRT_ERROR(conn, "xmlReadDoc");
920         goto cont;
921       }
922
923       xpath_ctx = xmlXPathNewContext(xml_doc);
924
925       if (lv_domain_get_tag(xpath_ctx, name, tag) < 0) {
926         ERROR(PLUGIN_NAME " plugin: lv_domain_get_tag failed.");
927         goto cont;
928       }
929
930       if (!lv_instance_include_domain(inst, name, tag))
931         goto cont;
932
933       if (add_domain(state, dom) < 0) {
934         ERROR(PLUGIN_NAME " plugin: malloc failed.");
935         goto cont;
936       }
937
938       /* Block devices. */
939       const char *bd_xmlpath = "/domain/devices/disk/target[@dev]";
940       if (blockdevice_format == source)
941         bd_xmlpath = "/domain/devices/disk/source[@dev]";
942       xpath_obj = xmlXPathEval((const xmlChar *)bd_xmlpath, xpath_ctx);
943
944       if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
945           xpath_obj->nodesetval == NULL)
946         goto cont;
947
948       for (int j = 0; j < xpath_obj->nodesetval->nodeNr; ++j) {
949         xmlNodePtr node;
950         char *path = NULL;
951
952         node = xpath_obj->nodesetval->nodeTab[j];
953         if (!node)
954           continue;
955         path = (char *)xmlGetProp(node, (xmlChar *)"dev");
956         if (!path)
957           continue;
958
959         if (il_block_devices &&
960             ignore_device_match(il_block_devices, name, path) != 0)
961           goto cont2;
962
963         add_block_device(state, dom, path);
964       cont2:
965         if (path)
966           xmlFree(path);
967       }
968       xmlXPathFreeObject(xpath_obj);
969
970       /* Network interfaces. */
971       xpath_obj = xmlXPathEval(
972           (xmlChar *)"/domain/devices/interface[target[@dev]]", xpath_ctx);
973       if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
974           xpath_obj->nodesetval == NULL)
975         goto cont;
976
977       xmlNodeSetPtr xml_interfaces = xpath_obj->nodesetval;
978
979       for (int j = 0; j < xml_interfaces->nodeNr; ++j) {
980         char *path = NULL;
981         char *address = NULL;
982         xmlNodePtr xml_interface;
983
984         xml_interface = xml_interfaces->nodeTab[j];
985         if (!xml_interface)
986           continue;
987
988         for (xmlNodePtr child = xml_interface->children; child;
989              child = child->next) {
990           if (child->type != XML_ELEMENT_NODE)
991             continue;
992
993           if (xmlStrEqual(child->name, (const xmlChar *)"target")) {
994             path = (char *)xmlGetProp(child, (const xmlChar *)"dev");
995             if (!path)
996               continue;
997           } else if (xmlStrEqual(child->name, (const xmlChar *)"mac")) {
998             address = (char *)xmlGetProp(child, (const xmlChar *)"address");
999             if (!address)
1000               continue;
1001           }
1002         }
1003
1004         if (il_interface_devices &&
1005             (ignore_device_match(il_interface_devices, name, path) != 0 ||
1006              ignore_device_match(il_interface_devices, name, address) != 0))
1007           goto cont3;
1008
1009         add_interface_device(state, dom, path, address, j + 1);
1010       cont3:
1011         if (path)
1012           xmlFree(path);
1013         if (address)
1014           xmlFree(address);
1015       }
1016
1017     cont:
1018       if (xpath_obj)
1019         xmlXPathFreeObject(xpath_obj);
1020       if (xpath_ctx)
1021         xmlXPathFreeContext(xpath_ctx);
1022       if (xml_doc)
1023         xmlFreeDoc(xml_doc);
1024       sfree(xml);
1025     }
1026
1027     sfree(domids);
1028   }
1029
1030   DEBUG(PLUGIN_NAME " plugin#%s: refreshing"
1031                     " domains=%i block_devices=%i iface_devices=%i",
1032         inst->tag, state->nr_domains, state->nr_block_devices,
1033         state->nr_interface_devices);
1034
1035   return 0;
1036 }
1037
1038 static void free_domains(struct lv_read_state *state) {
1039   if (state->domains) {
1040     for (int i = 0; i < state->nr_domains; ++i)
1041       virDomainFree(state->domains[i]);
1042     sfree(state->domains);
1043   }
1044   state->domains = NULL;
1045   state->nr_domains = 0;
1046 }
1047
1048 static int add_domain(struct lv_read_state *state, virDomainPtr dom) {
1049   virDomainPtr *new_ptr;
1050   int new_size = sizeof(state->domains[0]) * (state->nr_domains + 1);
1051
1052   if (state->domains)
1053     new_ptr = realloc(state->domains, new_size);
1054   else
1055     new_ptr = malloc(new_size);
1056
1057   if (new_ptr == NULL)
1058     return -1;
1059
1060   state->domains = new_ptr;
1061   state->domains[state->nr_domains] = dom;
1062   return state->nr_domains++;
1063 }
1064
1065 static void free_block_devices(struct lv_read_state *state) {
1066   if (state->block_devices) {
1067     for (int i = 0; i < state->nr_block_devices; ++i)
1068       sfree(state->block_devices[i].path);
1069     sfree(state->block_devices);
1070   }
1071   state->block_devices = NULL;
1072   state->nr_block_devices = 0;
1073 }
1074
1075 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
1076                             const char *path) {
1077   struct block_device *new_ptr;
1078   int new_size =
1079       sizeof(state->block_devices[0]) * (state->nr_block_devices + 1);
1080   char *path_copy;
1081
1082   path_copy = strdup(path);
1083   if (!path_copy)
1084     return -1;
1085
1086   if (state->block_devices)
1087     new_ptr = realloc(state->block_devices, new_size);
1088   else
1089     new_ptr = malloc(new_size);
1090
1091   if (new_ptr == NULL) {
1092     sfree(path_copy);
1093     return -1;
1094   }
1095   state->block_devices = new_ptr;
1096   state->block_devices[state->nr_block_devices].dom = dom;
1097   state->block_devices[state->nr_block_devices].path = path_copy;
1098   return state->nr_block_devices++;
1099 }
1100
1101 static void free_interface_devices(struct lv_read_state *state) {
1102   if (state->interface_devices) {
1103     for (int i = 0; i < state->nr_interface_devices; ++i) {
1104       sfree(state->interface_devices[i].path);
1105       sfree(state->interface_devices[i].address);
1106       sfree(state->interface_devices[i].number);
1107     }
1108     sfree(state->interface_devices);
1109   }
1110   state->interface_devices = NULL;
1111   state->nr_interface_devices = 0;
1112 }
1113
1114 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
1115                                 const char *path, const char *address,
1116                                 unsigned int number) {
1117   struct interface_device *new_ptr;
1118   int new_size =
1119       sizeof(state->interface_devices[0]) * (state->nr_interface_devices + 1);
1120   char *path_copy, *address_copy, number_string[15];
1121
1122   if ((path == NULL) || (address == NULL))
1123     return EINVAL;
1124
1125   path_copy = strdup(path);
1126   if (!path_copy)
1127     return -1;
1128
1129   address_copy = strdup(address);
1130   if (!address_copy) {
1131     sfree(path_copy);
1132     return -1;
1133   }
1134
1135   snprintf(number_string, sizeof(number_string), "interface-%u", number);
1136
1137   if (state->interface_devices)
1138     new_ptr = realloc(state->interface_devices, new_size);
1139   else
1140     new_ptr = malloc(new_size);
1141
1142   if (new_ptr == NULL) {
1143     sfree(path_copy);
1144     sfree(address_copy);
1145     return -1;
1146   }
1147   state->interface_devices = new_ptr;
1148   state->interface_devices[state->nr_interface_devices].dom = dom;
1149   state->interface_devices[state->nr_interface_devices].path = path_copy;
1150   state->interface_devices[state->nr_interface_devices].address = address_copy;
1151   state->interface_devices[state->nr_interface_devices].number =
1152       strdup(number_string);
1153   return state->nr_interface_devices++;
1154 }
1155
1156 static int ignore_device_match(ignorelist_t *il, const char *domname,
1157                                const char *devpath) {
1158   char *name;
1159   int n, r;
1160
1161   if ((domname == NULL) || (devpath == NULL))
1162     return 0;
1163
1164   n = sizeof(char) * (strlen(domname) + strlen(devpath) + 2);
1165   name = malloc(n);
1166   if (name == NULL) {
1167     ERROR(PLUGIN_NAME " plugin: malloc failed.");
1168     return 0;
1169   }
1170   ssnprintf(name, n, "%s:%s", domname, devpath);
1171   r = ignorelist_match(il, name);
1172   sfree(name);
1173   return r;
1174 }
1175
1176 static int lv_shutdown(void) {
1177   for (int i = 0; i < nr_instances; ++i) {
1178     lv_fini_instance(i);
1179   }
1180
1181   lv_disconnect();
1182
1183   ignorelist_free(il_domains);
1184   il_domains = NULL;
1185   ignorelist_free(il_block_devices);
1186   il_block_devices = NULL;
1187   ignorelist_free(il_interface_devices);
1188   il_interface_devices = NULL;
1189
1190   return 0;
1191 }
1192
1193 void module_register(void) {
1194   plugin_register_config(PLUGIN_NAME, lv_config, config_keys, NR_CONFIG_KEYS);
1195   plugin_register_init(PLUGIN_NAME, lv_init);
1196   plugin_register_shutdown(PLUGIN_NAME, lv_shutdown);
1197 }