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