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