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