virt plugin: Report disk flush information
[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   char flush_type_instance[DATA_MAX_NAME_LEN];
377
378   ssnprintf(flush_type_instance, sizeof(flush_type_instance), "flush-%s",
379             type_instance);
380
381   if ((binfo->bi.rd_req != -1) && (binfo->bi.wr_req != -1))
382     submit_derive2("disk_ops", (derive_t)binfo->bi.rd_req,
383                    (derive_t)binfo->bi.wr_req, dom, type_instance);
384
385   if ((binfo->bi.rd_bytes != -1) && (binfo->bi.wr_bytes != -1))
386     submit_derive2("disk_octets", (derive_t)binfo->bi.rd_bytes,
387                    (derive_t)binfo->bi.wr_bytes, dom, type_instance);
388
389   if ((binfo->rd_total_times != -1) && (binfo->wr_total_times != -1))
390     submit_derive2("disk_time", (derive_t)binfo->rd_total_times,
391                    (derive_t)binfo->wr_total_times, dom, type_instance);
392
393   if (binfo->fl_req != -1)
394     submit(dom, "total_requests", flush_type_instance,
395            &(value_t){.derive = (derive_t)binfo->fl_req}, 1);
396   if (binfo->fl_total_times != -1) {
397     derive_t value = binfo->fl_total_times / 1000; // ns -> ms
398     submit(dom, "total_time_in_ms", flush_type_instance,
399            &(value_t){.derive = value}, 1);
400   }
401 }
402
403 static int lv_config(const char *key, const char *value) {
404   if (virInitialize() != 0)
405     return 1;
406
407   if (il_domains == NULL)
408     il_domains = ignorelist_create(1);
409   if (il_block_devices == NULL)
410     il_block_devices = ignorelist_create(1);
411   if (il_interface_devices == NULL)
412     il_interface_devices = ignorelist_create(1);
413
414   if (strcasecmp(key, "Connection") == 0) {
415     char *tmp = strdup(value);
416     if (tmp == NULL) {
417       ERROR(PLUGIN_NAME " plugin: Connection strdup failed.");
418       return 1;
419     }
420     sfree(conn_string);
421     conn_string = tmp;
422     return 0;
423   }
424
425   if (strcasecmp(key, "RefreshInterval") == 0) {
426     char *eptr = NULL;
427     interval = strtol(value, &eptr, 10);
428     if (eptr == NULL || *eptr != '\0')
429       return 1;
430     return 0;
431   }
432
433   if (strcasecmp(key, "Domain") == 0) {
434     if (ignorelist_add(il_domains, value))
435       return 1;
436     return 0;
437   }
438   if (strcasecmp(key, "BlockDevice") == 0) {
439     if (ignorelist_add(il_block_devices, value))
440       return 1;
441     return 0;
442   }
443
444   if (strcasecmp(key, "BlockDeviceFormat") == 0) {
445     if (strcasecmp(value, "target") == 0)
446       blockdevice_format = target;
447     else if (strcasecmp(value, "source") == 0)
448       blockdevice_format = source;
449     else {
450       ERROR(PLUGIN_NAME " plugin: unknown BlockDeviceFormat: %s", value);
451       return -1;
452     }
453     return 0;
454   }
455   if (strcasecmp(key, "BlockDeviceFormatBasename") == 0) {
456     blockdevice_format_basename = IS_TRUE(value);
457     return 0;
458   }
459   if (strcasecmp(key, "InterfaceDevice") == 0) {
460     if (ignorelist_add(il_interface_devices, value))
461       return 1;
462     return 0;
463   }
464
465   if (strcasecmp(key, "IgnoreSelected") == 0) {
466     if (IS_TRUE(value)) {
467       ignorelist_set_invert(il_domains, 0);
468       ignorelist_set_invert(il_block_devices, 0);
469       ignorelist_set_invert(il_interface_devices, 0);
470     } else {
471       ignorelist_set_invert(il_domains, 1);
472       ignorelist_set_invert(il_block_devices, 1);
473       ignorelist_set_invert(il_interface_devices, 1);
474     }
475     return 0;
476   }
477
478   if (strcasecmp(key, "HostnameFormat") == 0) {
479     char *value_copy;
480     char *fields[HF_MAX_FIELDS];
481     int n;
482
483     value_copy = strdup(value);
484     if (value_copy == NULL) {
485       ERROR(PLUGIN_NAME " plugin: strdup failed.");
486       return -1;
487     }
488
489     n = strsplit(value_copy, fields, HF_MAX_FIELDS);
490     if (n < 1) {
491       sfree(value_copy);
492       ERROR(PLUGIN_NAME " plugin: HostnameFormat: no fields");
493       return -1;
494     }
495
496     for (int i = 0; i < n; ++i) {
497       if (strcasecmp(fields[i], "hostname") == 0)
498         hostname_format[i] = hf_hostname;
499       else if (strcasecmp(fields[i], "name") == 0)
500         hostname_format[i] = hf_name;
501       else if (strcasecmp(fields[i], "uuid") == 0)
502         hostname_format[i] = hf_uuid;
503       else {
504         ERROR(PLUGIN_NAME " plugin: unknown HostnameFormat field: %s",
505               fields[i]);
506         sfree(value_copy);
507         return -1;
508       }
509     }
510     sfree(value_copy);
511
512     for (int i = n; i < HF_MAX_FIELDS; ++i)
513       hostname_format[i] = hf_none;
514
515     return 0;
516   }
517
518   if (strcasecmp(key, "PluginInstanceFormat") == 0) {
519     char *value_copy;
520     char *fields[PLGINST_MAX_FIELDS];
521     int n;
522
523     value_copy = strdup(value);
524     if (value_copy == NULL) {
525       ERROR(PLUGIN_NAME " plugin: strdup failed.");
526       return -1;
527     }
528
529     n = strsplit(value_copy, fields, PLGINST_MAX_FIELDS);
530     if (n < 1) {
531       sfree(value_copy);
532       ERROR(PLUGIN_NAME " plugin: PluginInstanceFormat: no fields");
533       return -1;
534     }
535
536     for (int i = 0; i < n; ++i) {
537       if (strcasecmp(fields[i], "none") == 0) {
538         plugin_instance_format[i] = plginst_none;
539         break;
540       } else if (strcasecmp(fields[i], "name") == 0)
541         plugin_instance_format[i] = plginst_name;
542       else if (strcasecmp(fields[i], "uuid") == 0)
543         plugin_instance_format[i] = plginst_uuid;
544       else {
545         ERROR(PLUGIN_NAME " plugin: unknown PluginInstanceFormat field: %s",
546               fields[i]);
547         sfree(value_copy);
548         return -1;
549       }
550     }
551     sfree(value_copy);
552
553     for (int i = n; i < PLGINST_MAX_FIELDS; ++i)
554       plugin_instance_format[i] = plginst_none;
555
556     return 0;
557   }
558
559   if (strcasecmp(key, "InterfaceFormat") == 0) {
560     if (strcasecmp(value, "name") == 0)
561       interface_format = if_name;
562     else if (strcasecmp(value, "address") == 0)
563       interface_format = if_address;
564     else if (strcasecmp(value, "number") == 0)
565       interface_format = if_number;
566     else {
567       ERROR(PLUGIN_NAME " plugin: unknown InterfaceFormat: %s", value);
568       return -1;
569     }
570     return 0;
571   }
572
573   if (strcasecmp(key, "Instances") == 0) {
574     char *eptr = NULL;
575     double val = strtod(value, &eptr);
576
577     if (*eptr != '\0') {
578       ERROR(PLUGIN_NAME " plugin: Invalid value for Instances = '%s'", value);
579       return 1;
580     }
581     if (val <= 0) {
582       ERROR(PLUGIN_NAME " plugin: Instances <= 0 makes no sense.");
583       return 1;
584     }
585     if (val > NR_INSTANCES_MAX) {
586       ERROR(PLUGIN_NAME " plugin: Instances=%f > NR_INSTANCES_MAX=%i"
587                         " use a lower setting or recompile the plugin.",
588             val, NR_INSTANCES_MAX);
589       return 1;
590     }
591
592     nr_instances = (int)val;
593     DEBUG(PLUGIN_NAME " plugin: configured %i instances", nr_instances);
594     return 0;
595   }
596
597   /* Unrecognised option. */
598   return -1;
599 }
600
601 static int lv_connect(void) {
602   if (conn == NULL) {
603     /* `conn_string == NULL' is acceptable. */
604     conn = virConnectOpenReadOnly(conn_string);
605     if (conn == NULL) {
606       c_complain(LOG_ERR, &conn_complain,
607                  PLUGIN_NAME " plugin: Unable to connect: "
608                              "virConnectOpenReadOnly failed.");
609       return -1;
610     }
611   }
612   c_release(LOG_NOTICE, &conn_complain,
613             PLUGIN_NAME " plugin: Connection established.");
614   return 0;
615 }
616
617 static void lv_disconnect(void) {
618   if (conn != NULL)
619     virConnectClose(conn);
620   conn = NULL;
621   WARNING(PLUGIN_NAME " plugin: closed connection to libvirt");
622 }
623
624 static int lv_domain_block_info(virDomainPtr dom, const char *path,
625                                 struct lv_block_info *binfo) {
626 #ifdef HAVE_BLOCK_STATS_FLAGS
627   virTypedParameterPtr params = NULL;
628   int nparams = 0;
629   int rc = -1;
630   int ret;
631
632   ret = virDomainBlockStatsFlags(dom, path, NULL, &nparams, 0);
633   if (ret < 0 || nparams == 0) {
634     VIRT_ERROR(conn, "getting the disk params count");
635     return -1;
636   }
637
638   params = calloc(nparams, sizeof(virTypedParameter));
639   if (params == NULL) {
640     ERROR("virt plugin: alloc(%i) for block=%s parameters failed.", nparams,
641           path);
642     return -1;
643   }
644   ret = virDomainBlockStatsFlags(dom, path, params, &nparams, 0);
645   if (ret < 0) {
646     VIRT_ERROR(conn, "getting the disk params values");
647     goto done;
648   }
649
650   rc = get_block_info(binfo, params, nparams);
651
652 done:
653   virTypedParamsFree(params, nparams);
654   return rc;
655 #else
656   return virDomainBlockStats(dom, path, &(binfo->bi), sizeof(binfo->bi));
657 #endif /* HAVE_BLOCK_STATS_FLAGS */
658 }
659
660 static int lv_read(user_data_t *ud) {
661   time_t t;
662   struct lv_read_instance *inst = NULL;
663   struct lv_read_state *state = NULL;
664
665   if (ud->data == NULL) {
666     ERROR(PLUGIN_NAME " plugin: NULL userdata");
667     return -1;
668   }
669
670   inst = ud->data;
671   state = &inst->read_state;
672
673   if (inst->id == 0) {
674     if (lv_connect() < 0)
675       return -1;
676   }
677
678   time(&t);
679
680   /* Need to refresh domain or device lists? */
681   if ((last_refresh == (time_t)0) ||
682       ((interval > 0) && ((last_refresh + interval) <= t))) {
683     if (refresh_lists(inst) != 0) {
684       if (inst->id == 0)
685         lv_disconnect();
686       return -1;
687     }
688     last_refresh = t;
689   }
690
691 #if 0
692     for (int i = 0; i < nr_domains; ++i)
693         fprintf (stderr, "domain %s\n", virDomainGetName (domains[i]));
694     for (int i = 0; i < nr_block_devices; ++i)
695         fprintf  (stderr, "block device %d %s:%s\n",
696                   i, virDomainGetName (block_devices[i].dom),
697                   block_devices[i].path);
698     for (int i = 0; i < nr_interface_devices; ++i)
699         fprintf (stderr, "interface device %d %s:%s\n",
700                  i, virDomainGetName (interface_devices[i].dom),
701                  interface_devices[i].path);
702 #endif
703
704   /* Get CPU usage, memory, VCPU usage for each domain. */
705   for (int i = 0; i < state->nr_domains; ++i) {
706     virDomainInfo info;
707     virVcpuInfoPtr vinfo = NULL;
708     virDomainMemoryStatPtr minfo = NULL;
709     int status;
710
711     status = virDomainGetInfo(state->domains[i], &info);
712     if (status != 0) {
713       ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
714             status);
715       continue;
716     }
717
718     if (info.state != VIR_DOMAIN_RUNNING) {
719       /* only gather stats for running domains */
720       continue;
721     }
722
723     cpu_submit(info.cpuTime, state->domains[i], "virt_cpu_total");
724     memory_submit((gauge_t)info.memory * 1024, state->domains[i]);
725
726     vinfo = malloc(info.nrVirtCpu * sizeof(vinfo[0]));
727     if (vinfo == NULL) {
728       ERROR(PLUGIN_NAME " plugin: malloc failed.");
729       continue;
730     }
731
732     status = virDomainGetVcpus(state->domains[i], vinfo, info.nrVirtCpu,
733                                /* cpu map = */ NULL, /* cpu map length = */ 0);
734     if (status < 0) {
735       ERROR(PLUGIN_NAME " plugin: virDomainGetVcpus failed with status %i.",
736             status);
737       sfree(vinfo);
738       continue;
739     }
740
741     for (int j = 0; j < info.nrVirtCpu; ++j)
742       vcpu_submit(vinfo[j].cpuTime, state->domains[i], vinfo[j].number,
743                   "virt_vcpu");
744
745     sfree(vinfo);
746
747     minfo =
748         malloc(VIR_DOMAIN_MEMORY_STAT_NR * sizeof(virDomainMemoryStatStruct));
749     if (minfo == NULL) {
750       ERROR("virt plugin: malloc failed.");
751       continue;
752     }
753
754     status = virDomainMemoryStats(state->domains[i], minfo,
755                                   VIR_DOMAIN_MEMORY_STAT_NR, 0);
756
757     if (status < 0) {
758       ERROR("virt plugin: virDomainMemoryStats failed with status %i.", status);
759       sfree(minfo);
760       continue;
761     }
762
763     for (int j = 0; j < status; j++) {
764       memory_stats_submit((gauge_t)minfo[j].val * 1024, state->domains[i],
765                           minfo[j].tag);
766     }
767
768     sfree(minfo);
769   }
770
771   /* Get block device stats for each domain. */
772   for (int i = 0; i < state->nr_block_devices; ++i) {
773     struct block_device *bdev = &(state->block_devices[i]);
774     struct lv_block_info binfo;
775     init_block_info(&binfo);
776
777     if (lv_domain_block_info(bdev->dom, bdev->path, &binfo) < 0)
778       continue;
779
780     char *type_instance = NULL;
781     if (blockdevice_format_basename && blockdevice_format == source)
782       type_instance = strdup(basename(bdev->path));
783     else
784       type_instance = strdup(bdev->path);
785
786     disk_submit(&binfo, bdev->dom, type_instance);
787
788     sfree(type_instance);
789   } /* for (nr_block_devices) */
790
791   /* Get interface stats for each domain. */
792   for (int i = 0; i < state->nr_interface_devices; ++i) {
793     struct _virDomainInterfaceStats stats;
794     char *display_name = NULL;
795
796     switch (interface_format) {
797     case if_address:
798       display_name = state->interface_devices[i].address;
799       break;
800     case if_number:
801       display_name = state->interface_devices[i].number;
802       break;
803     case if_name:
804     default:
805       display_name = state->interface_devices[i].path;
806     }
807
808     if (virDomainInterfaceStats(state->interface_devices[i].dom,
809                                 state->interface_devices[i].path, &stats,
810                                 sizeof stats) != 0)
811       continue;
812
813     if ((stats.rx_bytes != -1) && (stats.tx_bytes != -1))
814       submit_derive2("if_octets", (derive_t)stats.rx_bytes,
815                      (derive_t)stats.tx_bytes, state->interface_devices[i].dom,
816                      display_name);
817
818     if ((stats.rx_packets != -1) && (stats.tx_packets != -1))
819       submit_derive2("if_packets", (derive_t)stats.rx_packets,
820                      (derive_t)stats.tx_packets,
821                      state->interface_devices[i].dom, display_name);
822
823     if ((stats.rx_errs != -1) && (stats.tx_errs != -1))
824       submit_derive2("if_errors", (derive_t)stats.rx_errs,
825                      (derive_t)stats.tx_errs, state->interface_devices[i].dom,
826                      display_name);
827
828     if ((stats.rx_drop != -1) && (stats.tx_drop != -1))
829       submit_derive2("if_dropped", (derive_t)stats.rx_drop,
830                      (derive_t)stats.tx_drop, state->interface_devices[i].dom,
831                      display_name);
832   } /* for (nr_interface_devices) */
833
834   return 0;
835 }
836
837 static int lv_init_instance(size_t i, plugin_read_cb callback) {
838   struct lv_user_data *lv_ud = &(lv_read_user_data[i]);
839   struct lv_read_instance *inst = &(lv_ud->inst);
840
841   memset(lv_ud, 0, sizeof(*lv_ud));
842
843   ssnprintf(inst->tag, sizeof(inst->tag), "%s-%zu", PLUGIN_NAME, i);
844   inst->id = i;
845
846   user_data_t *ud = &(lv_ud->ud);
847   ud->data = inst;
848   ud->free_func = NULL;
849
850   INFO(PLUGIN_NAME " plugin: reader %s initialized", inst->tag);
851   return plugin_register_complex_read(NULL, inst->tag, callback, 0, ud);
852 }
853
854 static void lv_clean_read_state(struct lv_read_state *state) {
855   free_block_devices(state);
856   free_interface_devices(state);
857   free_domains(state);
858 }
859
860 static void lv_fini_instance(size_t i) {
861   struct lv_read_instance *inst = &(lv_read_user_data[i].inst);
862   struct lv_read_state *state = &(inst->read_state);
863
864   lv_clean_read_state(state);
865   INFO(PLUGIN_NAME " plugin: reader %s finalized", inst->tag);
866 }
867
868 static int lv_init(void) {
869   if (virInitialize() != 0)
870     return -1;
871
872   if (lv_connect() != 0)
873     return -1;
874
875   DEBUG(PLUGIN_NAME " plugin: starting %i instances", nr_instances);
876
877   for (int i = 0; i < nr_instances; ++i)
878     lv_init_instance(i, lv_read);
879
880   return 0;
881 }
882
883 /*
884  * returns 0 on success and <0 on error
885  */
886 static int lv_domain_get_tag(xmlXPathContextPtr xpath_ctx, const char *dom_name,
887                              char *dom_tag) {
888   char xpath_str[BUFFER_MAX_LEN] = {'\0'};
889   xmlXPathObjectPtr xpath_obj = NULL;
890   xmlNodePtr xml_node = NULL;
891   int ret = -1;
892   int err;
893
894   err = xmlXPathRegisterNs(xpath_ctx,
895                            (const xmlChar *)METADATA_VM_PARTITION_PREFIX,
896                            (const xmlChar *)METADATA_VM_PARTITION_URI);
897   if (err) {
898     ERROR(PLUGIN_NAME " plugin: xmlXpathRegisterNs(%s, %s) failed on domain %s",
899           METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_URI, dom_name);
900     goto done;
901   }
902
903   ssnprintf(xpath_str, sizeof(xpath_str), "/domain/metadata/%s:%s/text()",
904             METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_ELEMENT);
905   xpath_obj = xmlXPathEvalExpression((xmlChar *)xpath_str, xpath_ctx);
906   if (xpath_obj == NULL) {
907     ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) failed on domain %s",
908           xpath_str, dom_name);
909     goto done;
910   }
911
912   if (xpath_obj->type != XPATH_NODESET) {
913     ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) unexpected return type %d "
914                       "(wanted %d) on domain %s",
915           xpath_str, xpath_obj->type, XPATH_NODESET, dom_name);
916     goto done;
917   }
918
919   /*
920    * from now on there is no real error, it's ok if a domain
921    * doesn't have the metadata partition tag.
922    */
923   ret = 0;
924   if (xpath_obj->nodesetval == NULL || xpath_obj->nodesetval->nodeNr != 1) {
925     DEBUG(PLUGIN_NAME " plugin: xmlXPathEval(%s) return nodeset size=%i "
926                       "expected=1 on domain %s",
927           xpath_str,
928           (xpath_obj->nodesetval == NULL) ? 0 : xpath_obj->nodesetval->nodeNr,
929           dom_name);
930   } else {
931     xml_node = xpath_obj->nodesetval->nodeTab[0];
932     sstrncpy(dom_tag, (const char *)xml_node->content, PARTITION_TAG_MAX_LEN);
933   }
934
935 done:
936   /* deregister to clean up */
937   err = xmlXPathRegisterNs(xpath_ctx,
938                            (const xmlChar *)METADATA_VM_PARTITION_PREFIX, NULL);
939   if (err) {
940     /* we can't really recover here */
941     ERROR(PLUGIN_NAME
942           " plugin: deregistration of namespace %s failed for domain %s",
943           METADATA_VM_PARTITION_PREFIX, dom_name);
944   }
945   if (xpath_obj)
946     xmlXPathFreeObject(xpath_obj);
947
948   return ret;
949 }
950
951 static int is_known_tag(const char *dom_tag) {
952   for (int i = 0; i < nr_instances; ++i)
953     if (!strcmp(dom_tag, lv_read_user_data[i].inst.tag))
954       return 1;
955   return 0;
956 }
957
958 static int lv_instance_include_domain(struct lv_read_instance *inst,
959                                       const char *dom_name,
960                                       const char *dom_tag) {
961   if ((dom_tag[0] != '\0') && (strcmp(dom_tag, inst->tag) == 0))
962     return 1;
963
964   /* instance#0 will always be there, so it is in charge of extra duties */
965   if (inst->id == 0) {
966     if (dom_tag[0] == '\0' || !is_known_tag(dom_tag)) {
967       DEBUG(PLUGIN_NAME " plugin#%s: refreshing domain %s "
968                         "with unknown tag '%s'",
969             inst->tag, dom_name, dom_tag);
970       return 1;
971     }
972   }
973
974   return 0;
975 }
976
977 static int refresh_lists(struct lv_read_instance *inst) {
978   struct lv_read_state *state = &inst->read_state;
979   int n;
980
981   n = virConnectNumOfDomains(conn);
982   if (n < 0) {
983     VIRT_ERROR(conn, "reading number of domains");
984     return -1;
985   }
986
987   lv_clean_read_state(state);
988
989   if (n > 0) {
990     int *domids;
991
992     /* Get list of domains. */
993     domids = malloc(sizeof(*domids) * n);
994     if (domids == NULL) {
995       ERROR(PLUGIN_NAME " plugin: malloc failed.");
996       return -1;
997     }
998
999     n = virConnectListDomains(conn, domids, n);
1000     if (n < 0) {
1001       VIRT_ERROR(conn, "reading list of domains");
1002       sfree(domids);
1003       return -1;
1004     }
1005
1006     /* Fetch each domain and add it to the list, unless ignore. */
1007     for (int i = 0; i < n; ++i) {
1008       virDomainPtr dom = NULL;
1009       const char *name;
1010       char *xml = NULL;
1011       xmlDocPtr xml_doc = NULL;
1012       xmlXPathContextPtr xpath_ctx = NULL;
1013       xmlXPathObjectPtr xpath_obj = NULL;
1014       char tag[PARTITION_TAG_MAX_LEN] = {'\0'};
1015
1016       dom = virDomainLookupByID(conn, domids[i]);
1017       if (dom == NULL) {
1018         VIRT_ERROR(conn, "virDomainLookupByID");
1019         /* Could be that the domain went away -- ignore it anyway. */
1020         continue;
1021       }
1022
1023       name = virDomainGetName(dom);
1024       if (name == NULL) {
1025         VIRT_ERROR(conn, "virDomainGetName");
1026         goto cont;
1027       }
1028
1029       if (il_domains && ignorelist_match(il_domains, name) != 0)
1030         goto cont;
1031
1032       /* Get a list of devices for this domain. */
1033       xml = virDomainGetXMLDesc(dom, 0);
1034       if (!xml) {
1035         VIRT_ERROR(conn, "virDomainGetXMLDesc");
1036         goto cont;
1037       }
1038
1039       /* Yuck, XML.  Parse out the devices. */
1040       xml_doc = xmlReadDoc((xmlChar *)xml, NULL, NULL, XML_PARSE_NONET);
1041       if (xml_doc == NULL) {
1042         VIRT_ERROR(conn, "xmlReadDoc");
1043         goto cont;
1044       }
1045
1046       xpath_ctx = xmlXPathNewContext(xml_doc);
1047
1048       if (lv_domain_get_tag(xpath_ctx, name, tag) < 0) {
1049         ERROR(PLUGIN_NAME " plugin: lv_domain_get_tag failed.");
1050         goto cont;
1051       }
1052
1053       if (!lv_instance_include_domain(inst, name, tag))
1054         goto cont;
1055
1056       if (add_domain(state, dom) < 0) {
1057         ERROR(PLUGIN_NAME " plugin: malloc failed.");
1058         goto cont;
1059       }
1060
1061       /* Block devices. */
1062       const char *bd_xmlpath = "/domain/devices/disk/target[@dev]";
1063       if (blockdevice_format == source)
1064         bd_xmlpath = "/domain/devices/disk/source[@dev]";
1065       xpath_obj = xmlXPathEval((const xmlChar *)bd_xmlpath, xpath_ctx);
1066
1067       if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
1068           xpath_obj->nodesetval == NULL)
1069         goto cont;
1070
1071       for (int j = 0; j < xpath_obj->nodesetval->nodeNr; ++j) {
1072         xmlNodePtr node;
1073         char *path = NULL;
1074
1075         node = xpath_obj->nodesetval->nodeTab[j];
1076         if (!node)
1077           continue;
1078         path = (char *)xmlGetProp(node, (xmlChar *)"dev");
1079         if (!path)
1080           continue;
1081
1082         if (il_block_devices &&
1083             ignore_device_match(il_block_devices, name, path) != 0)
1084           goto cont2;
1085
1086         add_block_device(state, dom, path);
1087       cont2:
1088         if (path)
1089           xmlFree(path);
1090       }
1091       xmlXPathFreeObject(xpath_obj);
1092
1093       /* Network interfaces. */
1094       xpath_obj = xmlXPathEval(
1095           (xmlChar *)"/domain/devices/interface[target[@dev]]", xpath_ctx);
1096       if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
1097           xpath_obj->nodesetval == NULL)
1098         goto cont;
1099
1100       xmlNodeSetPtr xml_interfaces = xpath_obj->nodesetval;
1101
1102       for (int j = 0; j < xml_interfaces->nodeNr; ++j) {
1103         char *path = NULL;
1104         char *address = NULL;
1105         xmlNodePtr xml_interface;
1106
1107         xml_interface = xml_interfaces->nodeTab[j];
1108         if (!xml_interface)
1109           continue;
1110
1111         for (xmlNodePtr child = xml_interface->children; child;
1112              child = child->next) {
1113           if (child->type != XML_ELEMENT_NODE)
1114             continue;
1115
1116           if (xmlStrEqual(child->name, (const xmlChar *)"target")) {
1117             path = (char *)xmlGetProp(child, (const xmlChar *)"dev");
1118             if (!path)
1119               continue;
1120           } else if (xmlStrEqual(child->name, (const xmlChar *)"mac")) {
1121             address = (char *)xmlGetProp(child, (const xmlChar *)"address");
1122             if (!address)
1123               continue;
1124           }
1125         }
1126
1127         if (il_interface_devices &&
1128             (ignore_device_match(il_interface_devices, name, path) != 0 ||
1129              ignore_device_match(il_interface_devices, name, address) != 0))
1130           goto cont3;
1131
1132         add_interface_device(state, dom, path, address, j + 1);
1133       cont3:
1134         if (path)
1135           xmlFree(path);
1136         if (address)
1137           xmlFree(address);
1138       }
1139
1140     cont:
1141       if (xpath_obj)
1142         xmlXPathFreeObject(xpath_obj);
1143       if (xpath_ctx)
1144         xmlXPathFreeContext(xpath_ctx);
1145       if (xml_doc)
1146         xmlFreeDoc(xml_doc);
1147       sfree(xml);
1148     }
1149
1150     sfree(domids);
1151   }
1152
1153   DEBUG(PLUGIN_NAME " plugin#%s: refreshing"
1154                     " domains=%i block_devices=%i iface_devices=%i",
1155         inst->tag, state->nr_domains, state->nr_block_devices,
1156         state->nr_interface_devices);
1157
1158   return 0;
1159 }
1160
1161 static void free_domains(struct lv_read_state *state) {
1162   if (state->domains) {
1163     for (int i = 0; i < state->nr_domains; ++i)
1164       virDomainFree(state->domains[i]);
1165     sfree(state->domains);
1166   }
1167   state->domains = NULL;
1168   state->nr_domains = 0;
1169 }
1170
1171 static int add_domain(struct lv_read_state *state, virDomainPtr dom) {
1172   virDomainPtr *new_ptr;
1173   int new_size = sizeof(state->domains[0]) * (state->nr_domains + 1);
1174
1175   if (state->domains)
1176     new_ptr = realloc(state->domains, new_size);
1177   else
1178     new_ptr = malloc(new_size);
1179
1180   if (new_ptr == NULL)
1181     return -1;
1182
1183   state->domains = new_ptr;
1184   state->domains[state->nr_domains] = dom;
1185   return state->nr_domains++;
1186 }
1187
1188 static void free_block_devices(struct lv_read_state *state) {
1189   if (state->block_devices) {
1190     for (int i = 0; i < state->nr_block_devices; ++i)
1191       sfree(state->block_devices[i].path);
1192     sfree(state->block_devices);
1193   }
1194   state->block_devices = NULL;
1195   state->nr_block_devices = 0;
1196 }
1197
1198 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
1199                             const char *path) {
1200   struct block_device *new_ptr;
1201   int new_size =
1202       sizeof(state->block_devices[0]) * (state->nr_block_devices + 1);
1203   char *path_copy;
1204
1205   path_copy = strdup(path);
1206   if (!path_copy)
1207     return -1;
1208
1209   if (state->block_devices)
1210     new_ptr = realloc(state->block_devices, new_size);
1211   else
1212     new_ptr = malloc(new_size);
1213
1214   if (new_ptr == NULL) {
1215     sfree(path_copy);
1216     return -1;
1217   }
1218   state->block_devices = new_ptr;
1219   state->block_devices[state->nr_block_devices].dom = dom;
1220   state->block_devices[state->nr_block_devices].path = path_copy;
1221   return state->nr_block_devices++;
1222 }
1223
1224 static void free_interface_devices(struct lv_read_state *state) {
1225   if (state->interface_devices) {
1226     for (int i = 0; i < state->nr_interface_devices; ++i) {
1227       sfree(state->interface_devices[i].path);
1228       sfree(state->interface_devices[i].address);
1229       sfree(state->interface_devices[i].number);
1230     }
1231     sfree(state->interface_devices);
1232   }
1233   state->interface_devices = NULL;
1234   state->nr_interface_devices = 0;
1235 }
1236
1237 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
1238                                 const char *path, const char *address,
1239                                 unsigned int number) {
1240   struct interface_device *new_ptr;
1241   int new_size =
1242       sizeof(state->interface_devices[0]) * (state->nr_interface_devices + 1);
1243   char *path_copy, *address_copy, number_string[15];
1244
1245   if ((path == NULL) || (address == NULL))
1246     return EINVAL;
1247
1248   path_copy = strdup(path);
1249   if (!path_copy)
1250     return -1;
1251
1252   address_copy = strdup(address);
1253   if (!address_copy) {
1254     sfree(path_copy);
1255     return -1;
1256   }
1257
1258   snprintf(number_string, sizeof(number_string), "interface-%u", number);
1259
1260   if (state->interface_devices)
1261     new_ptr = realloc(state->interface_devices, new_size);
1262   else
1263     new_ptr = malloc(new_size);
1264
1265   if (new_ptr == NULL) {
1266     sfree(path_copy);
1267     sfree(address_copy);
1268     return -1;
1269   }
1270   state->interface_devices = new_ptr;
1271   state->interface_devices[state->nr_interface_devices].dom = dom;
1272   state->interface_devices[state->nr_interface_devices].path = path_copy;
1273   state->interface_devices[state->nr_interface_devices].address = address_copy;
1274   state->interface_devices[state->nr_interface_devices].number =
1275       strdup(number_string);
1276   return state->nr_interface_devices++;
1277 }
1278
1279 static int ignore_device_match(ignorelist_t *il, const char *domname,
1280                                const char *devpath) {
1281   char *name;
1282   int n, r;
1283
1284   if ((domname == NULL) || (devpath == NULL))
1285     return 0;
1286
1287   n = sizeof(char) * (strlen(domname) + strlen(devpath) + 2);
1288   name = malloc(n);
1289   if (name == NULL) {
1290     ERROR(PLUGIN_NAME " plugin: malloc failed.");
1291     return 0;
1292   }
1293   ssnprintf(name, n, "%s:%s", domname, devpath);
1294   r = ignorelist_match(il, name);
1295   sfree(name);
1296   return r;
1297 }
1298
1299 static int lv_shutdown(void) {
1300   for (int i = 0; i < nr_instances; ++i) {
1301     lv_fini_instance(i);
1302   }
1303
1304   lv_disconnect();
1305
1306   ignorelist_free(il_domains);
1307   il_domains = NULL;
1308   ignorelist_free(il_block_devices);
1309   il_block_devices = NULL;
1310   ignorelist_free(il_interface_devices);
1311   il_interface_devices = NULL;
1312
1313   return 0;
1314 }
1315
1316 void module_register(void) {
1317   plugin_register_config(PLUGIN_NAME, lv_config, config_keys, NR_CONFIG_KEYS);
1318   plugin_register_init(PLUGIN_NAME, lv_init);
1319   plugin_register_shutdown(PLUGIN_NAME, lv_shutdown);
1320 }