Update virt.c
[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  *   Przemyslaw Szczerbik <przemyslawx.szczerbik@intel.com>
21  **/
22
23 #include "collectd.h"
24
25 #include "common.h"
26 #include "plugin.h"
27 #include "utils_complain.h"
28 #include "utils_ignorelist.h"
29
30 #include <libgen.h> /* for basename(3) */
31 #include <libvirt/libvirt.h>
32 #include <libvirt/virterror.h>
33 #include <libxml/parser.h>
34 #include <libxml/tree.h>
35 #include <libxml/xpath.h>
36 #include <libxml/xpathInternals.h>
37
38 /* Plugin name */
39 #define PLUGIN_NAME "virt"
40
41 #ifdef LIBVIR_CHECK_VERSION
42
43 #if LIBVIR_CHECK_VERSION(0, 9, 2)
44 #define HAVE_DOM_REASON 1
45 #endif
46
47 #if LIBVIR_CHECK_VERSION(0, 9, 5)
48 #define HAVE_BLOCK_STATS_FLAGS 1
49 #define HAVE_DOM_REASON_PAUSED_SHUTTING_DOWN 1
50 #endif
51
52 #if LIBVIR_CHECK_VERSION(0, 9, 10)
53 #define HAVE_DISK_ERR 1
54 #endif
55
56 #if LIBVIR_CHECK_VERSION(0, 9, 11)
57 #define HAVE_CPU_STATS 1
58 #define HAVE_DOM_STATE_PMSUSPENDED 1
59 #define HAVE_DOM_REASON_RUNNING_WAKEUP 1
60 #endif
61
62 #if LIBVIR_CHECK_VERSION(1, 0, 1)
63 #define HAVE_DOM_REASON_PAUSED_SNAPSHOT 1
64 #endif
65
66 #if LIBVIR_CHECK_VERSION(1, 1, 1)
67 #define HAVE_DOM_REASON_PAUSED_CRASHED 1
68 #endif
69
70 #if LIBVIR_CHECK_VERSION(1, 2, 9)
71 #define HAVE_JOB_STATS 1
72 #endif
73
74 #if LIBVIR_CHECK_VERSION(1, 2, 10)
75 #define HAVE_DOM_REASON_CRASHED 1
76 #endif
77
78 #if LIBVIR_CHECK_VERSION(1, 2, 11)
79 #define HAVE_FS_INFO 1
80 #endif
81
82 #if LIBVIR_CHECK_VERSION(1, 2, 15)
83 #define HAVE_DOM_REASON_PAUSED_STARTING_UP 1
84 #endif
85
86 #if LIBVIR_CHECK_VERSION(1, 3, 3)
87 #define HAVE_PERF_STATS 1
88 #define HAVE_DOM_REASON_POSTCOPY 1
89 #endif
90
91 #endif /* LIBVIR_CHECK_VERSION */
92
93 static const char *config_keys[] = {"Connection",
94
95                                     "RefreshInterval",
96
97                                     "Domain",
98                                     "BlockDevice",
99                                     "BlockDeviceFormat",
100                                     "BlockDeviceFormatBasename",
101                                     "InterfaceDevice",
102                                     "IgnoreSelected",
103
104                                     "HostnameFormat",
105                                     "InterfaceFormat",
106
107                                     "PluginInstanceFormat",
108
109                                     "Instances",
110                                     "ExtraStats",
111                                     NULL};
112
113 const char *domain_states[] = {
114         [VIR_DOMAIN_NOSTATE] = "no state",
115         [VIR_DOMAIN_RUNNING] = "the domain is running",
116         [VIR_DOMAIN_BLOCKED] = "the domain is blocked on resource",
117         [VIR_DOMAIN_PAUSED] = "the domain is paused by user",
118         [VIR_DOMAIN_SHUTDOWN] = "the domain is being shut down",
119         [VIR_DOMAIN_SHUTOFF] = "the domain is shut off",
120         [VIR_DOMAIN_CRASHED] = "the domain is crashed",
121 #ifdef HAVE_DOM_STATE_PMSUSPENDED
122         [VIR_DOMAIN_PMSUSPENDED] =
123             "the domain is suspended by guest power management",
124 #endif
125 };
126
127 #ifdef HAVE_DOM_REASON
128 #define DOMAIN_STATE_REASON_MAX_SIZE 20
129 const char *domain_reasons[][DOMAIN_STATE_REASON_MAX_SIZE] = {
130         [VIR_DOMAIN_NOSTATE][VIR_DOMAIN_NOSTATE_UNKNOWN] =
131             "the reason is unknown",
132
133         [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_UNKNOWN] =
134             "the reason is unknown",
135         [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_BOOTED] =
136             "normal startup from boot",
137         [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_MIGRATED] =
138             "migrated from another host",
139         [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_RESTORED] =
140             "restored from a state file",
141         [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_FROM_SNAPSHOT] =
142             "restored from snapshot",
143         [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_UNPAUSED] =
144             "returned from paused state",
145         [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_MIGRATION_CANCELED] =
146             "returned from migration",
147         [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_SAVE_CANCELED] =
148             "returned from failed save process",
149 #ifdef HAVE_DOM_REASON_RUNNING_WAKEUP
150         [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_WAKEUP] =
151             "returned from pmsuspended due to wakeup event",
152 #endif
153 #ifdef HAVE_DOM_REASON_CRASHED
154         [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_CRASHED] =
155             "resumed from crashed",
156 #endif
157 #ifdef HAVE_DOM_REASON_POSTCOPY
158         [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_POSTCOPY] =
159             "running in post-copy migration mode",
160 #endif
161
162         [VIR_DOMAIN_BLOCKED][VIR_DOMAIN_BLOCKED_UNKNOWN] =
163             "the reason is unknown",
164
165         [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_UNKNOWN] =
166             "the reason is unknown",
167         [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_USER] = "paused on user request",
168         [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_MIGRATION] =
169             "paused for offline migration",
170         [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_SAVE] = "paused for save",
171         [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_DUMP] =
172             "paused for offline core dump",
173         [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_IOERROR] =
174             "paused due to a disk I/O error",
175         [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_WATCHDOG] =
176             "paused due to a watchdog event",
177         [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_FROM_SNAPSHOT] =
178             "paused after restoring from snapshot",
179 #ifdef HAVE_DOM_REASON_PAUSED_SHUTTING_DOWN
180         [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_SHUTTING_DOWN] =
181             "paused during shutdown process",
182 #endif
183 #ifdef HAVE_DOM_REASON_PAUSED_SNAPSHOT
184         [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_SNAPSHOT] =
185             "paused while creating a snapshot",
186 #endif
187 #ifdef HAVE_DOM_REASON_PAUSED_CRASHED
188         [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_CRASHED] =
189             "paused due to a guest crash",
190 #endif
191 #ifdef HAVE_DOM_REASON_PAUSED_STARTING_UP
192         [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_STARTING_UP] =
193             "the domain is being started",
194 #endif
195 #ifdef HAVE_DOM_REASON_POSTCOPY
196         [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_POSTCOPY] =
197             "paused for post-copy migration",
198         [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_POSTCOPY_FAILED] =
199             "paused after failed post-copy",
200 #endif
201
202         [VIR_DOMAIN_SHUTDOWN][VIR_DOMAIN_SHUTDOWN_UNKNOWN] =
203             "the reason is unknown",
204         [VIR_DOMAIN_SHUTDOWN][VIR_DOMAIN_SHUTDOWN_USER] =
205             "shutting down on user request",
206
207         [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_UNKNOWN] =
208             "the reason is unknown",
209         [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_SHUTDOWN] = "normal shutdown",
210         [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_DESTROYED] = "forced poweroff",
211         [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_CRASHED] = "domain crashed",
212         [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_MIGRATED] =
213             "migrated to another host",
214         [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_SAVED] = "saved to a file",
215         [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_FAILED] =
216             "domain failed to start",
217         [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT] =
218             "restored from a snapshot which was taken while domain was shutoff",
219
220         [VIR_DOMAIN_CRASHED][VIR_DOMAIN_CRASHED_UNKNOWN] =
221             "the reason is unknown",
222 #ifdef VIR_DOMAIN_CRASHED_PANICKED
223         [VIR_DOMAIN_CRASHED][VIR_DOMAIN_CRASHED_PANICKED] = "domain panicked",
224 #endif
225
226 #ifdef HAVE_DOM_STATE_PMSUSPENDED
227         [VIR_DOMAIN_PMSUSPENDED][VIR_DOMAIN_PMSUSPENDED_UNKNOWN] =
228             "the reason is unknown",
229 #endif
230 };
231 #endif /* HAVE_DOM_REASON */
232
233 #define NR_CONFIG_KEYS ((sizeof config_keys / sizeof config_keys[0]) - 1)
234 #define NANOSEC_IN_SEC 1e9
235
236 #define GET_STATS(_f, _name, ...)                                              \
237   do {                                                                         \
238     status = _f(__VA_ARGS__);                                                  \
239     if (status != 0)                                                           \
240       ERROR(PLUGIN_NAME ": Failed to get " _name);                             \
241   } while (0)
242
243 /* Connection. */
244 static virConnectPtr conn = 0;
245 static char *conn_string = NULL;
246 static c_complain_t conn_complain = C_COMPLAIN_INIT_STATIC;
247
248 /* Node information required for %CPU */
249 static virNodeInfo nodeinfo;
250
251 /* Seconds between list refreshes, 0 disables completely. */
252 static int interval = 60;
253
254 /* List of domains, if specified. */
255 static ignorelist_t *il_domains = NULL;
256 /* List of block devices, if specified. */
257 static ignorelist_t *il_block_devices = NULL;
258 /* List of network interface devices, if specified. */
259 static ignorelist_t *il_interface_devices = NULL;
260
261 static int ignore_device_match(ignorelist_t *, const char *domname,
262                                const char *devpath);
263
264 /* Actual list of block devices found on last refresh. */
265 struct block_device {
266   virDomainPtr dom; /* domain */
267   char *path;       /* name of block device */
268 };
269
270 /* Actual list of network interfaces found on last refresh. */
271 struct interface_device {
272   virDomainPtr dom; /* domain */
273   char *path;       /* name of interface device */
274   char *address;    /* mac address of interface device */
275   char *number;     /* interface device number */
276 };
277
278 typedef struct domain_s {
279   virDomainPtr ptr;
280   virDomainInfo info;
281 } domain_t;
282
283 struct lv_read_state {
284   /* Actual list of domains found on last refresh. */
285   domain_t *domains;
286   int nr_domains;
287
288   struct block_device *block_devices;
289   int nr_block_devices;
290
291   struct interface_device *interface_devices;
292   int nr_interface_devices;
293 };
294
295 static void free_domains(struct lv_read_state *state);
296 static int add_domain(struct lv_read_state *state, virDomainPtr dom);
297
298 static void free_block_devices(struct lv_read_state *state);
299 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
300                             const char *path);
301
302 static void free_interface_devices(struct lv_read_state *state);
303 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
304                                 const char *path, const char *address,
305                                 unsigned int number);
306
307 #define METADATA_VM_PARTITION_URI "http://ovirt.org/ovirtmap/tag/1.0"
308 #define METADATA_VM_PARTITION_ELEMENT "tag"
309 #define METADATA_VM_PARTITION_PREFIX "ovirtmap"
310
311 #define BUFFER_MAX_LEN 256
312 #define PARTITION_TAG_MAX_LEN 32
313
314 struct lv_read_instance {
315   struct lv_read_state read_state;
316   char tag[PARTITION_TAG_MAX_LEN];
317   size_t id;
318 };
319
320 struct lv_user_data {
321   struct lv_read_instance inst;
322   user_data_t ud;
323 };
324
325 #define NR_INSTANCES_DEFAULT 1
326 #define NR_INSTANCES_MAX 128
327 static int nr_instances = NR_INSTANCES_DEFAULT;
328 static struct lv_user_data lv_read_user_data[NR_INSTANCES_MAX];
329
330 /* HostnameFormat. */
331 #define HF_MAX_FIELDS 3
332
333 enum hf_field { hf_none = 0, hf_hostname, hf_name, hf_uuid };
334
335 static enum hf_field hostname_format[HF_MAX_FIELDS] = {hf_name};
336
337 /* PluginInstanceFormat */
338 #define PLGINST_MAX_FIELDS 2
339
340 enum plginst_field { plginst_none = 0, plginst_name, plginst_uuid };
341
342 static enum plginst_field plugin_instance_format[PLGINST_MAX_FIELDS] = {
343     plginst_none};
344
345 /* BlockDeviceFormat */
346 enum bd_field { target, source };
347
348 /* InterfaceFormat. */
349 enum if_field { if_address, if_name, if_number };
350
351 /* ExtraStats */
352 #define EX_STATS_MAX_FIELDS 15
353 enum ex_stats {
354   ex_stats_none = 0,
355   ex_stats_disk = 1 << 0,
356   ex_stats_pcpu = 1 << 1,
357   ex_stats_cpu_util = 1 << 2,
358   ex_stats_domain_state = 1 << 3,
359 #ifdef HAVE_PERF_STATS
360   ex_stats_perf = 1 << 4,
361 #endif
362   ex_stats_vcpupin = 1 << 5,
363 #ifdef HAVE_DISK_ERR
364   ex_stats_disk_err = 1 << 6,
365 #endif
366 #ifdef HAVE_FS_INFO
367   ex_stats_fs_info = 1 << 7,
368 #endif
369 #ifdef HAVE_JOB_STATS
370   ex_stats_job_stats_completed = 1 << 8,
371   ex_stats_job_stats_background = 1 << 9,
372 #endif
373 };
374
375 static unsigned int extra_stats = ex_stats_none;
376
377 struct ex_stats_item {
378   const char *name;
379   enum ex_stats flag;
380 };
381 static const struct ex_stats_item ex_stats_table[] = {
382     {"disk", ex_stats_disk},
383     {"pcpu", ex_stats_pcpu},
384     {"cpu_util", ex_stats_cpu_util},
385     {"domain_state", ex_stats_domain_state},
386 #ifdef HAVE_PERF_STATS
387     {"perf", ex_stats_perf},
388 #endif
389     {"vcpupin", ex_stats_vcpupin},
390 #ifdef HAVE_DISK_ERR
391     {"disk_err", ex_stats_disk_err},
392 #endif
393 #ifdef HAVE_FS_INFO
394     {"fs_info", ex_stats_fs_info},
395 #endif
396 #ifdef HAVE_JOB_STATS
397     {"job_stats_completed", ex_stats_job_stats_completed},
398     {"job_stats_background", ex_stats_job_stats_background},
399 #endif
400     {NULL, ex_stats_none},
401 };
402
403 /* BlockDeviceFormatBasename */
404 _Bool blockdevice_format_basename = 0;
405 static enum bd_field blockdevice_format = target;
406 static enum if_field interface_format = if_name;
407
408 /* Time that we last refreshed. */
409 static time_t last_refresh = (time_t)0;
410
411 static int refresh_lists(struct lv_read_instance *inst);
412
413 struct lv_info {
414   virDomainInfo di;
415   unsigned long long total_user_cpu_time;
416   unsigned long long total_syst_cpu_time;
417 };
418
419 struct lv_block_info {
420   virDomainBlockStatsStruct bi;
421
422   long long rd_total_times;
423   long long wr_total_times;
424
425   long long fl_req;
426   long long fl_total_times;
427 };
428
429 static void init_block_info(struct lv_block_info *binfo) {
430   if (binfo == NULL)
431     return;
432
433   binfo->bi.rd_req = -1;
434   binfo->bi.wr_req = -1;
435   binfo->bi.rd_bytes = -1;
436   binfo->bi.wr_bytes = -1;
437
438   binfo->rd_total_times = -1;
439   binfo->wr_total_times = -1;
440   binfo->fl_req = -1;
441   binfo->fl_total_times = -1;
442 }
443
444 #ifdef HAVE_BLOCK_STATS_FLAGS
445
446 #define GET_BLOCK_INFO_VALUE(NAME, FIELD)                                      \
447   if (!strcmp(param[i].field, NAME)) {                                         \
448     binfo->FIELD = param[i].value.l;                                           \
449     continue;                                                                  \
450   }
451
452 static int get_block_info(struct lv_block_info *binfo,
453                           virTypedParameterPtr param, int nparams) {
454   if (binfo == NULL || param == NULL)
455     return -1;
456
457   for (int i = 0; i < nparams; ++i) {
458     /* ignore type. Everything must be LLONG anyway. */
459     GET_BLOCK_INFO_VALUE("rd_operations", bi.rd_req);
460     GET_BLOCK_INFO_VALUE("wr_operations", bi.wr_req);
461     GET_BLOCK_INFO_VALUE("rd_bytes", bi.rd_bytes);
462     GET_BLOCK_INFO_VALUE("wr_bytes", bi.wr_bytes);
463     GET_BLOCK_INFO_VALUE("rd_total_times", rd_total_times);
464     GET_BLOCK_INFO_VALUE("wr_total_times", wr_total_times);
465     GET_BLOCK_INFO_VALUE("flush_operations", fl_req);
466     GET_BLOCK_INFO_VALUE("flush_total_times", fl_total_times);
467   }
468
469   return 0;
470 }
471
472 #undef GET_BLOCK_INFO_VALUE
473
474 #endif /* HAVE_BLOCK_STATS_FLAGS */
475
476 /* ERROR(...) macro for virterrors. */
477 #define VIRT_ERROR(conn, s)                                                    \
478   do {                                                                         \
479     virErrorPtr err;                                                           \
480     err = (conn) ? virConnGetLastError((conn)) : virGetLastError();            \
481     if (err)                                                                   \
482       ERROR("%s: %s", (s), err->message);                                      \
483   } while (0)
484
485 static void init_lv_info(struct lv_info *info) {
486   if (info != NULL)
487     memset(info, 0, sizeof(*info));
488 }
489
490 static int lv_domain_info(virDomainPtr dom, struct lv_info *info) {
491 #ifdef HAVE_CPU_STATS
492   virTypedParameterPtr param = NULL;
493   int nparams = 0;
494 #endif /* HAVE_CPU_STATS */
495   int ret = virDomainGetInfo(dom, &(info->di));
496   if (ret != 0) {
497     return ret;
498   }
499
500 #ifdef HAVE_CPU_STATS
501   nparams = virDomainGetCPUStats(dom, NULL, 0, -1, 1, 0);
502   if (nparams < 0) {
503     VIRT_ERROR(conn, "getting the CPU params count");
504     return -1;
505   }
506
507   param = calloc(nparams, sizeof(virTypedParameter));
508   if (param == NULL) {
509     ERROR("virt plugin: alloc(%i) for cpu parameters failed.", nparams);
510     return -1;
511   }
512
513   ret = virDomainGetCPUStats(dom, param, nparams, -1, 1, 0); // total stats.
514   if (ret < 0) {
515     virTypedParamsClear(param, nparams);
516     sfree(param);
517     VIRT_ERROR(conn, "getting the disk params values");
518     return -1;
519   }
520
521   for (int i = 0; i < nparams; ++i) {
522     if (!strcmp(param[i].field, "user_time"))
523       info->total_user_cpu_time = param[i].value.ul;
524     else if (!strcmp(param[i].field, "system_time"))
525       info->total_syst_cpu_time = param[i].value.ul;
526   }
527
528   virTypedParamsClear(param, nparams);
529   sfree(param);
530 #endif /* HAVE_CPU_STATS */
531
532   return 0;
533 }
534
535 static void init_value_list(value_list_t *vl, virDomainPtr dom) {
536   int n;
537   const char *name;
538   char uuid[VIR_UUID_STRING_BUFLEN];
539
540   sstrncpy(vl->plugin, PLUGIN_NAME, sizeof(vl->plugin));
541
542   vl->host[0] = '\0';
543
544   /* Construct the hostname field according to HostnameFormat. */
545   for (int i = 0; i < HF_MAX_FIELDS; ++i) {
546     if (hostname_format[i] == hf_none)
547       continue;
548
549     n = DATA_MAX_NAME_LEN - strlen(vl->host) - 2;
550
551     if (i > 0 && n >= 1) {
552       strncat(vl->host, ":", 1);
553       n--;
554     }
555
556     switch (hostname_format[i]) {
557     case hf_none:
558       break;
559     case hf_hostname:
560       strncat(vl->host, hostname_g, n);
561       break;
562     case hf_name:
563       name = virDomainGetName(dom);
564       if (name)
565         strncat(vl->host, name, n);
566       break;
567     case hf_uuid:
568       if (virDomainGetUUIDString(dom, uuid) == 0)
569         strncat(vl->host, uuid, n);
570       break;
571     }
572   }
573
574   vl->host[sizeof(vl->host) - 1] = '\0';
575
576   /* Construct the plugin instance field according to PluginInstanceFormat. */
577   for (int i = 0; i < PLGINST_MAX_FIELDS; ++i) {
578     if (plugin_instance_format[i] == plginst_none)
579       continue;
580
581     n = sizeof(vl->plugin_instance) - strlen(vl->plugin_instance) - 2;
582
583     if (i > 0 && n >= 1) {
584       strncat(vl->plugin_instance, ":", 1);
585       n--;
586     }
587
588     switch (plugin_instance_format[i]) {
589     case plginst_none:
590       break;
591     case plginst_name:
592       name = virDomainGetName(dom);
593       if (name)
594         strncat(vl->plugin_instance, name, n);
595       break;
596     case plginst_uuid:
597       if (virDomainGetUUIDString(dom, uuid) == 0)
598         strncat(vl->plugin_instance, uuid, n);
599       break;
600     }
601   }
602
603   vl->plugin_instance[sizeof(vl->plugin_instance) - 1] = '\0';
604
605 } /* void init_value_list */
606
607 static int init_notif(notification_t *notif, const virDomainPtr domain,
608                       int severity, const char *msg, const char *type,
609                       const char *type_instance) {
610   value_list_t vl = VALUE_LIST_INIT;
611
612   if (!notif) {
613     ERROR(PLUGIN_NAME ": init_notif: NULL pointer");
614     return -1;
615   }
616
617   init_value_list(&vl, domain);
618   notification_init(notif, severity, msg, vl.host, vl.plugin,
619                     vl.plugin_instance, type, type_instance);
620   notif->time = cdtime();
621   return 0;
622 }
623
624 static void submit_notif(const virDomainPtr domain, int severity,
625                          const char *msg, const char *type,
626                          const char *type_instance) {
627   notification_t notif;
628
629   init_notif(&notif, domain, severity, msg, type, type_instance);
630   plugin_dispatch_notification(&notif);
631   if (notif.meta)
632     plugin_notification_meta_free(notif.meta);
633 }
634
635 static void submit(virDomainPtr dom, char const *type,
636                    char const *type_instance, value_t *values,
637                    size_t values_len) {
638   value_list_t vl = VALUE_LIST_INIT;
639   init_value_list(&vl, dom);
640
641   vl.values = values;
642   vl.values_len = values_len;
643
644   sstrncpy(vl.type, type, sizeof(vl.type));
645   if (type_instance != NULL)
646     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
647
648   plugin_dispatch_values(&vl);
649 }
650
651 static void memory_submit(virDomainPtr dom, gauge_t value) {
652   submit(dom, "memory", "total", &(value_t){.gauge = value}, 1);
653 }
654
655 static void memory_stats_submit(gauge_t value, virDomainPtr dom,
656                                 int tag_index) {
657   static const char *tags[] = {"swap_in",        "swap_out", "major_fault",
658                                "minor_fault",    "unused",   "available",
659                                "actual_balloon", "rss",      "usable",
660                                "last_update"};
661
662   if ((tag_index < 0) || (tag_index >= (int)STATIC_ARRAY_SIZE(tags))) {
663     ERROR("virt plugin: Array index out of bounds: tag_index = %d", tag_index);
664     return;
665   }
666
667   submit(dom, "memory", tags[tag_index], &(value_t){.gauge = value}, 1);
668 }
669
670 static void submit_derive2(const char *type, derive_t v0, derive_t v1,
671                            virDomainPtr dom, const char *devname) {
672   value_t values[] = {
673       {.derive = v0}, {.derive = v1},
674   };
675
676   submit(dom, type, devname, values, STATIC_ARRAY_SIZE(values));
677 } /* void submit_derive2 */
678
679 static void pcpu_submit(virDomainPtr dom, struct lv_info *info) {
680 #ifdef HAVE_CPU_STATS
681   if (extra_stats & ex_stats_pcpu)
682     submit_derive2("ps_cputime", info->total_user_cpu_time,
683                    info->total_syst_cpu_time, dom, NULL);
684 #endif /* HAVE_CPU_STATS */
685 }
686
687 static double cpu_ns_to_percent(unsigned int node_cpus,
688                                 unsigned long long cpu_time_old,
689                                 unsigned long long cpu_time_new) {
690   double percent = 0.0;
691   unsigned long long cpu_time_diff = 0;
692   double time_diff_sec = CDTIME_T_TO_DOUBLE(plugin_get_interval());
693
694   if (node_cpus != 0 && time_diff_sec != 0 && cpu_time_old != 0) {
695     cpu_time_diff = cpu_time_new - cpu_time_old;
696     percent = ((double)(100 * cpu_time_diff)) /
697               (time_diff_sec * node_cpus * NANOSEC_IN_SEC);
698   }
699
700   DEBUG(PLUGIN_NAME ": node_cpus=%u cpu_time_old=%llu cpu_time_new=%llu"
701                     "cpu_time_diff=%llu time_diff_sec=%f percent=%f",
702         node_cpus, cpu_time_old, cpu_time_new, cpu_time_diff, time_diff_sec,
703         percent);
704
705   return percent;
706 }
707
708 static void cpu_submit(const domain_t *dom, unsigned long long cpuTime_new) {
709
710   if (!dom)
711     return;
712
713   if (extra_stats & ex_stats_cpu_util) {
714     /* Computing %CPU requires 2 samples of cpuTime */
715     if (dom->info.cpuTime != 0 && cpuTime_new != 0) {
716
717       submit(dom->ptr, "percent", "virt_cpu_total",
718              &(value_t){.gauge = cpu_ns_to_percent(
719                             nodeinfo.cpus, dom->info.cpuTime, cpuTime_new)},
720              1);
721     }
722   }
723
724   submit(dom->ptr, "virt_cpu_total", NULL, &(value_t){.derive = cpuTime_new},
725          1);
726 }
727
728 static void vcpu_submit(derive_t value, virDomainPtr dom, int vcpu_nr,
729                         const char *type) {
730   char type_instance[DATA_MAX_NAME_LEN];
731
732   snprintf(type_instance, sizeof(type_instance), "%d", vcpu_nr);
733   submit(dom, type, type_instance, &(value_t){.derive = value}, 1);
734 }
735
736 static void disk_submit(struct lv_block_info *binfo, virDomainPtr dom,
737                         const char *dev) {
738   char *dev_copy = strdup(dev);
739   const char *type_instance = dev_copy;
740
741   if (!dev_copy)
742     return;
743
744   if (blockdevice_format_basename && blockdevice_format == source)
745     type_instance = basename(dev_copy);
746
747   if (!type_instance) {
748     sfree(dev_copy);
749     return;
750   }
751
752   char flush_type_instance[DATA_MAX_NAME_LEN];
753   snprintf(flush_type_instance, sizeof(flush_type_instance), "flush-%s",
754            type_instance);
755
756   if ((binfo->bi.rd_req != -1) && (binfo->bi.wr_req != -1))
757     submit_derive2("disk_ops", (derive_t)binfo->bi.rd_req,
758                    (derive_t)binfo->bi.wr_req, dom, type_instance);
759
760   if ((binfo->bi.rd_bytes != -1) && (binfo->bi.wr_bytes != -1))
761     submit_derive2("disk_octets", (derive_t)binfo->bi.rd_bytes,
762                    (derive_t)binfo->bi.wr_bytes, dom, type_instance);
763
764   if (extra_stats & ex_stats_disk) {
765     if ((binfo->rd_total_times != -1) && (binfo->wr_total_times != -1))
766       submit_derive2("disk_time", (derive_t)binfo->rd_total_times,
767                      (derive_t)binfo->wr_total_times, dom, type_instance);
768
769     if (binfo->fl_req != -1)
770       submit(dom, "total_requests", flush_type_instance,
771              &(value_t){.derive = (derive_t)binfo->fl_req}, 1);
772     if (binfo->fl_total_times != -1) {
773       derive_t value = binfo->fl_total_times / 1000; // ns -> ms
774       submit(dom, "total_time_in_ms", flush_type_instance,
775              &(value_t){.derive = value}, 1);
776     }
777   }
778
779   sfree(dev_copy);
780 }
781
782 static unsigned int parse_ex_stats_flags(char **exstats, int numexstats) {
783   unsigned int ex_stats_flags = ex_stats_none;
784   for (int i = 0; i < numexstats; i++) {
785     for (int j = 0; ex_stats_table[j].name != NULL; j++) {
786       if (strcasecmp(exstats[i], ex_stats_table[j].name) == 0) {
787         DEBUG(PLUGIN_NAME " plugin: enabling extra stats for '%s'",
788               ex_stats_table[j].name);
789         ex_stats_flags |= ex_stats_table[j].flag;
790         break;
791       }
792
793       if (ex_stats_table[j + 1].name == NULL) {
794         ERROR(PLUGIN_NAME ": Unmatched ExtraStats option: %s", exstats[i]);
795       }
796     }
797   }
798   return ex_stats_flags;
799 }
800
801 static void domain_state_submit(virDomainPtr dom, int state, int reason) {
802
803   if ((state < 0) || (state >= STATIC_ARRAY_SIZE(domain_states))) {
804     ERROR(PLUGIN_NAME ": Array index out of bounds: state=%d", state);
805     return;
806   }
807
808   char msg[DATA_MAX_NAME_LEN];
809   const char *state_str = domain_states[state];
810 #ifdef HAVE_DOM_REASON
811   if ((reason < 0) || (reason >= STATIC_ARRAY_SIZE(domain_reasons[0]))) {
812     ERROR(PLUGIN_NAME ": Array index out of bounds: reason=%d", reason);
813     return;
814   }
815
816   const char *reason_str = domain_reasons[state][reason];
817   /* Array size for domain reasons is fixed, but different domain states can
818    * have different number of reasons. We need to check if reason was
819    * successfully parsed */
820   if (!reason_str) {
821     ERROR(PLUGIN_NAME ": Invalid reason (%d) for domain state: %s", reason,
822           state_str);
823     return;
824   }
825 #else
826   const char *reason_str = "N/A";
827 #endif
828
829   snprintf(msg, sizeof(msg), "Domain state: %s. Reason: %s", state_str,
830            reason_str);
831
832   int severity;
833   switch (state) {
834   case VIR_DOMAIN_NOSTATE:
835   case VIR_DOMAIN_RUNNING:
836   case VIR_DOMAIN_SHUTDOWN:
837   case VIR_DOMAIN_SHUTOFF:
838     severity = NOTIF_OKAY;
839     break;
840   case VIR_DOMAIN_BLOCKED:
841   case VIR_DOMAIN_PAUSED:
842 #ifdef DOM_STATE_PMSUSPENDED
843   case VIR_DOMAIN_PMSUSPENDED:
844 #endif
845     severity = NOTIF_WARNING;
846     break;
847   case VIR_DOMAIN_CRASHED:
848     severity = NOTIF_FAILURE;
849     break;
850   default:
851     ERROR(PLUGIN_NAME ": Unrecognized domain state (%d)", state);
852     return;
853   }
854   submit_notif(dom, severity, msg, "domain_state", NULL);
855 }
856
857 static int lv_config(const char *key, const char *value) {
858   if (virInitialize() != 0)
859     return 1;
860
861   if (il_domains == NULL)
862     il_domains = ignorelist_create(1);
863   if (il_block_devices == NULL)
864     il_block_devices = ignorelist_create(1);
865   if (il_interface_devices == NULL)
866     il_interface_devices = ignorelist_create(1);
867
868   if (strcasecmp(key, "Connection") == 0) {
869     char *tmp = strdup(value);
870     if (tmp == NULL) {
871       ERROR(PLUGIN_NAME " plugin: Connection strdup failed.");
872       return 1;
873     }
874     sfree(conn_string);
875     conn_string = tmp;
876     return 0;
877   }
878
879   if (strcasecmp(key, "RefreshInterval") == 0) {
880     char *eptr = NULL;
881     interval = strtol(value, &eptr, 10);
882     if (eptr == NULL || *eptr != '\0')
883       return 1;
884     return 0;
885   }
886
887   if (strcasecmp(key, "Domain") == 0) {
888     if (ignorelist_add(il_domains, value))
889       return 1;
890     return 0;
891   }
892   if (strcasecmp(key, "BlockDevice") == 0) {
893     if (ignorelist_add(il_block_devices, value))
894       return 1;
895     return 0;
896   }
897
898   if (strcasecmp(key, "BlockDeviceFormat") == 0) {
899     if (strcasecmp(value, "target") == 0)
900       blockdevice_format = target;
901     else if (strcasecmp(value, "source") == 0)
902       blockdevice_format = source;
903     else {
904       ERROR(PLUGIN_NAME " plugin: unknown BlockDeviceFormat: %s", value);
905       return -1;
906     }
907     return 0;
908   }
909   if (strcasecmp(key, "BlockDeviceFormatBasename") == 0) {
910     blockdevice_format_basename = IS_TRUE(value);
911     return 0;
912   }
913   if (strcasecmp(key, "InterfaceDevice") == 0) {
914     if (ignorelist_add(il_interface_devices, value))
915       return 1;
916     return 0;
917   }
918
919   if (strcasecmp(key, "IgnoreSelected") == 0) {
920     if (IS_TRUE(value)) {
921       ignorelist_set_invert(il_domains, 0);
922       ignorelist_set_invert(il_block_devices, 0);
923       ignorelist_set_invert(il_interface_devices, 0);
924     } else {
925       ignorelist_set_invert(il_domains, 1);
926       ignorelist_set_invert(il_block_devices, 1);
927       ignorelist_set_invert(il_interface_devices, 1);
928     }
929     return 0;
930   }
931
932   if (strcasecmp(key, "HostnameFormat") == 0) {
933     char *value_copy;
934     char *fields[HF_MAX_FIELDS];
935     int n;
936
937     value_copy = strdup(value);
938     if (value_copy == NULL) {
939       ERROR(PLUGIN_NAME " plugin: strdup failed.");
940       return -1;
941     }
942
943     n = strsplit(value_copy, fields, HF_MAX_FIELDS);
944     if (n < 1) {
945       sfree(value_copy);
946       ERROR(PLUGIN_NAME " plugin: HostnameFormat: no fields");
947       return -1;
948     }
949
950     for (int i = 0; i < n; ++i) {
951       if (strcasecmp(fields[i], "hostname") == 0)
952         hostname_format[i] = hf_hostname;
953       else if (strcasecmp(fields[i], "name") == 0)
954         hostname_format[i] = hf_name;
955       else if (strcasecmp(fields[i], "uuid") == 0)
956         hostname_format[i] = hf_uuid;
957       else {
958         ERROR(PLUGIN_NAME " plugin: unknown HostnameFormat field: %s",
959               fields[i]);
960         sfree(value_copy);
961         return -1;
962       }
963     }
964     sfree(value_copy);
965
966     for (int i = n; i < HF_MAX_FIELDS; ++i)
967       hostname_format[i] = hf_none;
968
969     return 0;
970   }
971
972   if (strcasecmp(key, "PluginInstanceFormat") == 0) {
973     char *value_copy;
974     char *fields[PLGINST_MAX_FIELDS];
975     int n;
976
977     value_copy = strdup(value);
978     if (value_copy == NULL) {
979       ERROR(PLUGIN_NAME " plugin: strdup failed.");
980       return -1;
981     }
982
983     n = strsplit(value_copy, fields, PLGINST_MAX_FIELDS);
984     if (n < 1) {
985       sfree(value_copy);
986       ERROR(PLUGIN_NAME " plugin: PluginInstanceFormat: no fields");
987       return -1;
988     }
989
990     for (int i = 0; i < n; ++i) {
991       if (strcasecmp(fields[i], "none") == 0) {
992         plugin_instance_format[i] = plginst_none;
993         break;
994       } else if (strcasecmp(fields[i], "name") == 0)
995         plugin_instance_format[i] = plginst_name;
996       else if (strcasecmp(fields[i], "uuid") == 0)
997         plugin_instance_format[i] = plginst_uuid;
998       else {
999         ERROR(PLUGIN_NAME " plugin: unknown PluginInstanceFormat field: %s",
1000               fields[i]);
1001         sfree(value_copy);
1002         return -1;
1003       }
1004     }
1005     sfree(value_copy);
1006
1007     for (int i = n; i < PLGINST_MAX_FIELDS; ++i)
1008       plugin_instance_format[i] = plginst_none;
1009
1010     return 0;
1011   }
1012
1013   if (strcasecmp(key, "InterfaceFormat") == 0) {
1014     if (strcasecmp(value, "name") == 0)
1015       interface_format = if_name;
1016     else if (strcasecmp(value, "address") == 0)
1017       interface_format = if_address;
1018     else if (strcasecmp(value, "number") == 0)
1019       interface_format = if_number;
1020     else {
1021       ERROR(PLUGIN_NAME " plugin: unknown InterfaceFormat: %s", value);
1022       return -1;
1023     }
1024     return 0;
1025   }
1026
1027   if (strcasecmp(key, "Instances") == 0) {
1028     char *eptr = NULL;
1029     double val = strtod(value, &eptr);
1030
1031     if (*eptr != '\0') {
1032       ERROR(PLUGIN_NAME " plugin: Invalid value for Instances = '%s'", value);
1033       return 1;
1034     }
1035     if (val <= 0) {
1036       ERROR(PLUGIN_NAME " plugin: Instances <= 0 makes no sense.");
1037       return 1;
1038     }
1039     if (val > NR_INSTANCES_MAX) {
1040       ERROR(PLUGIN_NAME " plugin: Instances=%f > NR_INSTANCES_MAX=%i"
1041                         " use a lower setting or recompile the plugin.",
1042             val, NR_INSTANCES_MAX);
1043       return 1;
1044     }
1045
1046     nr_instances = (int)val;
1047     DEBUG(PLUGIN_NAME " plugin: configured %i instances", nr_instances);
1048     return 0;
1049   }
1050
1051   if (strcasecmp(key, "ExtraStats") == 0) {
1052     char *localvalue = strdup(value);
1053     if (localvalue != NULL) {
1054       char *exstats[EX_STATS_MAX_FIELDS];
1055       int numexstats =
1056           strsplit(localvalue, exstats, STATIC_ARRAY_SIZE(exstats));
1057       extra_stats = parse_ex_stats_flags(exstats, numexstats);
1058       sfree(localvalue);
1059
1060 #ifdef HAVE_JOB_STATS
1061       if ((extra_stats & ex_stats_job_stats_completed) &&
1062           (extra_stats & ex_stats_job_stats_background)) {
1063         ERROR(PLUGIN_NAME " plugin: Invalid job stats configuration. Only one "
1064                           "type of job statistics can be collected at the same "
1065                           "time");
1066         return 1;
1067       }
1068 #endif
1069     }
1070   }
1071
1072   /* Unrecognised option. */
1073   return -1;
1074 }
1075
1076 static int lv_connect(void) {
1077   if (conn == NULL) {
1078 /* `conn_string == NULL' is acceptable */
1079 #ifdef HAVE_FS_INFO
1080     /* virDomainGetFSInfo requires full read-write access connection */
1081     if (extra_stats & ex_stats_fs_info)
1082       conn = virConnectOpen(conn_string);
1083     else
1084 #endif
1085       conn = virConnectOpenReadOnly(conn_string);
1086     if (conn == NULL) {
1087       c_complain(LOG_ERR, &conn_complain,
1088                  PLUGIN_NAME " plugin: Unable to connect: "
1089                              "virConnectOpen failed.");
1090       return -1;
1091     }
1092     int status = virNodeGetInfo(conn, &nodeinfo);
1093     if (status != 0) {
1094       ERROR(PLUGIN_NAME ": virNodeGetInfo failed");
1095       return -1;
1096     }
1097   }
1098   c_release(LOG_NOTICE, &conn_complain,
1099             PLUGIN_NAME " plugin: Connection established.");
1100   return 0;
1101 }
1102
1103 static void lv_disconnect(void) {
1104   if (conn != NULL)
1105     virConnectClose(conn);
1106   conn = NULL;
1107   WARNING(PLUGIN_NAME " plugin: closed connection to libvirt");
1108 }
1109
1110 static int lv_domain_block_info(virDomainPtr dom, const char *path,
1111                                 struct lv_block_info *binfo) {
1112 #ifdef HAVE_BLOCK_STATS_FLAGS
1113   int nparams = 0;
1114   if (virDomainBlockStatsFlags(dom, path, NULL, &nparams, 0) < 0 ||
1115       nparams <= 0) {
1116     VIRT_ERROR(conn, "getting the disk params count");
1117     return -1;
1118   }
1119
1120   virTypedParameterPtr params = calloc((size_t)nparams, sizeof(*params));
1121   if (params == NULL) {
1122     ERROR("virt plugin: alloc(%i) for block=%s parameters failed.", nparams,
1123           path);
1124     return -1;
1125   }
1126
1127   int rc = -1;
1128   if (virDomainBlockStatsFlags(dom, path, params, &nparams, 0) < 0) {
1129     VIRT_ERROR(conn, "getting the disk params values");
1130   } else {
1131     rc = get_block_info(binfo, params, nparams);
1132   }
1133
1134   virTypedParamsClear(params, nparams);
1135   sfree(params);
1136   return rc;
1137 #else
1138   return virDomainBlockStats(dom, path, &(binfo->bi), sizeof(binfo->bi));
1139 #endif /* HAVE_BLOCK_STATS_FLAGS */
1140 }
1141
1142 #ifdef HAVE_PERF_STATS
1143 static void perf_submit(virDomainStatsRecordPtr stats) {
1144   for (int i = 0; i < stats->nparams; ++i) {
1145     /* Replace '.' with '_' in event field to match other metrics' naming
1146      * convention */
1147     char *c = strchr(stats->params[i].field, '.');
1148     if (c)
1149       *c = '_';
1150     submit(stats->dom, "perf", stats->params[i].field,
1151            &(value_t){.derive = stats->params[i].value.ul}, 1);
1152   }
1153 }
1154
1155 static int get_perf_events(virDomainPtr domain) {
1156   virDomainStatsRecordPtr *stats = NULL;
1157   /* virDomainListGetStats requires a NULL terminated list of domains */
1158   virDomainPtr domain_array[] = {domain, NULL};
1159
1160   int status =
1161       virDomainListGetStats(domain_array, VIR_DOMAIN_STATS_PERF, &stats, 0);
1162   if (status == -1) {
1163     ERROR("virt plugin: virDomainListGetStats failed with status %i.", status);
1164     return status;
1165   }
1166
1167   for (int i = 0; i < status; ++i)
1168     perf_submit(stats[i]);
1169
1170   virDomainStatsRecordListFree(stats);
1171   return 0;
1172 }
1173 #endif /* HAVE_PERF_STATS */
1174
1175 static void vcpu_pin_submit(virDomainPtr dom, int max_cpus, int vcpu,
1176                             unsigned char *cpu_maps, int cpu_map_len) {
1177   for (int cpu = 0; cpu < max_cpus; ++cpu) {
1178     char type_instance[DATA_MAX_NAME_LEN];
1179     _Bool is_set = VIR_CPU_USABLE(cpu_maps, cpu_map_len, vcpu, cpu) ? 1 : 0;
1180
1181     snprintf(type_instance, sizeof(type_instance), "vcpu_%d-cpu_%d", vcpu, cpu);
1182     submit(dom, "cpu_affinity", type_instance, &(value_t){.gauge = is_set}, 1);
1183   }
1184 }
1185
1186 static int get_vcpu_stats(virDomainPtr domain, unsigned short nr_virt_cpu) {
1187   int max_cpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
1188   int cpu_map_len = VIR_CPU_MAPLEN(max_cpus);
1189
1190   virVcpuInfoPtr vinfo = calloc(nr_virt_cpu, sizeof(vinfo[0]));
1191   if (vinfo == NULL) {
1192     ERROR(PLUGIN_NAME " plugin: calloc failed.");
1193     return -1;
1194   }
1195
1196   unsigned char *cpumaps = calloc(nr_virt_cpu, cpu_map_len);
1197   if (cpumaps == NULL) {
1198     ERROR(PLUGIN_NAME " plugin: calloc failed.");
1199     sfree(vinfo);
1200     return -1;
1201   }
1202
1203   int status =
1204       virDomainGetVcpus(domain, vinfo, nr_virt_cpu, cpumaps, cpu_map_len);
1205   if (status < 0) {
1206     ERROR(PLUGIN_NAME " plugin: virDomainGetVcpus failed with status %i.",
1207           status);
1208     sfree(cpumaps);
1209     sfree(vinfo);
1210     return status;
1211   }
1212
1213   for (int i = 0; i < nr_virt_cpu; ++i) {
1214     vcpu_submit(vinfo[i].cpuTime, domain, vinfo[i].number, "virt_vcpu");
1215     if (extra_stats & ex_stats_vcpupin)
1216       vcpu_pin_submit(domain, max_cpus, i, cpumaps, cpu_map_len);
1217   }
1218
1219   sfree(cpumaps);
1220   sfree(vinfo);
1221   return 0;
1222 }
1223
1224 #ifdef HAVE_DOM_REASON
1225 static int get_domain_state(virDomainPtr domain) {
1226   int domain_state = 0;
1227   int domain_reason = 0;
1228
1229   int status = virDomainGetState(domain, &domain_state, &domain_reason, 0);
1230   if (status != 0) {
1231     ERROR(PLUGIN_NAME " plugin: virDomainGetState failed with status %i.",
1232           status);
1233     return status;
1234   }
1235
1236   domain_state_submit(domain, domain_state, domain_reason);
1237   return status;
1238 }
1239 #endif /* HAVE_DOM_REASON */
1240
1241 static int get_memory_stats(virDomainPtr domain) {
1242   virDomainMemoryStatPtr minfo =
1243       calloc(VIR_DOMAIN_MEMORY_STAT_NR, sizeof(virDomainMemoryStatStruct));
1244   if (minfo == NULL) {
1245     ERROR("virt plugin: malloc failed.");
1246     return -1;
1247   }
1248
1249   int mem_stats =
1250       virDomainMemoryStats(domain, minfo, VIR_DOMAIN_MEMORY_STAT_NR, 0);
1251   if (mem_stats < 0) {
1252     ERROR("virt plugin: virDomainMemoryStats failed with mem_stats %i.",
1253           mem_stats);
1254     sfree(minfo);
1255     return mem_stats;
1256   }
1257
1258   for (int i = 0; i < mem_stats; i++)
1259     memory_stats_submit((gauge_t)minfo[i].val * 1024, domain, minfo[i].tag);
1260
1261   sfree(minfo);
1262   return 0;
1263 }
1264
1265 #ifdef HAVE_DISK_ERR
1266 static void disk_err_submit(virDomainPtr domain,
1267                             virDomainDiskErrorPtr disk_err) {
1268   submit(domain, "disk_error", disk_err->disk,
1269          &(value_t){.gauge = disk_err->error}, 1);
1270 }
1271
1272 static int get_disk_err(virDomainPtr domain) {
1273   /* Get preferred size of disk errors array */
1274   int disk_err_count = virDomainGetDiskErrors(domain, NULL, 0, 0);
1275   if (disk_err_count == -1) {
1276     ERROR(PLUGIN_NAME
1277           " plugin: failed to get preferred size of disk errors array");
1278     return -1;
1279   }
1280
1281   DEBUG(PLUGIN_NAME
1282         " plugin: preferred size of disk errors array: %d for domain %s",
1283         disk_err_count, virDomainGetName(domain));
1284   virDomainDiskError disk_err[disk_err_count];
1285
1286   disk_err_count = virDomainGetDiskErrors(domain, disk_err, disk_err_count, 0);
1287   if (disk_err_count == -1) {
1288     ERROR(PLUGIN_NAME " plugin: virDomainGetDiskErrors failed with status %d",
1289           disk_err_count);
1290     return -1;
1291   }
1292
1293   DEBUG(PLUGIN_NAME " plugin: detected %d disk errors in domain %s",
1294         disk_err_count, virDomainGetName(domain));
1295
1296   for (int i = 0; i < disk_err_count; ++i) {
1297     disk_err_submit(domain, &disk_err[i]);
1298     sfree(disk_err[i].disk);
1299   }
1300
1301   return 0;
1302 }
1303 #endif /* HAVE_DISK_ERR */
1304
1305 static int get_block_stats(struct block_device *block_dev) {
1306
1307   if (!block_dev) {
1308     ERROR(PLUGIN_NAME " plugin: get_block_stats NULL pointer");
1309     return -1;
1310   }
1311
1312   struct lv_block_info binfo;
1313   init_block_info(&binfo);
1314
1315   if (lv_domain_block_info(block_dev->dom, block_dev->path, &binfo) < 0) {
1316     ERROR(PLUGIN_NAME " plugin: lv_domain_block_info failed");
1317     return -1;
1318   }
1319
1320   disk_submit(&binfo, block_dev->dom, block_dev->path);
1321   return 0;
1322 }
1323
1324 #ifdef HAVE_FS_INFO
1325
1326 #define NM_ADD_ITEM(_fun, _name, _val)                                         \
1327   do {                                                                         \
1328     ret = _fun(&notif, _name, _val);                                           \
1329     if (ret != 0) {                                                            \
1330       ERROR(PLUGIN_NAME " plugin: failed to add notification metadata");       \
1331       goto cleanup;                                                            \
1332     }                                                                          \
1333   } while (0)
1334
1335 #define NM_ADD_STR_ITEMS(_items, _size)                                        \
1336   do {                                                                         \
1337     for (int _i = 0; _i < _size; ++_i) {                                       \
1338       DEBUG(PLUGIN_NAME                                                        \
1339             " plugin: Adding notification metadata name=%s value=%s",          \
1340             _items[_i].name, _items[_i].value);                                \
1341       NM_ADD_ITEM(plugin_notification_meta_add_string, _items[_i].name,        \
1342                   _items[_i].value);                                           \
1343     }                                                                          \
1344   } while (0)
1345
1346 static int fs_info_notify(virDomainPtr domain, virDomainFSInfoPtr fs_info) {
1347   notification_t notif;
1348   int ret = 0;
1349
1350   /* Local struct, just for the purpose of this function. */
1351   typedef struct nm_str_item_s {
1352     const char *name;
1353     const char *value;
1354   } nm_str_item_t;
1355
1356   nm_str_item_t fs_dev_alias[fs_info->ndevAlias];
1357   nm_str_item_t fs_str_items[] = {
1358       {.name = "mountpoint", .value = fs_info->mountpoint},
1359       {.name = "name", .value = fs_info->name},
1360       {.name = "fstype", .value = fs_info->fstype}};
1361
1362   for (int i = 0; i < fs_info->ndevAlias; ++i) {
1363     fs_dev_alias[i].name = "devAlias";
1364     fs_dev_alias[i].value = fs_info->devAlias[i];
1365   }
1366
1367   init_notif(&notif, domain, NOTIF_OKAY, "File system information",
1368              "file_system", NULL);
1369   NM_ADD_STR_ITEMS(fs_str_items, STATIC_ARRAY_SIZE(fs_str_items));
1370   NM_ADD_ITEM(plugin_notification_meta_add_unsigned_int, "ndevAlias",
1371               fs_info->ndevAlias);
1372   NM_ADD_STR_ITEMS(fs_dev_alias, fs_info->ndevAlias);
1373
1374   plugin_dispatch_notification(&notif);
1375
1376 cleanup:
1377   if (notif.meta)
1378     plugin_notification_meta_free(notif.meta);
1379   return ret;
1380 }
1381
1382 #undef RETURN_ON_ERR
1383 #undef NM_ADD_STR_ITEMS
1384
1385 static int get_fs_info(virDomainPtr domain) {
1386   virDomainFSInfoPtr *fs_info = NULL;
1387   int ret = 0;
1388
1389   int mount_points_cnt = virDomainGetFSInfo(domain, &fs_info, 0);
1390   if (mount_points_cnt == -1) {
1391     ERROR(PLUGIN_NAME " plugin: virDomainGetFSInfo failed: %d",
1392           mount_points_cnt);
1393     return mount_points_cnt;
1394   }
1395
1396   for (int i = 0; i < mount_points_cnt; ++i) {
1397     if (fs_info_notify(domain, fs_info[i]) != 0) {
1398       ERROR(PLUGIN_NAME " plugin: failed to send file system notification "
1399                         "for mount point %s",
1400             fs_info[i]->mountpoint);
1401       ret = -1;
1402     }
1403     virDomainFSInfoFree(fs_info[i]);
1404   }
1405
1406   sfree(fs_info);
1407   return ret;
1408 }
1409
1410 #endif /* HAVE_FS_INFO */
1411
1412 #ifdef HAVE_JOB_STATS
1413 static void job_stats_submit(virDomainPtr domain, virTypedParameterPtr param) {
1414   value_t vl = {0};
1415
1416   if (param->type == VIR_TYPED_PARAM_INT)
1417     vl.derive = param->value.i;
1418   else if (param->type == VIR_TYPED_PARAM_UINT)
1419     vl.derive = param->value.ui;
1420   else if (param->type == VIR_TYPED_PARAM_LLONG)
1421     vl.derive = param->value.l;
1422   else if (param->type == VIR_TYPED_PARAM_ULLONG)
1423     vl.derive = param->value.ul;
1424   else if (param->type == VIR_TYPED_PARAM_DOUBLE)
1425     vl.derive = param->value.d;
1426   else if (param->type == VIR_TYPED_PARAM_BOOLEAN)
1427     vl.derive = param->value.b;
1428   else if (param->type == VIR_TYPED_PARAM_STRING) {
1429     submit_notif(domain, NOTIF_OKAY, param->value.s, "job_stats", param->field);
1430     return;
1431   } else {
1432     ERROR(PLUGIN_NAME " plugin: unrecognized virTypedParameterType");
1433     return;
1434   }
1435
1436   submit(domain, "job_stats", param->field, &vl, 1);
1437 }
1438
1439 static int get_job_stats(virDomainPtr domain) {
1440   int ret = 0;
1441   int job_type = 0;
1442   int nparams = 0;
1443   virTypedParameterPtr params = NULL;
1444   int flags = (extra_stats & ex_stats_job_stats_completed)
1445                   ? VIR_DOMAIN_JOB_STATS_COMPLETED
1446                   : 0;
1447
1448   ret = virDomainGetJobStats(domain, &job_type, &params, &nparams, flags);
1449   if (ret != 0) {
1450     ERROR(PLUGIN_NAME " plugin: virDomainGetJobStats failed: %d", ret);
1451     return ret;
1452   }
1453
1454   DEBUG(PLUGIN_NAME " plugin: job_type=%d nparams=%d", job_type, nparams);
1455
1456   for (int i = 0; i < nparams; ++i) {
1457     DEBUG(PLUGIN_NAME " plugin: param[%d] field=%s type=%d", i, params[i].field,
1458           params[i].type);
1459     job_stats_submit(domain, &params[i]);
1460   }
1461
1462   virTypedParamsFree(params, nparams);
1463   return ret;
1464 }
1465 #endif /* HAVE_JOB_STATS */
1466
1467 static int get_domain_metrics(domain_t *domain) {
1468   struct lv_info info;
1469
1470   if (!domain || !domain->ptr) {
1471     ERROR(PLUGIN_NAME ": get_domain_metrics: NULL pointer");
1472     return -1;
1473   }
1474
1475   init_lv_info(&info);
1476   int status = lv_domain_info(domain->ptr, &info);
1477   if (status != 0) {
1478     ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
1479           status);
1480     return -1;
1481   }
1482
1483   if (extra_stats & ex_stats_domain_state) {
1484 #ifdef HAVE_DOM_REASON
1485     /* At this point we already know domain's state from virDomainGetInfo call,
1486      * however it doesn't provide a reason for entering particular state.
1487      * We need to get it from virDomainGetState.
1488      */
1489     GET_STATS(get_domain_state, "domain reason", domain->ptr);
1490 #else
1491     /* virDomainGetState is not available. Submit 0, which corresponds to
1492      * unknown reason. */
1493     domain_state_submit(domain->ptr, info.di.state, 0);
1494 #endif
1495   }
1496
1497   /* Gather remaining stats only for running domains */
1498   if (info.di.state != VIR_DOMAIN_RUNNING)
1499     return 0;
1500
1501   pcpu_submit(domain->ptr, &info);
1502   cpu_submit(domain, info.di.cpuTime);
1503
1504   memory_submit(domain->ptr, (gauge_t)info.di.memory * 1024);
1505
1506   GET_STATS(get_vcpu_stats, "vcpu stats", domain->ptr, info.di.nrVirtCpu);
1507   GET_STATS(get_memory_stats, "memory stats", domain->ptr);
1508
1509 #ifdef HAVE_PERF_STATS
1510   if (extra_stats & ex_stats_perf)
1511     GET_STATS(get_perf_events, "performance monitoring events", domain->ptr);
1512 #endif
1513
1514 #ifdef HAVE_FS_INFO
1515   if (extra_stats & ex_stats_fs_info)
1516     GET_STATS(get_fs_info, "file system info", domain->ptr);
1517 #endif
1518
1519 #ifdef HAVE_DISK_ERR
1520   if (extra_stats & ex_stats_disk_err)
1521     GET_STATS(get_disk_err, "disk errors", domain->ptr);
1522 #endif
1523
1524 #ifdef HAVE_JOB_STATS
1525   if (extra_stats &
1526       (ex_stats_job_stats_completed | ex_stats_job_stats_background))
1527     GET_STATS(get_job_stats, "job stats", domain->ptr);
1528 #endif
1529
1530   /* Update cached virDomainInfo. It has to be done after cpu_submit */
1531   memcpy(&domain->info, &info.di, sizeof(domain->info));
1532   return 0;
1533 }
1534
1535 static int get_if_dev_stats(struct interface_device *if_dev) {
1536   virDomainInterfaceStatsStruct stats = {0};
1537   char *display_name = NULL;
1538
1539   if (!if_dev) {
1540     ERROR(PLUGIN_NAME " plugin: get_if_dev_stats: NULL pointer");
1541     return -1;
1542   }
1543
1544   switch (interface_format) {
1545   case if_address:
1546     display_name = if_dev->address;
1547     break;
1548   case if_number:
1549     display_name = if_dev->number;
1550     break;
1551   case if_name:
1552   default:
1553     display_name = if_dev->path;
1554   }
1555
1556   if (virDomainInterfaceStats(if_dev->dom, if_dev->path, &stats,
1557                               sizeof(stats)) != 0) {
1558     ERROR(PLUGIN_NAME " plugin: virDomainInterfaceStats failed");
1559     return -1;
1560   }
1561
1562   if ((stats.rx_bytes != -1) && (stats.tx_bytes != -1))
1563     submit_derive2("if_octets", (derive_t)stats.rx_bytes,
1564                    (derive_t)stats.tx_bytes, if_dev->dom, display_name);
1565
1566   if ((stats.rx_packets != -1) && (stats.tx_packets != -1))
1567     submit_derive2("if_packets", (derive_t)stats.rx_packets,
1568                    (derive_t)stats.tx_packets, if_dev->dom, display_name);
1569
1570   if ((stats.rx_errs != -1) && (stats.tx_errs != -1))
1571     submit_derive2("if_errors", (derive_t)stats.rx_errs,
1572                    (derive_t)stats.tx_errs, if_dev->dom, display_name);
1573
1574   if ((stats.rx_drop != -1) && (stats.tx_drop != -1))
1575     submit_derive2("if_dropped", (derive_t)stats.rx_drop,
1576                    (derive_t)stats.tx_drop, if_dev->dom, display_name);
1577   return 0;
1578 }
1579
1580 static int lv_read(user_data_t *ud) {
1581   time_t t;
1582   struct lv_read_instance *inst = NULL;
1583   struct lv_read_state *state = NULL;
1584
1585   if (ud->data == NULL) {
1586     ERROR(PLUGIN_NAME " plugin: NULL userdata");
1587     return -1;
1588   }
1589
1590   inst = ud->data;
1591   state = &inst->read_state;
1592
1593   if (inst->id == 0) {
1594     if (lv_connect() < 0)
1595       return -1;
1596   }
1597
1598   time(&t);
1599
1600   /* Need to refresh domain or device lists? */
1601   if ((last_refresh == (time_t)0) ||
1602       ((interval > 0) && ((last_refresh + interval) <= t))) {
1603     if (refresh_lists(inst) != 0) {
1604       if (inst->id == 0)
1605         lv_disconnect();
1606       return -1;
1607     }
1608     last_refresh = t;
1609   }
1610
1611 #if 0
1612     for (int i = 0; i < nr_domains; ++i)
1613         fprintf (stderr, "domain %s\n", virDomainGetName (state->domains[i].ptr));
1614     for (int i = 0; i < nr_block_devices; ++i)
1615         fprintf  (stderr, "block device %d %s:%s\n",
1616                   i, virDomainGetName (block_devices[i].dom),
1617                   block_devices[i].path);
1618     for (int i = 0; i < nr_interface_devices; ++i)
1619         fprintf (stderr, "interface device %d %s:%s\n",
1620                  i, virDomainGetName (interface_devices[i].dom),
1621                  interface_devices[i].path);
1622 #endif
1623
1624   /* Get domains' metrics */
1625   for (int i = 0; i < state->nr_domains; ++i) {
1626     int status = get_domain_metrics(&state->domains[i]);
1627     if (status != 0)
1628       ERROR(PLUGIN_NAME " failed to get metrics for domain=%s",
1629             virDomainGetName(state->domains[i].ptr));
1630   }
1631
1632   /* Get block device stats for each domain. */
1633   for (int i = 0; i < state->nr_block_devices; ++i) {
1634     int status = get_block_stats(&state->block_devices[i]);
1635     if (status != 0)
1636       ERROR(PLUGIN_NAME
1637             " failed to get stats for block device (%s) in domain %s",
1638             state->block_devices[i].path,
1639             virDomainGetName(state->block_devices[i].dom));
1640   }
1641
1642   /* Get interface stats for each domain. */
1643   for (int i = 0; i < state->nr_interface_devices; ++i) {
1644     int status = get_if_dev_stats(&state->interface_devices[i]);
1645     if (status != 0)
1646       ERROR(PLUGIN_NAME
1647             " failed to get interface stats for device (%s) in domain %s",
1648             state->interface_devices[i].path,
1649             virDomainGetName(state->interface_devices[i].dom));
1650   }
1651
1652   return 0;
1653 }
1654
1655 static int lv_init_instance(size_t i, plugin_read_cb callback) {
1656   struct lv_user_data *lv_ud = &(lv_read_user_data[i]);
1657   struct lv_read_instance *inst = &(lv_ud->inst);
1658
1659   memset(lv_ud, 0, sizeof(*lv_ud));
1660
1661   snprintf(inst->tag, sizeof(inst->tag), "%s-%zu", PLUGIN_NAME, i);
1662   inst->id = i;
1663
1664   user_data_t *ud = &(lv_ud->ud);
1665   ud->data = inst;
1666   ud->free_func = NULL;
1667
1668   INFO(PLUGIN_NAME " plugin: reader %s initialized", inst->tag);
1669   return plugin_register_complex_read(NULL, inst->tag, callback, 0, ud);
1670 }
1671
1672 static void lv_clean_read_state(struct lv_read_state *state) {
1673   free_block_devices(state);
1674   free_interface_devices(state);
1675   free_domains(state);
1676 }
1677
1678 static void lv_fini_instance(size_t i) {
1679   struct lv_read_instance *inst = &(lv_read_user_data[i].inst);
1680   struct lv_read_state *state = &(inst->read_state);
1681
1682   lv_clean_read_state(state);
1683   INFO(PLUGIN_NAME " plugin: reader %s finalized", inst->tag);
1684 }
1685
1686 static int lv_init(void) {
1687   if (virInitialize() != 0)
1688     return -1;
1689
1690   if (lv_connect() != 0)
1691     return -1;
1692
1693   DEBUG(PLUGIN_NAME " plugin: starting %i instances", nr_instances);
1694
1695   for (int i = 0; i < nr_instances; ++i)
1696     lv_init_instance(i, lv_read);
1697
1698   return 0;
1699 }
1700
1701 /*
1702  * returns 0 on success and <0 on error
1703  */
1704 static int lv_domain_get_tag(xmlXPathContextPtr xpath_ctx, const char *dom_name,
1705                              char *dom_tag) {
1706   char xpath_str[BUFFER_MAX_LEN] = {'\0'};
1707   xmlXPathObjectPtr xpath_obj = NULL;
1708   xmlNodePtr xml_node = NULL;
1709   int ret = -1;
1710   int err;
1711
1712   err = xmlXPathRegisterNs(xpath_ctx,
1713                            (const xmlChar *)METADATA_VM_PARTITION_PREFIX,
1714                            (const xmlChar *)METADATA_VM_PARTITION_URI);
1715   if (err) {
1716     ERROR(PLUGIN_NAME " plugin: xmlXpathRegisterNs(%s, %s) failed on domain %s",
1717           METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_URI, dom_name);
1718     goto done;
1719   }
1720
1721   snprintf(xpath_str, sizeof(xpath_str), "/domain/metadata/%s:%s/text()",
1722            METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_ELEMENT);
1723   xpath_obj = xmlXPathEvalExpression((xmlChar *)xpath_str, xpath_ctx);
1724   if (xpath_obj == NULL) {
1725     ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) failed on domain %s",
1726           xpath_str, dom_name);
1727     goto done;
1728   }
1729
1730   if (xpath_obj->type != XPATH_NODESET) {
1731     ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) unexpected return type %d "
1732                       "(wanted %d) on domain %s",
1733           xpath_str, xpath_obj->type, XPATH_NODESET, dom_name);
1734     goto done;
1735   }
1736
1737   /*
1738    * from now on there is no real error, it's ok if a domain
1739    * doesn't have the metadata partition tag.
1740    */
1741   ret = 0;
1742   if (xpath_obj->nodesetval == NULL || xpath_obj->nodesetval->nodeNr != 1) {
1743     DEBUG(PLUGIN_NAME " plugin: xmlXPathEval(%s) return nodeset size=%i "
1744                       "expected=1 on domain %s",
1745           xpath_str,
1746           (xpath_obj->nodesetval == NULL) ? 0 : xpath_obj->nodesetval->nodeNr,
1747           dom_name);
1748   } else {
1749     xml_node = xpath_obj->nodesetval->nodeTab[0];
1750     sstrncpy(dom_tag, (const char *)xml_node->content, PARTITION_TAG_MAX_LEN);
1751   }
1752
1753 done:
1754   /* deregister to clean up */
1755   err = xmlXPathRegisterNs(xpath_ctx,
1756                            (const xmlChar *)METADATA_VM_PARTITION_PREFIX, NULL);
1757   if (err) {
1758     /* we can't really recover here */
1759     ERROR(PLUGIN_NAME
1760           " plugin: deregistration of namespace %s failed for domain %s",
1761           METADATA_VM_PARTITION_PREFIX, dom_name);
1762   }
1763   if (xpath_obj)
1764     xmlXPathFreeObject(xpath_obj);
1765
1766   return ret;
1767 }
1768
1769 static int is_known_tag(const char *dom_tag) {
1770   for (int i = 0; i < nr_instances; ++i)
1771     if (!strcmp(dom_tag, lv_read_user_data[i].inst.tag))
1772       return 1;
1773   return 0;
1774 }
1775
1776 static int lv_instance_include_domain(struct lv_read_instance *inst,
1777                                       const char *dom_name,
1778                                       const char *dom_tag) {
1779   if ((dom_tag[0] != '\0') && (strcmp(dom_tag, inst->tag) == 0))
1780     return 1;
1781
1782   /* instance#0 will always be there, so it is in charge of extra duties */
1783   if (inst->id == 0) {
1784     if (dom_tag[0] == '\0' || !is_known_tag(dom_tag)) {
1785       DEBUG(PLUGIN_NAME " plugin#%s: refreshing domain %s "
1786                         "with unknown tag '%s'",
1787             inst->tag, dom_name, dom_tag);
1788       return 1;
1789     }
1790   }
1791
1792   return 0;
1793 }
1794
1795 /*
1796   virConnectListAllDomains() appeared in 0.10.2
1797   Note that LIBVIR_CHECK_VERSION appeared a year later, so
1798   in some systems which actually have virConnectListAllDomains()
1799   we can't detect this.
1800  */
1801 #ifdef LIBVIR_CHECK_VERSION
1802 #if LIBVIR_CHECK_VERSION(0, 10, 2)
1803 #define HAVE_LIST_ALL_DOMAINS 1
1804 #endif
1805 #endif
1806
1807 static int refresh_lists(struct lv_read_instance *inst) {
1808   struct lv_read_state *state = &inst->read_state;
1809   int n;
1810
1811   n = virConnectNumOfDomains(conn);
1812   if (n < 0) {
1813     VIRT_ERROR(conn, "reading number of domains");
1814     return -1;
1815   }
1816
1817   lv_clean_read_state(state);
1818
1819   if (n > 0) {
1820 #ifdef HAVE_LIST_ALL_DOMAINS
1821     virDomainPtr *domains;
1822     n = virConnectListAllDomains(conn, &domains,
1823                                  VIR_CONNECT_LIST_DOMAINS_ACTIVE);
1824 #else
1825     int *domids;
1826
1827     /* Get list of domains. */
1828     domids = malloc(sizeof(*domids) * n);
1829     if (domids == NULL) {
1830       ERROR(PLUGIN_NAME " plugin: malloc failed.");
1831       return -1;
1832     }
1833
1834     n = virConnectListDomains(conn, domids, n);
1835 #endif
1836
1837     if (n < 0) {
1838       VIRT_ERROR(conn, "reading list of domains");
1839 #ifndef HAVE_LIST_ALL_DOMAINS
1840       sfree(domids);
1841 #endif
1842       return -1;
1843     }
1844
1845     /* Fetch each domain and add it to the list, unless ignore. */
1846     for (int i = 0; i < n; ++i) {
1847       const char *name;
1848       char *xml = NULL;
1849       xmlDocPtr xml_doc = NULL;
1850       xmlXPathContextPtr xpath_ctx = NULL;
1851       xmlXPathObjectPtr xpath_obj = NULL;
1852       char tag[PARTITION_TAG_MAX_LEN] = {'\0'};
1853       virDomainInfo info;
1854       int status;
1855
1856 #ifdef HAVE_LIST_ALL_DOMAINS
1857       virDomainPtr dom = domains[i];
1858 #else
1859       virDomainPtr dom = NULL;
1860       dom = virDomainLookupByID(conn, domids[i]);
1861       if (dom == NULL) {
1862         VIRT_ERROR(conn, "virDomainLookupByID");
1863         /* Could be that the domain went away -- ignore it anyway. */
1864         continue;
1865       }
1866 #endif
1867
1868       name = virDomainGetName(dom);
1869       if (name == NULL) {
1870         VIRT_ERROR(conn, "virDomainGetName");
1871         goto cont;
1872       }
1873
1874       status = virDomainGetInfo(dom, &info);
1875       if (status != 0) {
1876         ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
1877               status);
1878         continue;
1879       }
1880
1881       if (info.state != VIR_DOMAIN_RUNNING) {
1882         DEBUG(PLUGIN_NAME " plugin: skipping inactive domain %s", name);
1883         continue;
1884       }
1885
1886       if (il_domains && ignorelist_match(il_domains, name) != 0)
1887         goto cont;
1888
1889       /* Get a list of devices for this domain. */
1890       xml = virDomainGetXMLDesc(dom, 0);
1891       if (!xml) {
1892         VIRT_ERROR(conn, "virDomainGetXMLDesc");
1893         goto cont;
1894       }
1895
1896       /* Yuck, XML.  Parse out the devices. */
1897       xml_doc = xmlReadDoc((xmlChar *)xml, NULL, NULL, XML_PARSE_NONET);
1898       if (xml_doc == NULL) {
1899         VIRT_ERROR(conn, "xmlReadDoc");
1900         goto cont;
1901       }
1902
1903       xpath_ctx = xmlXPathNewContext(xml_doc);
1904
1905       if (lv_domain_get_tag(xpath_ctx, name, tag) < 0) {
1906         ERROR(PLUGIN_NAME " plugin: lv_domain_get_tag failed.");
1907         goto cont;
1908       }
1909
1910       if (!lv_instance_include_domain(inst, name, tag))
1911         goto cont;
1912
1913       if (add_domain(state, dom) < 0) {
1914         ERROR(PLUGIN_NAME " plugin: malloc failed.");
1915         goto cont;
1916       }
1917
1918       /* Block devices. */
1919       const char *bd_xmlpath = "/domain/devices/disk/target[@dev]";
1920       if (blockdevice_format == source)
1921         bd_xmlpath = "/domain/devices/disk/source[@dev]";
1922       xpath_obj = xmlXPathEval((const xmlChar *)bd_xmlpath, xpath_ctx);
1923
1924       if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
1925           xpath_obj->nodesetval == NULL)
1926         goto cont;
1927
1928       for (int j = 0; j < xpath_obj->nodesetval->nodeNr; ++j) {
1929         xmlNodePtr node;
1930         char *path = NULL;
1931
1932         node = xpath_obj->nodesetval->nodeTab[j];
1933         if (!node)
1934           continue;
1935         path = (char *)xmlGetProp(node, (xmlChar *)"dev");
1936         if (!path)
1937           continue;
1938
1939         if (il_block_devices &&
1940             ignore_device_match(il_block_devices, name, path) != 0)
1941           goto cont2;
1942
1943         add_block_device(state, dom, path);
1944       cont2:
1945         if (path)
1946           xmlFree(path);
1947       }
1948       xmlXPathFreeObject(xpath_obj);
1949
1950       /* Network interfaces. */
1951       xpath_obj = xmlXPathEval(
1952           (xmlChar *)"/domain/devices/interface[target[@dev]]", xpath_ctx);
1953       if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
1954           xpath_obj->nodesetval == NULL)
1955         goto cont;
1956
1957       xmlNodeSetPtr xml_interfaces = xpath_obj->nodesetval;
1958
1959       for (int j = 0; j < xml_interfaces->nodeNr; ++j) {
1960         char *path = NULL;
1961         char *address = NULL;
1962         xmlNodePtr xml_interface;
1963
1964         xml_interface = xml_interfaces->nodeTab[j];
1965         if (!xml_interface)
1966           continue;
1967
1968         for (xmlNodePtr child = xml_interface->children; child;
1969              child = child->next) {
1970           if (child->type != XML_ELEMENT_NODE)
1971             continue;
1972
1973           if (xmlStrEqual(child->name, (const xmlChar *)"target")) {
1974             path = (char *)xmlGetProp(child, (const xmlChar *)"dev");
1975             if (!path)
1976               continue;
1977           } else if (xmlStrEqual(child->name, (const xmlChar *)"mac")) {
1978             address = (char *)xmlGetProp(child, (const xmlChar *)"address");
1979             if (!address)
1980               continue;
1981           }
1982         }
1983
1984         if (il_interface_devices &&
1985             (ignore_device_match(il_interface_devices, name, path) != 0 ||
1986              ignore_device_match(il_interface_devices, name, address) != 0))
1987           goto cont3;
1988
1989         add_interface_device(state, dom, path, address, j + 1);
1990       cont3:
1991         if (path)
1992           xmlFree(path);
1993         if (address)
1994           xmlFree(address);
1995       }
1996
1997     cont:
1998       if (xpath_obj)
1999         xmlXPathFreeObject(xpath_obj);
2000       if (xpath_ctx)
2001         xmlXPathFreeContext(xpath_ctx);
2002       if (xml_doc)
2003         xmlFreeDoc(xml_doc);
2004       sfree(xml);
2005     }
2006
2007 #ifdef HAVE_LIST_ALL_DOMAINS
2008     sfree(domains);
2009 #else
2010     sfree(domids);
2011 #endif
2012   }
2013
2014   DEBUG(PLUGIN_NAME " plugin#%s: refreshing"
2015                     " domains=%i block_devices=%i iface_devices=%i",
2016         inst->tag, state->nr_domains, state->nr_block_devices,
2017         state->nr_interface_devices);
2018
2019   return 0;
2020 }
2021
2022 static void free_domains(struct lv_read_state *state) {
2023   if (state->domains) {
2024     for (int i = 0; i < state->nr_domains; ++i)
2025       virDomainFree(state->domains[i].ptr);
2026     sfree(state->domains);
2027   }
2028   state->domains = NULL;
2029   state->nr_domains = 0;
2030 }
2031
2032 static int add_domain(struct lv_read_state *state, virDomainPtr dom) {
2033   domain_t *new_ptr;
2034   int new_size = sizeof(state->domains[0]) * (state->nr_domains + 1);
2035
2036   if (state->domains)
2037     new_ptr = realloc(state->domains, new_size);
2038   else
2039     new_ptr = malloc(new_size);
2040
2041   if (new_ptr == NULL)
2042     return -1;
2043
2044   state->domains = new_ptr;
2045   state->domains[state->nr_domains].ptr = dom;
2046   memset(&state->domains[state->nr_domains].info, 0,
2047          sizeof(state->domains[state->nr_domains].info));
2048
2049   return state->nr_domains++;
2050 }
2051
2052 static void free_block_devices(struct lv_read_state *state) {
2053   if (state->block_devices) {
2054     for (int i = 0; i < state->nr_block_devices; ++i)
2055       sfree(state->block_devices[i].path);
2056     sfree(state->block_devices);
2057   }
2058   state->block_devices = NULL;
2059   state->nr_block_devices = 0;
2060 }
2061
2062 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
2063                             const char *path) {
2064   struct block_device *new_ptr;
2065   int new_size =
2066       sizeof(state->block_devices[0]) * (state->nr_block_devices + 1);
2067   char *path_copy;
2068
2069   path_copy = strdup(path);
2070   if (!path_copy)
2071     return -1;
2072
2073   if (state->block_devices)
2074     new_ptr = realloc(state->block_devices, new_size);
2075   else
2076     new_ptr = malloc(new_size);
2077
2078   if (new_ptr == NULL) {
2079     sfree(path_copy);
2080     return -1;
2081   }
2082   state->block_devices = new_ptr;
2083   state->block_devices[state->nr_block_devices].dom = dom;
2084   state->block_devices[state->nr_block_devices].path = path_copy;
2085   return state->nr_block_devices++;
2086 }
2087
2088 static void free_interface_devices(struct lv_read_state *state) {
2089   if (state->interface_devices) {
2090     for (int i = 0; i < state->nr_interface_devices; ++i) {
2091       sfree(state->interface_devices[i].path);
2092       sfree(state->interface_devices[i].address);
2093       sfree(state->interface_devices[i].number);
2094     }
2095     sfree(state->interface_devices);
2096   }
2097   state->interface_devices = NULL;
2098   state->nr_interface_devices = 0;
2099 }
2100
2101 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
2102                                 const char *path, const char *address,
2103                                 unsigned int number) {
2104   struct interface_device *new_ptr;
2105   int new_size =
2106       sizeof(state->interface_devices[0]) * (state->nr_interface_devices + 1);
2107   char *path_copy, *address_copy, number_string[15];
2108
2109   if ((path == NULL) || (address == NULL))
2110     return EINVAL;
2111
2112   path_copy = strdup(path);
2113   if (!path_copy)
2114     return -1;
2115
2116   address_copy = strdup(address);
2117   if (!address_copy) {
2118     sfree(path_copy);
2119     return -1;
2120   }
2121
2122   snprintf(number_string, sizeof(number_string), "interface-%u", number);
2123
2124   if (state->interface_devices)
2125     new_ptr = realloc(state->interface_devices, new_size);
2126   else
2127     new_ptr = malloc(new_size);
2128
2129   if (new_ptr == NULL) {
2130     sfree(path_copy);
2131     sfree(address_copy);
2132     return -1;
2133   }
2134   state->interface_devices = new_ptr;
2135   state->interface_devices[state->nr_interface_devices].dom = dom;
2136   state->interface_devices[state->nr_interface_devices].path = path_copy;
2137   state->interface_devices[state->nr_interface_devices].address = address_copy;
2138   state->interface_devices[state->nr_interface_devices].number =
2139       strdup(number_string);
2140   return state->nr_interface_devices++;
2141 }
2142
2143 static int ignore_device_match(ignorelist_t *il, const char *domname,
2144                                const char *devpath) {
2145   char *name;
2146   int n, r;
2147
2148   if ((domname == NULL) || (devpath == NULL))
2149     return 0;
2150
2151   n = strlen(domname) + strlen(devpath) + 2;
2152   name = malloc(n);
2153   if (name == NULL) {
2154     ERROR(PLUGIN_NAME " plugin: malloc failed.");
2155     return 0;
2156   }
2157   snprintf(name, n, "%s:%s", domname, devpath);
2158   r = ignorelist_match(il, name);
2159   sfree(name);
2160   return r;
2161 }
2162
2163 static int lv_shutdown(void) {
2164   for (int i = 0; i < nr_instances; ++i) {
2165     lv_fini_instance(i);
2166   }
2167
2168   lv_disconnect();
2169
2170   ignorelist_free(il_domains);
2171   il_domains = NULL;
2172   ignorelist_free(il_block_devices);
2173   il_block_devices = NULL;
2174   ignorelist_free(il_interface_devices);
2175   il_interface_devices = NULL;
2176
2177   return 0;
2178 }
2179
2180 void module_register(void) {
2181   plugin_register_config(PLUGIN_NAME, lv_config, config_keys, NR_CONFIG_KEYS);
2182   plugin_register_init(PLUGIN_NAME, lv_init);
2183   plugin_register_shutdown(PLUGIN_NAME, lv_shutdown);
2184 }