Fix compile time issues
[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 "plugin.h"
26 #include "utils/common/common.h"
27 #include "utils/ignorelist/ignorelist.h"
28 #include "utils_complain.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 #include <stdbool.h>
38
39 /* Plugin name */
40 #define PLUGIN_NAME "virt"
41
42 /* Secure strcat macro assuring null termination. Parameter (n) is the size of
43    buffer (d), allowing this macro to be safe for static and dynamic buffers */
44 #define SSTRNCAT(d, s, n)                                                      \
45   do {                                                                         \
46     size_t _l = strlen(d);                                                     \
47     sstrncpy((d) + _l, (s), (n)-_l);                                           \
48   } while (0)
49
50 #ifdef LIBVIR_CHECK_VERSION
51
52 #if LIBVIR_CHECK_VERSION(0, 9, 2)
53 #define HAVE_DOM_REASON 1
54 #endif
55
56 #if LIBVIR_CHECK_VERSION(0, 9, 5)
57 #define HAVE_BLOCK_STATS_FLAGS 1
58 #define HAVE_DOM_REASON_PAUSED_SHUTTING_DOWN 1
59 #endif
60
61 #if LIBVIR_CHECK_VERSION(0, 9, 10)
62 #define HAVE_DISK_ERR 1
63 #endif
64
65 #if LIBVIR_CHECK_VERSION(0, 9, 11)
66 #define HAVE_CPU_STATS 1
67 #define HAVE_DOM_STATE_PMSUSPENDED 1
68 #define HAVE_DOM_REASON_RUNNING_WAKEUP 1
69 #endif
70
71 /*
72   virConnectListAllDomains() appeared in 0.10.2 (Sep 2012)
73   Note that LIBVIR_CHECK_VERSION appeared a year later (Dec 2013,
74   libvirt-1.2.0),
75   so in some systems which actually have virConnectListAllDomains()
76   we can't detect this.
77  */
78 #if LIBVIR_CHECK_VERSION(0, 10, 2)
79 #define HAVE_LIST_ALL_DOMAINS 1
80 #endif
81
82 #if LIBVIR_CHECK_VERSION(1, 0, 1)
83 #define HAVE_DOM_REASON_PAUSED_SNAPSHOT 1
84 #endif
85
86 #if LIBVIR_CHECK_VERSION(1, 1, 1)
87 #define HAVE_DOM_REASON_PAUSED_CRASHED 1
88 #endif
89
90 #if LIBVIR_CHECK_VERSION(1, 2, 9)
91 #define HAVE_JOB_STATS 1
92 #endif
93
94 #if LIBVIR_CHECK_VERSION(1, 2, 10)
95 #define HAVE_DOM_REASON_CRASHED 1
96 #endif
97
98 #if LIBVIR_CHECK_VERSION(1, 2, 11)
99 #define HAVE_FS_INFO 1
100 #endif
101
102 #if LIBVIR_CHECK_VERSION(1, 2, 15)
103 #define HAVE_DOM_REASON_PAUSED_STARTING_UP 1
104 #endif
105
106 #if LIBVIR_CHECK_VERSION(1, 3, 3)
107 #define HAVE_PERF_STATS 1
108 #define HAVE_DOM_REASON_POSTCOPY 1
109 #endif
110
111 #if LIBVIR_CHECK_VERSION(4, 10, 0)
112 #define HAVE_DOM_REASON_SHUTOFF_DAEMON 1
113 #endif
114 #endif /* LIBVIR_CHECK_VERSION */
115
116 /* structure used for aggregating notification-thread data*/
117 typedef struct virt_notif_thread_s {
118   pthread_t event_loop_tid;
119   int domain_event_cb_id;
120   pthread_mutex_t active_mutex; /* protects 'is_active' member access*/
121   bool is_active;
122 } virt_notif_thread_t;
123
124 /* PersistentNotification is false by default */
125 static bool persistent_notification = false;
126
127 static bool report_block_devices = true;
128 static bool report_network_interfaces = true;
129
130 /* Thread used for handling libvirt notifications events */
131 static virt_notif_thread_t notif_thread;
132
133 const char *domain_states[] = {
134     [VIR_DOMAIN_NOSTATE] = "no state",
135     [VIR_DOMAIN_RUNNING] = "the domain is running",
136     [VIR_DOMAIN_BLOCKED] = "the domain is blocked on resource",
137     [VIR_DOMAIN_PAUSED] = "the domain is paused by user",
138     [VIR_DOMAIN_SHUTDOWN] = "the domain is being shut down",
139     [VIR_DOMAIN_SHUTOFF] = "the domain is shut off",
140     [VIR_DOMAIN_CRASHED] = "the domain is crashed",
141 #ifdef HAVE_DOM_STATE_PMSUSPENDED
142     [VIR_DOMAIN_PMSUSPENDED] =
143         "the domain is suspended by guest power management",
144 #endif
145 };
146
147 static int map_domain_event_to_state(int event) {
148   int ret;
149   switch (event) {
150   case VIR_DOMAIN_EVENT_STARTED:
151     ret = VIR_DOMAIN_RUNNING;
152     break;
153   case VIR_DOMAIN_EVENT_SUSPENDED:
154     ret = VIR_DOMAIN_PAUSED;
155     break;
156   case VIR_DOMAIN_EVENT_RESUMED:
157     ret = VIR_DOMAIN_RUNNING;
158     break;
159   case VIR_DOMAIN_EVENT_STOPPED:
160     ret = VIR_DOMAIN_SHUTOFF;
161     break;
162   case VIR_DOMAIN_EVENT_SHUTDOWN:
163     ret = VIR_DOMAIN_SHUTDOWN;
164     break;
165 #ifdef HAVE_DOM_STATE_PMSUSPENDED
166   case VIR_DOMAIN_EVENT_PMSUSPENDED:
167     ret = VIR_DOMAIN_PMSUSPENDED;
168     break;
169 #endif
170 #ifdef HAVE_DOM_REASON_CRASHED
171   case VIR_DOMAIN_EVENT_CRASHED:
172     ret = VIR_DOMAIN_CRASHED;
173     break;
174 #endif
175   default:
176     ret = VIR_DOMAIN_NOSTATE;
177   }
178   return ret;
179 }
180
181 #ifdef HAVE_DOM_REASON
182 static int map_domain_event_detail_to_reason(int event, int detail) {
183   int ret;
184   switch (event) {
185   case VIR_DOMAIN_EVENT_STARTED:
186     switch (detail) {
187     case VIR_DOMAIN_EVENT_STARTED_BOOTED: /* Normal startup from boot */
188       ret = VIR_DOMAIN_RUNNING_BOOTED;
189       break;
190     case VIR_DOMAIN_EVENT_STARTED_MIGRATED: /* Incoming migration from another
191                                                host */
192       ret = VIR_DOMAIN_RUNNING_MIGRATED;
193       break;
194     case VIR_DOMAIN_EVENT_STARTED_RESTORED: /* Restored from a state file */
195       ret = VIR_DOMAIN_RUNNING_RESTORED;
196       break;
197     case VIR_DOMAIN_EVENT_STARTED_FROM_SNAPSHOT: /* Restored from snapshot */
198       ret = VIR_DOMAIN_RUNNING_FROM_SNAPSHOT;
199       break;
200 #ifdef HAVE_DOM_REASON_RUNNING_WAKEUP
201     case VIR_DOMAIN_EVENT_STARTED_WAKEUP: /* Started due to wakeup event */
202       ret = VIR_DOMAIN_RUNNING_WAKEUP;
203       break;
204 #endif
205     default:
206       ret = VIR_DOMAIN_RUNNING_UNKNOWN;
207     }
208     break;
209   case VIR_DOMAIN_EVENT_SUSPENDED:
210     switch (detail) {
211     case VIR_DOMAIN_EVENT_SUSPENDED_PAUSED: /* Normal suspend due to admin
212                                                pause */
213       ret = VIR_DOMAIN_PAUSED_USER;
214       break;
215     case VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED: /* Suspended for offline
216                                                  migration */
217       ret = VIR_DOMAIN_PAUSED_MIGRATION;
218       break;
219     case VIR_DOMAIN_EVENT_SUSPENDED_IOERROR: /* Suspended due to a disk I/O
220                                                 error */
221       ret = VIR_DOMAIN_PAUSED_IOERROR;
222       break;
223     case VIR_DOMAIN_EVENT_SUSPENDED_WATCHDOG: /* Suspended due to a watchdog
224                                                  firing */
225       ret = VIR_DOMAIN_PAUSED_WATCHDOG;
226       break;
227     case VIR_DOMAIN_EVENT_SUSPENDED_RESTORED: /* Restored from paused state
228                                                  file */
229       ret = VIR_DOMAIN_PAUSED_UNKNOWN;
230       break;
231     case VIR_DOMAIN_EVENT_SUSPENDED_FROM_SNAPSHOT: /* Restored from paused
232                                                       snapshot */
233       ret = VIR_DOMAIN_PAUSED_FROM_SNAPSHOT;
234       break;
235     case VIR_DOMAIN_EVENT_SUSPENDED_API_ERROR: /* Suspended after failure during
236                                                   libvirt API call */
237       ret = VIR_DOMAIN_PAUSED_UNKNOWN;
238       break;
239 #ifdef HAVE_DOM_REASON_POSTCOPY
240     case VIR_DOMAIN_EVENT_SUSPENDED_POSTCOPY: /* Suspended for post-copy
241                                                  migration */
242       ret = VIR_DOMAIN_PAUSED_POSTCOPY;
243       break;
244     case VIR_DOMAIN_EVENT_SUSPENDED_POSTCOPY_FAILED: /* Suspended after failed
245                                                         post-copy */
246       ret = VIR_DOMAIN_PAUSED_POSTCOPY_FAILED;
247       break;
248 #endif
249     default:
250       ret = VIR_DOMAIN_PAUSED_UNKNOWN;
251     }
252     break;
253   case VIR_DOMAIN_EVENT_RESUMED:
254     switch (detail) {
255     case VIR_DOMAIN_EVENT_RESUMED_UNPAUSED: /* Normal resume due to admin
256                                                unpause */
257       ret = VIR_DOMAIN_RUNNING_UNPAUSED;
258       break;
259     case VIR_DOMAIN_EVENT_RESUMED_MIGRATED: /* Resumed for completion of
260                                                migration */
261       ret = VIR_DOMAIN_RUNNING_MIGRATED;
262       break;
263     case VIR_DOMAIN_EVENT_RESUMED_FROM_SNAPSHOT: /* Resumed from snapshot */
264       ret = VIR_DOMAIN_RUNNING_FROM_SNAPSHOT;
265       break;
266 #ifdef HAVE_DOM_REASON_POSTCOPY
267     case VIR_DOMAIN_EVENT_RESUMED_POSTCOPY: /* Resumed, but migration is still
268                                                running in post-copy mode */
269       ret = VIR_DOMAIN_RUNNING_POSTCOPY;
270       break;
271 #endif
272     default:
273       ret = VIR_DOMAIN_RUNNING_UNKNOWN;
274     }
275     break;
276   case VIR_DOMAIN_EVENT_STOPPED:
277     switch (detail) {
278     case VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN: /* Normal shutdown */
279       ret = VIR_DOMAIN_SHUTOFF_SHUTDOWN;
280       break;
281     case VIR_DOMAIN_EVENT_STOPPED_DESTROYED: /* Forced poweroff from host */
282       ret = VIR_DOMAIN_SHUTOFF_DESTROYED;
283       break;
284     case VIR_DOMAIN_EVENT_STOPPED_CRASHED: /* Guest crashed */
285       ret = VIR_DOMAIN_SHUTOFF_CRASHED;
286       break;
287     case VIR_DOMAIN_EVENT_STOPPED_MIGRATED: /* Migrated off to another host */
288       ret = VIR_DOMAIN_SHUTOFF_MIGRATED;
289       break;
290     case VIR_DOMAIN_EVENT_STOPPED_SAVED: /* Saved to a state file */
291       ret = VIR_DOMAIN_SHUTOFF_SAVED;
292       break;
293     case VIR_DOMAIN_EVENT_STOPPED_FAILED: /* Host emulator/mgmt failed */
294       ret = VIR_DOMAIN_SHUTOFF_FAILED;
295       break;
296     case VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT: /* Offline snapshot loaded */
297       ret = VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT;
298       break;
299     default:
300       ret = VIR_DOMAIN_SHUTOFF_UNKNOWN;
301     }
302     break;
303   case VIR_DOMAIN_EVENT_SHUTDOWN:
304     switch (detail) {
305     case VIR_DOMAIN_EVENT_SHUTDOWN_FINISHED: /* Guest finished shutdown
306                                                 sequence */
307 #ifdef LIBVIR_CHECK_VERSION
308 #if LIBVIR_CHECK_VERSION(3, 4, 0)
309     case VIR_DOMAIN_EVENT_SHUTDOWN_GUEST: /* Domain finished shutting down after
310                                              request from the guest itself (e.g.
311                                              hardware-specific action) */
312     case VIR_DOMAIN_EVENT_SHUTDOWN_HOST:  /* Domain finished shutting down after
313                                              request from the host (e.g. killed
314                                              by a signal) */
315 #endif
316 #endif
317       ret = VIR_DOMAIN_SHUTDOWN_USER;
318       break;
319     default:
320       ret = VIR_DOMAIN_SHUTDOWN_UNKNOWN;
321     }
322     break;
323 #ifdef HAVE_DOM_STATE_PMSUSPENDED
324   case VIR_DOMAIN_EVENT_PMSUSPENDED:
325     switch (detail) {
326     case VIR_DOMAIN_EVENT_PMSUSPENDED_MEMORY: /* Guest was PM suspended to
327                                                  memory */
328       ret = VIR_DOMAIN_PMSUSPENDED_UNKNOWN;
329       break;
330     case VIR_DOMAIN_EVENT_PMSUSPENDED_DISK: /* Guest was PM suspended to disk */
331       ret = VIR_DOMAIN_PMSUSPENDED_DISK_UNKNOWN;
332       break;
333     default:
334       ret = VIR_DOMAIN_PMSUSPENDED_UNKNOWN;
335     }
336     break;
337 #endif
338   case VIR_DOMAIN_EVENT_CRASHED:
339     switch (detail) {
340     case VIR_DOMAIN_EVENT_CRASHED_PANICKED: /* Guest was panicked */
341       ret = VIR_DOMAIN_CRASHED_PANICKED;
342       break;
343     default:
344       ret = VIR_DOMAIN_CRASHED_UNKNOWN;
345     }
346     break;
347   default:
348     ret = VIR_DOMAIN_NOSTATE_UNKNOWN;
349   }
350   return ret;
351 }
352
353 #define DOMAIN_STATE_REASON_MAX_SIZE 20
354 const char *domain_reasons[][DOMAIN_STATE_REASON_MAX_SIZE] = {
355     [VIR_DOMAIN_NOSTATE][VIR_DOMAIN_NOSTATE_UNKNOWN] = "the reason is unknown",
356
357     [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_UNKNOWN] = "the reason is unknown",
358     [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_BOOTED] =
359         "normal startup from boot",
360     [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_MIGRATED] =
361         "migrated from another host",
362     [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_RESTORED] =
363         "restored from a state file",
364     [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_FROM_SNAPSHOT] =
365         "restored from snapshot",
366     [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_UNPAUSED] =
367         "returned from paused state",
368     [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_MIGRATION_CANCELED] =
369         "returned from migration",
370     [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_SAVE_CANCELED] =
371         "returned from failed save process",
372 #ifdef HAVE_DOM_REASON_RUNNING_WAKEUP
373     [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_WAKEUP] =
374         "returned from pmsuspended due to wakeup event",
375 #endif
376 #ifdef HAVE_DOM_REASON_CRASHED
377     [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_CRASHED] = "resumed from crashed",
378 #endif
379 #ifdef HAVE_DOM_REASON_POSTCOPY
380     [VIR_DOMAIN_RUNNING][VIR_DOMAIN_RUNNING_POSTCOPY] =
381         "running in post-copy migration mode",
382 #endif
383     [VIR_DOMAIN_BLOCKED][VIR_DOMAIN_BLOCKED_UNKNOWN] = "the reason is unknown",
384
385     [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_UNKNOWN] = "the reason is unknown",
386     [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_USER] = "paused on user request",
387     [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_MIGRATION] =
388         "paused for offline migration",
389     [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_SAVE] = "paused for save",
390     [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_DUMP] =
391         "paused for offline core dump",
392     [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_IOERROR] =
393         "paused due to a disk I/O error",
394     [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_WATCHDOG] =
395         "paused due to a watchdog event",
396     [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_FROM_SNAPSHOT] =
397         "paused after restoring from snapshot",
398 #ifdef HAVE_DOM_REASON_PAUSED_SHUTTING_DOWN
399     [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_SHUTTING_DOWN] =
400         "paused during shutdown process",
401 #endif
402 #ifdef HAVE_DOM_REASON_PAUSED_SNAPSHOT
403     [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_SNAPSHOT] =
404         "paused while creating a snapshot",
405 #endif
406 #ifdef HAVE_DOM_REASON_PAUSED_CRASHED
407     [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_CRASHED] =
408         "paused due to a guest crash",
409 #endif
410 #ifdef HAVE_DOM_REASON_PAUSED_STARTING_UP
411     [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_STARTING_UP] =
412         "the domain is being started",
413 #endif
414 #ifdef HAVE_DOM_REASON_POSTCOPY
415     [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_POSTCOPY] =
416         "paused for post-copy migration",
417     [VIR_DOMAIN_PAUSED][VIR_DOMAIN_PAUSED_POSTCOPY_FAILED] =
418         "paused after failed post-copy",
419 #endif
420     [VIR_DOMAIN_SHUTDOWN][VIR_DOMAIN_SHUTDOWN_UNKNOWN] =
421         "the reason is unknown",
422     [VIR_DOMAIN_SHUTDOWN][VIR_DOMAIN_SHUTDOWN_USER] =
423         "shutting down on user request",
424
425     [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_UNKNOWN] = "the reason is unknown",
426     [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_SHUTDOWN] = "normal shutdown",
427     [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_DESTROYED] = "forced poweroff",
428     [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_CRASHED] = "domain crashed",
429     [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_MIGRATED] =
430         "migrated to another host",
431     [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_SAVED] = "saved to a file",
432     [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_FAILED] = "domain failed to start",
433     [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_FROM_SNAPSHOT] =
434         "restored from a snapshot which was taken while domain was shutoff",
435 #ifdef HAVE_DOM_REASON_SHUTOFF_DAEMON
436     [VIR_DOMAIN_SHUTOFF][VIR_DOMAIN_SHUTOFF_DAEMON] =
437         "daemon decides to kill domain during reconnection processing",
438 #endif
439
440     [VIR_DOMAIN_CRASHED][VIR_DOMAIN_CRASHED_UNKNOWN] = "the reason is unknown",
441 #ifdef VIR_DOMAIN_CRASHED_PANICKED
442     [VIR_DOMAIN_CRASHED][VIR_DOMAIN_CRASHED_PANICKED] = "domain panicked",
443 #endif
444
445 #ifdef HAVE_DOM_STATE_PMSUSPENDED
446     [VIR_DOMAIN_PMSUSPENDED][VIR_DOMAIN_PMSUSPENDED_UNKNOWN] =
447         "the reason is unknown",
448 #endif
449 };
450 #endif /* HAVE_DOM_REASON */
451
452 #define NANOSEC_IN_SEC 1e9
453
454 #define GET_STATS(_f, _name, ...)                                              \
455   do {                                                                         \
456     status = _f(__VA_ARGS__);                                                  \
457     if (status != 0)                                                           \
458       ERROR(PLUGIN_NAME " plugin: Failed to get " _name);                      \
459   } while (0)
460
461 /* Connection. */
462 static virConnectPtr conn;
463 static char *conn_string;
464 static c_complain_t conn_complain = C_COMPLAIN_INIT_STATIC;
465
466 /* Node information required for %CPU */
467 static virNodeInfo nodeinfo;
468
469 /* Seconds between list refreshes, 0 disables completely. */
470 static int interval = 60;
471
472 /* List of domains, if specified. */
473 static ignorelist_t *il_domains;
474 /* List of block devices, if specified. */
475 static ignorelist_t *il_block_devices;
476 /* List of network interface devices, if specified. */
477 static ignorelist_t *il_interface_devices;
478
479 static int ignore_device_match(ignorelist_t *, const char *domname,
480                                const char *devpath);
481
482 /* Actual list of block devices found on last refresh. */
483 struct block_device {
484   virDomainPtr dom; /* domain */
485   char *path;       /* name of block device */
486   bool has_source;  /* information whether source is defined or not */
487 };
488
489 /* Actual list of network interfaces found on last refresh. */
490 struct interface_device {
491   virDomainPtr dom; /* domain */
492   char *path;       /* name of interface device */
493   char *address;    /* mac address of interface device */
494   char *number;     /* interface device number */
495 };
496
497 typedef struct domain_s {
498   virDomainPtr ptr;
499   virDomainInfo info;
500   bool active;
501 } domain_t;
502
503 struct lv_read_state {
504   /* Actual list of domains found on last refresh. */
505   domain_t *domains;
506   int nr_domains;
507
508   struct block_device *block_devices;
509   int nr_block_devices;
510
511   struct interface_device *interface_devices;
512   int nr_interface_devices;
513 };
514
515 static void free_domains(struct lv_read_state *state);
516 static int add_domain(struct lv_read_state *state, virDomainPtr dom,
517                       bool active);
518
519 static void free_block_devices(struct lv_read_state *state);
520 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
521                             const char *path, bool has_source);
522
523 static void free_interface_devices(struct lv_read_state *state);
524 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
525                                 const char *path, const char *address,
526                                 unsigned int number);
527
528 #define METADATA_VM_PARTITION_URI "http://ovirt.org/ovirtmap/tag/1.0"
529 #define METADATA_VM_PARTITION_ELEMENT "tag"
530 #define METADATA_VM_PARTITION_PREFIX "ovirtmap"
531
532 #define BUFFER_MAX_LEN 256
533 #define PARTITION_TAG_MAX_LEN 32
534
535 struct lv_read_instance {
536   struct lv_read_state read_state;
537   char tag[PARTITION_TAG_MAX_LEN];
538   size_t id;
539 };
540
541 struct lv_user_data {
542   struct lv_read_instance inst;
543   user_data_t ud;
544 };
545
546 #define NR_INSTANCES_DEFAULT 1
547 #define NR_INSTANCES_MAX 128
548 static int nr_instances = NR_INSTANCES_DEFAULT;
549 static struct lv_user_data lv_read_user_data[NR_INSTANCES_MAX];
550
551 /* HostnameFormat. */
552 #define HF_MAX_FIELDS 4
553
554 enum hf_field { hf_none = 0, hf_hostname, hf_name, hf_uuid, hf_metadata };
555
556 static enum hf_field hostname_format[HF_MAX_FIELDS] = {hf_name};
557
558 /* PluginInstanceFormat */
559 #define PLGINST_MAX_FIELDS 3
560
561 enum plginst_field {
562   plginst_none = 0,
563   plginst_name,
564   plginst_uuid,
565   plginst_metadata
566 };
567
568 static enum plginst_field plugin_instance_format[PLGINST_MAX_FIELDS] = {
569     plginst_none};
570
571 /* HostnameMetadataNS && HostnameMetadataXPath */
572 static char *hm_xpath;
573 static char *hm_ns;
574
575 /* BlockDeviceFormat */
576 enum bd_field { target, source };
577
578 /* InterfaceFormat. */
579 enum if_field { if_address, if_name, if_number };
580
581 /* ExtraStats */
582 #define EX_STATS_MAX_FIELDS 15
583 enum ex_stats {
584   ex_stats_none = 0,
585   ex_stats_disk = 1 << 0,
586   ex_stats_pcpu = 1 << 1,
587   ex_stats_cpu_util = 1 << 2,
588   ex_stats_domain_state = 1 << 3,
589 #ifdef HAVE_PERF_STATS
590   ex_stats_perf = 1 << 4,
591 #endif
592   ex_stats_vcpupin = 1 << 5,
593 #ifdef HAVE_DISK_ERR
594   ex_stats_disk_err = 1 << 6,
595 #endif
596 #ifdef HAVE_FS_INFO
597   ex_stats_fs_info = 1 << 7,
598 #endif
599 #ifdef HAVE_JOB_STATS
600   ex_stats_job_stats_completed = 1 << 8,
601   ex_stats_job_stats_background = 1 << 9,
602 #endif
603   ex_stats_disk_allocation = 1 << 10,
604   ex_stats_disk_capacity = 1 << 11,
605   ex_stats_disk_physical = 1 << 12,
606   ex_stats_memory = 1 << 13,
607   ex_stats_vcpu = 1 << 14
608 };
609
610 static unsigned int extra_stats = ex_stats_none;
611
612 struct ex_stats_item {
613   const char *name;
614   enum ex_stats flag;
615 };
616 static const struct ex_stats_item ex_stats_table[] = {
617     {"disk", ex_stats_disk},
618     {"pcpu", ex_stats_pcpu},
619     {"cpu_util", ex_stats_cpu_util},
620     {"domain_state", ex_stats_domain_state},
621 #ifdef HAVE_PERF_STATS
622     {"perf", ex_stats_perf},
623 #endif
624     {"vcpupin", ex_stats_vcpupin},
625 #ifdef HAVE_DISK_ERR
626     {"disk_err", ex_stats_disk_err},
627 #endif
628 #ifdef HAVE_FS_INFO
629     {"fs_info", ex_stats_fs_info},
630 #endif
631 #ifdef HAVE_JOB_STATS
632     {"job_stats_completed", ex_stats_job_stats_completed},
633     {"job_stats_background", ex_stats_job_stats_background},
634 #endif
635     {"disk_allocation", ex_stats_disk_allocation},
636     {"disk_capacity", ex_stats_disk_capacity},
637     {"disk_physical", ex_stats_disk_physical},
638     {"memory", ex_stats_memory},
639     {"vcpu", ex_stats_vcpu},
640     {NULL, ex_stats_none},
641 };
642
643 /* BlockDeviceFormatBasename */
644 static bool blockdevice_format_basename;
645 static enum bd_field blockdevice_format = target;
646 static enum if_field interface_format = if_name;
647
648 /* Time that we last refreshed. */
649 static time_t last_refresh = (time_t)0;
650
651 static int refresh_lists(struct lv_read_instance *inst);
652 static int register_event_impl(void);
653 static int start_event_loop(virt_notif_thread_t *thread_data);
654
655 struct lv_block_stats {
656   virDomainBlockStatsStruct bi;
657
658   long long rd_total_times;
659   long long wr_total_times;
660
661   long long fl_req;
662   long long fl_total_times;
663 };
664
665 static void init_block_stats(struct lv_block_stats *bstats) {
666   if (bstats == NULL)
667     return;
668
669   bstats->bi.rd_req = -1;
670   bstats->bi.wr_req = -1;
671   bstats->bi.rd_bytes = -1;
672   bstats->bi.wr_bytes = -1;
673
674   bstats->rd_total_times = -1;
675   bstats->wr_total_times = -1;
676   bstats->fl_req = -1;
677   bstats->fl_total_times = -1;
678 }
679
680 static void init_block_info(virDomainBlockInfoPtr binfo) {
681   binfo->allocation = -1;
682   binfo->capacity = -1;
683   binfo->physical = -1;
684 }
685
686 #ifdef HAVE_BLOCK_STATS_FLAGS
687
688 #define GET_BLOCK_STATS_VALUE(NAME, FIELD)                                     \
689   if (!strcmp(param[i].field, NAME)) {                                         \
690     bstats->FIELD = param[i].value.l;                                          \
691     continue;                                                                  \
692   }
693
694 static int get_block_stats(struct lv_block_stats *bstats,
695                            virTypedParameterPtr param, int nparams) {
696   if (bstats == NULL || param == NULL)
697     return -1;
698
699   for (int i = 0; i < nparams; ++i) {
700     /* ignore type. Everything must be LLONG anyway. */
701     GET_BLOCK_STATS_VALUE("rd_operations", bi.rd_req);
702     GET_BLOCK_STATS_VALUE("wr_operations", bi.wr_req);
703     GET_BLOCK_STATS_VALUE("rd_bytes", bi.rd_bytes);
704     GET_BLOCK_STATS_VALUE("wr_bytes", bi.wr_bytes);
705     GET_BLOCK_STATS_VALUE("rd_total_times", rd_total_times);
706     GET_BLOCK_STATS_VALUE("wr_total_times", wr_total_times);
707     GET_BLOCK_STATS_VALUE("flush_operations", fl_req);
708     GET_BLOCK_STATS_VALUE("flush_total_times", fl_total_times);
709   }
710
711   return 0;
712 }
713
714 #undef GET_BLOCK_STATS_VALUE
715
716 #endif /* HAVE_BLOCK_STATS_FLAGS */
717
718 /* ERROR(...) macro for virterrors. */
719 #define VIRT_ERROR(conn, s)                                                    \
720   do {                                                                         \
721     virErrorPtr err;                                                           \
722     err = (conn) ? virConnGetLastError((conn)) : virGetLastError();            \
723     if (err)                                                                   \
724       ERROR(PLUGIN_NAME " plugin: %s failed: %s", (s), err->message);          \
725   } while (0)
726
727 static char *metadata_get_hostname(virDomainPtr dom) {
728   const char *xpath_str = NULL;
729   if (hm_xpath == NULL)
730     xpath_str = "/instance/name/text()";
731   else
732     xpath_str = hm_xpath;
733
734   const char *namespace = NULL;
735   if (hm_ns == NULL) {
736     namespace = "http://openstack.org/xmlns/libvirt/nova/1.0";
737   } // namespace =hm_ns;
738   else {
739     namespace = hm_ns;
740   }
741
742   char *metadata_str = virDomainGetMetadata(
743       dom, VIR_DOMAIN_METADATA_ELEMENT, namespace, VIR_DOMAIN_AFFECT_CURRENT);
744   if (metadata_str == NULL) {
745     return NULL;
746   }
747
748   char *hostname = NULL;
749   xmlXPathContextPtr xpath_ctx = NULL;
750   xmlXPathObjectPtr xpath_obj = NULL;
751   xmlNodePtr xml_node = NULL;
752
753   xmlDocPtr xml_doc =
754       xmlReadDoc((xmlChar *)metadata_str, NULL, NULL, XML_PARSE_NONET);
755   if (xml_doc == NULL) {
756     ERROR(PLUGIN_NAME " plugin: xmlReadDoc failed to read metadata");
757     goto metadata_end;
758   }
759
760   xpath_ctx = xmlXPathNewContext(xml_doc);
761   if (xpath_ctx == NULL) {
762     ERROR(PLUGIN_NAME " plugin: xmlXPathNewContext(%s) failed for metadata",
763           metadata_str);
764     goto metadata_end;
765   }
766   xpath_obj = xmlXPathEval((xmlChar *)xpath_str, xpath_ctx);
767   if (xpath_obj == NULL) {
768     ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) failed for metadata",
769           xpath_str);
770     goto metadata_end;
771   }
772
773   if (xpath_obj->type != XPATH_NODESET) {
774     ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) unexpected return type %d "
775                       "(wanted %d) for metadata",
776           xpath_str, xpath_obj->type, XPATH_NODESET);
777     goto metadata_end;
778   }
779
780   // TODO(sileht): We can support || operator by looping on nodes here
781   if (xpath_obj->nodesetval == NULL || xpath_obj->nodesetval->nodeNr != 1) {
782     WARNING(PLUGIN_NAME " plugin: xmlXPathEval(%s) return nodeset size=%i "
783                         "expected=1 for metadata",
784             xpath_str,
785             (xpath_obj->nodesetval == NULL) ? 0
786                                             : xpath_obj->nodesetval->nodeNr);
787     goto metadata_end;
788   }
789
790   xml_node = xpath_obj->nodesetval->nodeTab[0];
791   if (xml_node->type == XML_TEXT_NODE) {
792     hostname = strdup((const char *)xml_node->content);
793   } else if (xml_node->type == XML_ATTRIBUTE_NODE) {
794     hostname = strdup((const char *)xml_node->children->content);
795   } else {
796     ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) unsupported node type %d",
797           xpath_str, xml_node->type);
798     goto metadata_end;
799   }
800
801   if (hostname == NULL) {
802     ERROR(PLUGIN_NAME " plugin: strdup(%s) hostname failed", xpath_str);
803     goto metadata_end;
804   }
805
806 metadata_end:
807   if (xpath_obj)
808     xmlXPathFreeObject(xpath_obj);
809   if (xpath_ctx)
810     xmlXPathFreeContext(xpath_ctx);
811   if (xml_doc)
812     xmlFreeDoc(xml_doc);
813   sfree(metadata_str);
814   return hostname;
815 }
816
817 static void init_value_list(value_list_t *vl, virDomainPtr dom) {
818   const char *name;
819   char uuid[VIR_UUID_STRING_BUFLEN];
820
821   sstrncpy(vl->plugin, PLUGIN_NAME, sizeof(vl->plugin));
822
823   vl->host[0] = '\0';
824
825   /* Construct the hostname field according to HostnameFormat. */
826   for (int i = 0; i < HF_MAX_FIELDS; ++i) {
827     if (hostname_format[i] == hf_none)
828       continue;
829
830     if (i > 0)
831       SSTRNCAT(vl->host, ":", sizeof(vl->host));
832
833     switch (hostname_format[i]) {
834     case hf_none:
835       break;
836     case hf_hostname:
837       SSTRNCAT(vl->host, hostname_g, sizeof(vl->host));
838       break;
839     case hf_name:
840       name = virDomainGetName(dom);
841       if (name)
842         SSTRNCAT(vl->host, name, sizeof(vl->host));
843       break;
844     case hf_uuid:
845       if (virDomainGetUUIDString(dom, uuid) == 0)
846         SSTRNCAT(vl->host, uuid, sizeof(vl->host));
847       break;
848     case hf_metadata:
849       name = metadata_get_hostname(dom);
850       if (name)
851         SSTRNCAT(vl->host, name, sizeof(vl->host));
852       break;
853     }
854   }
855
856   /* Construct the plugin instance field according to PluginInstanceFormat. */
857   for (int i = 0; i < PLGINST_MAX_FIELDS; ++i) {
858     if (plugin_instance_format[i] == plginst_none)
859       continue;
860
861     if (i > 0)
862       SSTRNCAT(vl->plugin_instance, ":", sizeof(vl->plugin_instance));
863
864     switch (plugin_instance_format[i]) {
865     case plginst_none:
866       break;
867     case plginst_name:
868       name = virDomainGetName(dom);
869       if (name)
870         SSTRNCAT(vl->plugin_instance, name, sizeof(vl->plugin_instance));
871       break;
872     case plginst_uuid:
873       if (virDomainGetUUIDString(dom, uuid) == 0)
874         SSTRNCAT(vl->plugin_instance, uuid, sizeof(vl->plugin_instance));
875       break;
876     case plginst_metadata:
877       name = metadata_get_hostname(dom);
878       if (name)
879         SSTRNCAT(vl->plugin_instance, name, sizeof(vl->plugin_instance));
880       break;
881     }
882   }
883
884 } /* void init_value_list */
885
886 static int init_notif(notification_t *notif, const virDomainPtr domain,
887                       int severity, const char *msg, const char *type,
888                       const char *type_instance) {
889   value_list_t vl = VALUE_LIST_INIT;
890
891   if (!notif) {
892     ERROR(PLUGIN_NAME " plugin: init_notif: NULL pointer");
893     return -1;
894   }
895
896   init_value_list(&vl, domain);
897   notification_init(notif, severity, msg, vl.host, vl.plugin,
898                     vl.plugin_instance, type, type_instance);
899   notif->time = cdtime();
900   return 0;
901 }
902
903 static void submit_notif(const virDomainPtr domain, int severity,
904                          const char *msg, const char *type,
905                          const char *type_instance) {
906   notification_t notif;
907
908   init_notif(&notif, domain, severity, msg, type, type_instance);
909   plugin_dispatch_notification(&notif);
910   if (notif.meta)
911     plugin_notification_meta_free(notif.meta);
912 }
913
914 static void submit(virDomainPtr dom, char const *type,
915                    char const *type_instance, value_t *values,
916                    size_t values_len) {
917   value_list_t vl = VALUE_LIST_INIT;
918   init_value_list(&vl, dom);
919
920   vl.values = values;
921   vl.values_len = values_len;
922
923   sstrncpy(vl.type, type, sizeof(vl.type));
924   if (type_instance != NULL)
925     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
926
927   plugin_dispatch_values(&vl);
928 }
929
930 static void memory_submit(virDomainPtr dom, gauge_t value) {
931   submit(dom, "memory", "total", &(value_t){.gauge = value}, 1);
932 }
933
934 static void memory_stats_submit(gauge_t value, virDomainPtr dom,
935                                 int tag_index) {
936   static const char *tags[] = {"swap_in",        "swap_out",   "major_fault",
937                                "minor_fault",    "unused",     "available",
938                                "actual_balloon", "rss",        "usable",
939                                "last_update",    "disk_caches"};
940
941   if ((tag_index < 0) || (tag_index >= (int)STATIC_ARRAY_SIZE(tags))) {
942     ERROR(PLUGIN_NAME " plugin: Array index out of bounds: tag_index = %d",
943           tag_index);
944     return;
945   }
946
947   submit(dom, "memory", tags[tag_index], &(value_t){.gauge = value}, 1);
948 }
949
950 static void submit_derive2(const char *type, derive_t v0, derive_t v1,
951                            virDomainPtr dom, const char *devname) {
952   value_t values[] = {
953       {.derive = v0},
954       {.derive = v1},
955   };
956
957   submit(dom, type, devname, values, STATIC_ARRAY_SIZE(values));
958 } /* void submit_derive2 */
959
960 static double cpu_ns_to_percent(unsigned int node_cpus,
961                                 unsigned long long cpu_time_old,
962                                 unsigned long long cpu_time_new) {
963   double percent = 0.0;
964   unsigned long long cpu_time_diff = 0;
965   double time_diff_sec = CDTIME_T_TO_DOUBLE(plugin_get_interval());
966
967   if (node_cpus != 0 && time_diff_sec != 0 && cpu_time_old != 0) {
968     cpu_time_diff = cpu_time_new - cpu_time_old;
969     percent = ((double)(100 * cpu_time_diff)) /
970               (time_diff_sec * node_cpus * NANOSEC_IN_SEC);
971   }
972
973   DEBUG(PLUGIN_NAME " plugin: node_cpus=%u cpu_time_old=%" PRIu64
974                     " cpu_time_new=%" PRIu64 " cpu_time_diff=%" PRIu64
975                     " time_diff_sec=%f percent=%f",
976         node_cpus, (uint64_t)cpu_time_old, (uint64_t)cpu_time_new,
977         (uint64_t)cpu_time_diff, time_diff_sec, percent);
978
979   return percent;
980 }
981
982 static void cpu_submit(const domain_t *dom, unsigned long long cpuTime_new) {
983
984   if (!dom)
985     return;
986
987   if (extra_stats & ex_stats_cpu_util) {
988     /* Computing %CPU requires 2 samples of cpuTime */
989     if (dom->info.cpuTime != 0 && cpuTime_new != 0) {
990
991       submit(dom->ptr, "percent", "virt_cpu_total",
992              &(value_t){.gauge = cpu_ns_to_percent(
993                             nodeinfo.cpus, dom->info.cpuTime, cpuTime_new)},
994              1);
995     }
996   }
997
998   submit(dom->ptr, "virt_cpu_total", NULL, &(value_t){.derive = cpuTime_new},
999          1);
1000 }
1001
1002 static void vcpu_submit(derive_t value, virDomainPtr dom, int vcpu_nr,
1003                         const char *type) {
1004   char type_instance[DATA_MAX_NAME_LEN];
1005
1006   ssnprintf(type_instance, sizeof(type_instance), "%d", vcpu_nr);
1007   submit(dom, type, type_instance, &(value_t){.derive = value}, 1);
1008 }
1009
1010 static void disk_block_stats_submit(struct lv_block_stats *bstats,
1011                                     virDomainPtr dom, const char *dev,
1012                                     virDomainBlockInfoPtr binfo) {
1013   char *dev_copy = strdup(dev);
1014   const char *type_instance = dev_copy;
1015
1016   if (!dev_copy)
1017     return;
1018
1019   if (blockdevice_format_basename && blockdevice_format == source)
1020     type_instance = basename(dev_copy);
1021
1022   if (!type_instance) {
1023     sfree(dev_copy);
1024     return;
1025   }
1026
1027   char flush_type_instance[DATA_MAX_NAME_LEN];
1028   ssnprintf(flush_type_instance, sizeof(flush_type_instance), "flush-%s",
1029             type_instance);
1030
1031   if ((bstats->bi.rd_req != -1) && (bstats->bi.wr_req != -1))
1032     submit_derive2("disk_ops", (derive_t)bstats->bi.rd_req,
1033                    (derive_t)bstats->bi.wr_req, dom, type_instance);
1034
1035   if ((bstats->bi.rd_bytes != -1) && (bstats->bi.wr_bytes != -1))
1036     submit_derive2("disk_octets", (derive_t)bstats->bi.rd_bytes,
1037                    (derive_t)bstats->bi.wr_bytes, dom, type_instance);
1038
1039   if (extra_stats & ex_stats_disk) {
1040     if ((bstats->rd_total_times != -1) && (bstats->wr_total_times != -1))
1041       submit_derive2("disk_time", (derive_t)bstats->rd_total_times,
1042                      (derive_t)bstats->wr_total_times, dom, type_instance);
1043
1044     if (bstats->fl_req != -1)
1045       submit(dom, "total_requests", flush_type_instance,
1046              &(value_t){.derive = (derive_t)bstats->fl_req}, 1);
1047     if (bstats->fl_total_times != -1) {
1048       derive_t value = bstats->fl_total_times / 1000; // ns -> ms
1049       submit(dom, "total_time_in_ms", flush_type_instance,
1050              &(value_t){.derive = value}, 1);
1051     }
1052   }
1053
1054   /* disk_allocation, disk_capacity and disk_physical are stored only
1055    * if corresponding extrastats are set in collectd configuration file */
1056   if ((extra_stats & ex_stats_disk_allocation) && binfo->allocation != -1)
1057     submit(dom, "disk_allocation", type_instance,
1058            &(value_t){.gauge = (gauge_t)binfo->allocation}, 1);
1059
1060   if ((extra_stats & ex_stats_disk_capacity) && binfo->capacity != -1)
1061     submit(dom, "disk_capacity", type_instance,
1062            &(value_t){.gauge = (gauge_t)binfo->capacity}, 1);
1063
1064   if ((extra_stats & ex_stats_disk_physical) && binfo->physical != -1)
1065     submit(dom, "disk_physical", type_instance,
1066            &(value_t){.gauge = (gauge_t)binfo->physical}, 1);
1067
1068   sfree(dev_copy);
1069 }
1070
1071 /**
1072  * Function for parsing ExtraStats configuration options.
1073  * Result of parsing is stored under 'out_parsed_flags' pointer.
1074  *
1075  * Returns 0 in case of success and 1 in case of parsing error
1076  */
1077 static int parse_ex_stats_flags(unsigned int *out_parsed_flags, char **exstats,
1078                                 int numexstats) {
1079   unsigned int ex_stats_flags = ex_stats_none;
1080
1081   assert(out_parsed_flags != NULL);
1082
1083   for (int i = 0; i < numexstats; i++) {
1084     for (int j = 0; ex_stats_table[j].name != NULL; j++) {
1085       if (strcasecmp(exstats[i], ex_stats_table[j].name) == 0) {
1086         DEBUG(PLUGIN_NAME " plugin: enabling extra stats for '%s'",
1087               ex_stats_table[j].name);
1088         ex_stats_flags |= ex_stats_table[j].flag;
1089         break;
1090       }
1091
1092       if (ex_stats_table[j + 1].name == NULL) {
1093         ERROR(PLUGIN_NAME " plugin: Unmatched ExtraStats option: %s",
1094               exstats[i]);
1095         return 1;
1096       }
1097     }
1098   }
1099
1100   *out_parsed_flags = ex_stats_flags;
1101   return 0;
1102 }
1103
1104 static void domain_state_submit_notif(virDomainPtr dom, int state, int reason) {
1105   if ((state < 0) || ((size_t)state >= STATIC_ARRAY_SIZE(domain_states))) {
1106     ERROR(PLUGIN_NAME " plugin: Array index out of bounds: state=%d", state);
1107     return;
1108   }
1109
1110   char msg[DATA_MAX_NAME_LEN];
1111   const char *state_str = domain_states[state];
1112 #ifdef HAVE_DOM_REASON
1113   if ((reason < 0) ||
1114       ((size_t)reason >= STATIC_ARRAY_SIZE(domain_reasons[0]))) {
1115     ERROR(PLUGIN_NAME " plugin: Array index out of bounds: reason=%d", reason);
1116     return;
1117   }
1118
1119   const char *reason_str = domain_reasons[state][reason];
1120   /* Array size for domain reasons is fixed, but different domain states can
1121    * have different number of reasons. We need to check if reason was
1122    * successfully parsed */
1123   if (!reason_str) {
1124     ERROR(PLUGIN_NAME " plugin: Invalid reason (%d) for domain state: %s",
1125           reason, state_str);
1126     return;
1127   }
1128 #else
1129   const char *reason_str = "N/A";
1130 #endif
1131
1132   ssnprintf(msg, sizeof(msg), "Domain state: %s. Reason: %s", state_str,
1133             reason_str);
1134
1135   int severity;
1136   switch (state) {
1137   case VIR_DOMAIN_NOSTATE:
1138   case VIR_DOMAIN_RUNNING:
1139   case VIR_DOMAIN_SHUTDOWN:
1140   case VIR_DOMAIN_SHUTOFF:
1141     severity = NOTIF_OKAY;
1142     break;
1143   case VIR_DOMAIN_BLOCKED:
1144   case VIR_DOMAIN_PAUSED:
1145 #ifdef DOM_STATE_PMSUSPENDED
1146   case VIR_DOMAIN_PMSUSPENDED:
1147 #endif
1148     severity = NOTIF_WARNING;
1149     break;
1150   case VIR_DOMAIN_CRASHED:
1151     severity = NOTIF_FAILURE;
1152     break;
1153   default:
1154     ERROR(PLUGIN_NAME " plugin: Unrecognized domain state (%d)", state);
1155     return;
1156   }
1157   submit_notif(dom, severity, msg, "domain_state", NULL);
1158 }
1159
1160 static int lv_init_ignorelists() {
1161   if (il_domains == NULL)
1162     il_domains = ignorelist_create(1);
1163   if (il_block_devices == NULL)
1164     il_block_devices = ignorelist_create(1);
1165   if (il_interface_devices == NULL)
1166     il_interface_devices = ignorelist_create(1);
1167
1168   if (!il_domains || !il_block_devices || !il_interface_devices)
1169     return 1;
1170
1171   return 0;
1172 }
1173
1174 /* Validates config option that may take multiple strings arguments.
1175  * Returns 0 on success, -1 otherwise */
1176 static int check_config_multiple_string_entry(const oconfig_item_t *ci) {
1177   if (ci == NULL) {
1178     ERROR(PLUGIN_NAME " plugin: ci oconfig_item can't be NULL");
1179     return -1;
1180   }
1181
1182   if (ci->values_num < 1) {
1183     ERROR(PLUGIN_NAME
1184           " plugin: the '%s' option requires at least one string argument",
1185           ci->key);
1186     return -1;
1187   }
1188
1189   for (int i = 0; i < ci->values_num; ++i) {
1190     if (ci->values[i].type != OCONFIG_TYPE_STRING) {
1191       ERROR(PLUGIN_NAME
1192             " plugin: one of the '%s' options is not a valid string",
1193             ci->key);
1194       return -1;
1195     }
1196   }
1197
1198   return 0;
1199 }
1200
1201 static int lv_config(oconfig_item_t *ci) {
1202   if (lv_init_ignorelists() != 0) {
1203     ERROR(PLUGIN_NAME " plugin: lv_init_ignorelist failed.");
1204     return -1;
1205   }
1206
1207   for (int i = 0; i < ci->children_num; ++i) {
1208     oconfig_item_t *c = ci->children + i;
1209
1210     if (strcasecmp(c->key, "Connection") == 0) {
1211       if (cf_util_get_string(c, &conn_string) != 0 || conn_string == NULL)
1212         return -1;
1213
1214       continue;
1215     } else if (strcasecmp(c->key, "RefreshInterval") == 0) {
1216       if (cf_util_get_int(c, &interval) != 0)
1217         return -1;
1218
1219       continue;
1220     } else if (strcasecmp(c->key, "Domain") == 0) {
1221       char *domain_name = NULL;
1222       if (cf_util_get_string(c, &domain_name) != 0)
1223         return -1;
1224
1225       if (ignorelist_add(il_domains, domain_name)) {
1226         ERROR(PLUGIN_NAME " plugin: Adding '%s' to domain-ignorelist failed",
1227               domain_name);
1228         sfree(domain_name);
1229         return -1;
1230       }
1231
1232       sfree(domain_name);
1233       continue;
1234     } else if (strcasecmp(c->key, "BlockDevice") == 0) {
1235       char *device_name = NULL;
1236       if (cf_util_get_string(c, &device_name) != 0)
1237         return -1;
1238
1239       if (ignorelist_add(il_block_devices, device_name) != 0) {
1240         ERROR(PLUGIN_NAME
1241               " plugin: Adding '%s' to block-device-ignorelist failed",
1242               device_name);
1243         sfree(device_name);
1244         return -1;
1245       }
1246
1247       sfree(device_name);
1248       continue;
1249     } else if (strcasecmp(c->key, "BlockDeviceFormat") == 0) {
1250       char *device_format = NULL;
1251       if (cf_util_get_string(c, &device_format) != 0)
1252         return -1;
1253
1254       if (strcasecmp(device_format, "target") == 0)
1255         blockdevice_format = target;
1256       else if (strcasecmp(device_format, "source") == 0)
1257         blockdevice_format = source;
1258       else {
1259         ERROR(PLUGIN_NAME " plugin: unknown BlockDeviceFormat: %s",
1260               device_format);
1261         sfree(device_format);
1262         return -1;
1263       }
1264
1265       sfree(device_format);
1266       continue;
1267     } else if (strcasecmp(c->key, "BlockDeviceFormatBasename") == 0) {
1268       if (cf_util_get_boolean(c, &blockdevice_format_basename) != 0)
1269         return -1;
1270
1271       continue;
1272     } else if (strcasecmp(c->key, "InterfaceDevice") == 0) {
1273       char *interface_name = NULL;
1274       if (cf_util_get_string(c, &interface_name) != 0)
1275         return -1;
1276
1277       if (ignorelist_add(il_interface_devices, interface_name)) {
1278         ERROR(PLUGIN_NAME " plugin: Adding '%s' to interface-ignorelist failed",
1279               interface_name);
1280         sfree(interface_name);
1281         return -1;
1282       }
1283
1284       sfree(interface_name);
1285       continue;
1286     } else if (strcasecmp(c->key, "IgnoreSelected") == 0) {
1287       bool ignore_selected = false;
1288       if (cf_util_get_boolean(c, &ignore_selected) != 0)
1289         return -1;
1290
1291       if (ignore_selected) {
1292         ignorelist_set_invert(il_domains, 0);
1293         ignorelist_set_invert(il_block_devices, 0);
1294         ignorelist_set_invert(il_interface_devices, 0);
1295       } else {
1296         ignorelist_set_invert(il_domains, 1);
1297         ignorelist_set_invert(il_block_devices, 1);
1298         ignorelist_set_invert(il_interface_devices, 1);
1299       }
1300
1301       continue;
1302     } else if (strcasecmp(c->key, "HostnameMetadataNS") == 0) {
1303       if (cf_util_get_string(c, &hm_ns) != 0)
1304         return -1;
1305
1306       continue;
1307     } else if (strcasecmp(c->key, "HostnameMetadataXPath") == 0) {
1308       if (cf_util_get_string(c, &hm_xpath) != 0)
1309         return -1;
1310
1311       continue;
1312     } else if (strcasecmp(c->key, "HostnameFormat") == 0) {
1313       /* this option can take multiple strings arguments in one config line*/
1314       if (check_config_multiple_string_entry(c) != 0) {
1315         ERROR(PLUGIN_NAME " plugin: Could not get 'HostnameFormat' parameter");
1316         return -1;
1317       }
1318
1319       const int params_num = c->values_num;
1320       for (int i = 0; i < params_num; ++i) {
1321         const char *param_name = c->values[i].value.string;
1322         if (strcasecmp(param_name, "hostname") == 0)
1323           hostname_format[i] = hf_hostname;
1324         else if (strcasecmp(param_name, "name") == 0)
1325           hostname_format[i] = hf_name;
1326         else if (strcasecmp(param_name, "uuid") == 0)
1327           hostname_format[i] = hf_uuid;
1328         else if (strcasecmp(param_name, "metadata") == 0)
1329           hostname_format[i] = hf_metadata;
1330         else {
1331           ERROR(PLUGIN_NAME " plugin: unknown HostnameFormat field: %s",
1332                 param_name);
1333           return -1;
1334         }
1335       }
1336
1337       for (int i = params_num; i < HF_MAX_FIELDS; ++i)
1338         hostname_format[i] = hf_none;
1339
1340       continue;
1341     } else if (strcasecmp(c->key, "PluginInstanceFormat") == 0) {
1342       /* this option can handle list of string parameters in one line*/
1343       if (check_config_multiple_string_entry(c) != 0) {
1344         ERROR(PLUGIN_NAME
1345               " plugin: Could not get 'PluginInstanceFormat' parameter");
1346         return -1;
1347       }
1348
1349       const int params_num = c->values_num;
1350       for (int i = 0; i < params_num; ++i) {
1351         const char *param_name = c->values[i].value.string;
1352         if (strcasecmp(param_name, "none") == 0) {
1353           plugin_instance_format[i] = plginst_none;
1354           break;
1355         } else if (strcasecmp(param_name, "name") == 0)
1356           plugin_instance_format[i] = plginst_name;
1357         else if (strcasecmp(param_name, "uuid") == 0)
1358           plugin_instance_format[i] = plginst_uuid;
1359         else if (strcasecmp(param_name, "metadata") == 0)
1360           plugin_instance_format[i] = plginst_metadata;
1361         else {
1362           ERROR(PLUGIN_NAME " plugin: unknown PluginInstanceFormat field: %s",
1363                 param_name);
1364
1365           return -1;
1366         }
1367       }
1368
1369       for (int i = params_num; i < PLGINST_MAX_FIELDS; ++i)
1370         plugin_instance_format[i] = plginst_none;
1371
1372       continue;
1373     } else if (strcasecmp(c->key, "InterfaceFormat") == 0) {
1374       char *format = NULL;
1375       if (cf_util_get_string(c, &format) != 0)
1376         return -1;
1377
1378       if (strcasecmp(format, "name") == 0)
1379         interface_format = if_name;
1380       else if (strcasecmp(format, "address") == 0)
1381         interface_format = if_address;
1382       else if (strcasecmp(format, "number") == 0)
1383         interface_format = if_number;
1384       else {
1385         ERROR(PLUGIN_NAME " plugin: unknown InterfaceFormat: %s", format);
1386         sfree(format);
1387         return -1;
1388       }
1389
1390       sfree(format);
1391       continue;
1392     } else if (strcasecmp(c->key, "Instances") == 0) {
1393       if (cf_util_get_int(c, &nr_instances) != 0)
1394         return -1;
1395
1396       if (nr_instances <= 0) {
1397         ERROR(PLUGIN_NAME " plugin: Instances <= 0 makes no sense.");
1398         return -1;
1399       }
1400       if (nr_instances > NR_INSTANCES_MAX) {
1401         ERROR(PLUGIN_NAME " plugin: Instances=%i > NR_INSTANCES_MAX=%i"
1402                           " use a lower setting or recompile the plugin.",
1403               nr_instances, NR_INSTANCES_MAX);
1404         return -1;
1405       }
1406
1407       DEBUG(PLUGIN_NAME " plugin: configured %i instances", nr_instances);
1408       continue;
1409     } else if (strcasecmp(c->key, "ExtraStats") == 0) {
1410       char *ex_str = NULL;
1411
1412       if (cf_util_get_string(c, &ex_str) != 0)
1413         return -1;
1414
1415       char *exstats[EX_STATS_MAX_FIELDS];
1416       int numexstats = strsplit(ex_str, exstats, STATIC_ARRAY_SIZE(exstats));
1417       int status = parse_ex_stats_flags(&extra_stats, exstats, numexstats);
1418       sfree(ex_str);
1419       if (status != 0) {
1420         ERROR(PLUGIN_NAME " plugin: parsing 'ExtraStats' option failed");
1421         return status;
1422       }
1423
1424 #ifdef HAVE_JOB_STATS
1425       if ((extra_stats & ex_stats_job_stats_completed) &&
1426           (extra_stats & ex_stats_job_stats_background)) {
1427         ERROR(PLUGIN_NAME " plugin: Invalid job stats configuration. Only one "
1428                           "type of job statistics can be collected at the same "
1429                           "time");
1430         return -1;
1431       }
1432 #endif
1433
1434       /* ExtraStats parsed successfully */
1435       continue;
1436     } else if (strcasecmp(c->key, "PersistentNotification") == 0) {
1437       if (cf_util_get_boolean(c, &persistent_notification) != 0)
1438         return -1;
1439
1440       continue;
1441     } else if (strcasecmp(c->key, "ReportBlockDevices") == 0) {
1442       if (cf_util_get_boolean(c, &report_block_devices) != 0)
1443         return -1;
1444
1445       continue;
1446     } else if (strcasecmp(c->key, "ReportNetworkInterfaces") == 0) {
1447       if (cf_util_get_boolean(c, &report_network_interfaces) != 0)
1448         return -1;
1449
1450       continue;
1451     } else {
1452       /* Unrecognised option. */
1453       ERROR(PLUGIN_NAME " plugin: Unrecognized option: '%s'", c->key);
1454       return -1;
1455     }
1456   }
1457
1458   return 0;
1459 }
1460
1461 static int lv_connect(void) {
1462   if (conn == NULL) {
1463     /* event implementation must be registered before connection is opened */
1464     if (!persistent_notification)
1465       if (register_event_impl() != 0)
1466         return -1;
1467
1468 /* `conn_string == NULL' is acceptable */
1469 #ifdef HAVE_FS_INFO
1470     /* virDomainGetFSInfo requires full read-write access connection */
1471     if (extra_stats & ex_stats_fs_info)
1472       conn = virConnectOpen(conn_string);
1473     else
1474 #endif
1475       conn = virConnectOpenReadOnly(conn_string);
1476     if (conn == NULL) {
1477       c_complain(LOG_ERR, &conn_complain,
1478                  PLUGIN_NAME " plugin: Unable to connect: "
1479                              "virConnectOpen failed.");
1480       return -1;
1481     }
1482     int status = virNodeGetInfo(conn, &nodeinfo);
1483     if (status != 0) {
1484       ERROR(PLUGIN_NAME " plugin: virNodeGetInfo failed");
1485       virConnectClose(conn);
1486       conn = NULL;
1487       return -1;
1488     }
1489
1490     if (!persistent_notification)
1491       if (start_event_loop(&notif_thread) != 0) {
1492         virConnectClose(conn);
1493         conn = NULL;
1494         return -1;
1495       }
1496   }
1497   c_release(LOG_NOTICE, &conn_complain,
1498             PLUGIN_NAME " plugin: Connection established.");
1499   return 0;
1500 }
1501
1502 static void lv_disconnect(void) {
1503   if (conn != NULL)
1504     virConnectClose(conn);
1505   conn = NULL;
1506   WARNING(PLUGIN_NAME " plugin: closed connection to libvirt");
1507 }
1508
1509 static int lv_domain_block_stats(virDomainPtr dom, const char *path,
1510                                  struct lv_block_stats *bstats) {
1511 #ifdef HAVE_BLOCK_STATS_FLAGS
1512   int nparams = 0;
1513   if (virDomainBlockStatsFlags(dom, path, NULL, &nparams, 0) < 0 ||
1514       nparams <= 0) {
1515     VIRT_ERROR(conn, "getting the disk params count");
1516     return -1;
1517   }
1518
1519   virTypedParameterPtr params = calloc(nparams, sizeof(*params));
1520   if (params == NULL) {
1521     ERROR(PLUGIN_NAME " plugin: alloc(%i) for block=%s parameters failed.",
1522           nparams, path);
1523     return -1;
1524   }
1525
1526   int rc = -1;
1527   if (virDomainBlockStatsFlags(dom, path, params, &nparams, 0) < 0) {
1528     VIRT_ERROR(conn, "getting the disk params values");
1529   } else {
1530     rc = get_block_stats(bstats, params, nparams);
1531   }
1532
1533   virTypedParamsClear(params, nparams);
1534   sfree(params);
1535   return rc;
1536 #else
1537   return virDomainBlockStats(dom, path, &(bstats->bi), sizeof(bstats->bi));
1538 #endif /* HAVE_BLOCK_STATS_FLAGS */
1539 }
1540
1541 #ifdef HAVE_PERF_STATS
1542 static void perf_submit(virDomainStatsRecordPtr stats) {
1543   for (int i = 0; i < stats->nparams; ++i) {
1544     /* Replace '.' with '_' in event field to match other metrics' naming
1545      * convention */
1546     char *c = strchr(stats->params[i].field, '.');
1547     if (c)
1548       *c = '_';
1549     submit(stats->dom, "perf", stats->params[i].field,
1550            &(value_t){.derive = stats->params[i].value.ul}, 1);
1551   }
1552 }
1553
1554 static int get_perf_events(virDomainPtr domain) {
1555   virDomainStatsRecordPtr *stats = NULL;
1556   /* virDomainListGetStats requires a NULL terminated list of domains */
1557   virDomainPtr domain_array[] = {domain, NULL};
1558
1559   int status =
1560       virDomainListGetStats(domain_array, VIR_DOMAIN_STATS_PERF, &stats, 0);
1561   if (status == -1) {
1562     ERROR(PLUGIN_NAME " plugin: virDomainListGetStats failed with status %i.",
1563           status);
1564
1565     virErrorPtr err = virGetLastError();
1566     if (err->code == VIR_ERR_NO_SUPPORT) {
1567       ERROR(PLUGIN_NAME
1568             " plugin: Disabled unsupported ExtraStats selector: perf");
1569       extra_stats &= ~(ex_stats_perf);
1570     }
1571
1572     return -1;
1573   }
1574
1575   for (int i = 0; i < status; ++i)
1576     perf_submit(stats[i]);
1577
1578   virDomainStatsRecordListFree(stats);
1579   return 0;
1580 }
1581 #endif /* HAVE_PERF_STATS */
1582
1583 static void vcpu_pin_submit(virDomainPtr dom, int max_cpus, int vcpu,
1584                             unsigned char *cpu_maps, int cpu_map_len) {
1585   for (int cpu = 0; cpu < max_cpus; ++cpu) {
1586     char type_instance[DATA_MAX_NAME_LEN];
1587     bool is_set = VIR_CPU_USABLE(cpu_maps, cpu_map_len, vcpu, cpu);
1588
1589     ssnprintf(type_instance, sizeof(type_instance), "vcpu_%d-cpu_%d", vcpu,
1590               cpu);
1591     submit(dom, "cpu_affinity", type_instance, &(value_t){.gauge = is_set}, 1);
1592   }
1593 }
1594
1595 static int get_vcpu_stats(virDomainPtr domain, unsigned short nr_virt_cpu) {
1596   int max_cpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
1597
1598   virVcpuInfoPtr vinfo = calloc(nr_virt_cpu, sizeof(*vinfo));
1599   if (vinfo == NULL) {
1600     ERROR(PLUGIN_NAME " plugin: calloc failed.");
1601     return -1;
1602   }
1603
1604   int cpu_map_len = 0;
1605   unsigned char *cpumaps = NULL;
1606   if (extra_stats & ex_stats_vcpupin) {
1607     cpu_map_len = VIR_CPU_MAPLEN(max_cpus);
1608     cpumaps = calloc(nr_virt_cpu, cpu_map_len);
1609
1610     if (cpumaps == NULL) {
1611       ERROR(PLUGIN_NAME " plugin: calloc failed.");
1612       sfree(vinfo);
1613       return -1;
1614     }
1615   }
1616
1617   int status =
1618       virDomainGetVcpus(domain, vinfo, nr_virt_cpu, cpumaps, cpu_map_len);
1619   if (status < 0) {
1620     ERROR(PLUGIN_NAME " plugin: virDomainGetVcpus failed with status %i.",
1621           status);
1622
1623     virErrorPtr err = virGetLastError();
1624     if (err->code == VIR_ERR_NO_SUPPORT) {
1625       if (extra_stats & ex_stats_vcpu)
1626         ERROR(PLUGIN_NAME
1627               " plugin: Disabled unsupported ExtraStats selector: vcpu");
1628       if (extra_stats & ex_stats_vcpupin)
1629         ERROR(PLUGIN_NAME
1630               " plugin: Disabled unsupported ExtraStats selector: vcpupin");
1631       extra_stats &= ~(ex_stats_vcpu | ex_stats_vcpupin);
1632     }
1633
1634     sfree(cpumaps);
1635     sfree(vinfo);
1636     return -1;
1637   }
1638
1639   for (int i = 0; i < nr_virt_cpu; ++i) {
1640     if (extra_stats & ex_stats_vcpu)
1641       vcpu_submit(vinfo[i].cpuTime, domain, vinfo[i].number, "virt_vcpu");
1642     if (extra_stats & ex_stats_vcpupin)
1643       vcpu_pin_submit(domain, max_cpus, i, cpumaps, cpu_map_len);
1644   }
1645
1646   sfree(cpumaps);
1647   sfree(vinfo);
1648   return 0;
1649 }
1650
1651 #ifdef HAVE_CPU_STATS
1652 static int get_pcpu_stats(virDomainPtr dom) {
1653   int nparams = virDomainGetCPUStats(dom, NULL, 0, -1, 1, 0);
1654   if (nparams < 0) {
1655     VIRT_ERROR(conn, "getting the CPU params count");
1656
1657     virErrorPtr err = virGetLastError();
1658     if (err->code == VIR_ERR_NO_SUPPORT) {
1659       ERROR(PLUGIN_NAME
1660             " plugin: Disabled unsupported ExtraStats selector: pcpu");
1661       extra_stats &= ~(ex_stats_pcpu);
1662     }
1663
1664     return -1;
1665   }
1666
1667   virTypedParameterPtr param = calloc(nparams, sizeof(*param));
1668   if (param == NULL) {
1669     ERROR(PLUGIN_NAME " plugin: alloc(%i) for cpu parameters failed.", nparams);
1670     return -1;
1671   }
1672
1673   int ret = virDomainGetCPUStats(dom, param, nparams, -1, 1, 0); // total stats.
1674   if (ret < 0) {
1675     virTypedParamsClear(param, nparams);
1676     sfree(param);
1677     VIRT_ERROR(conn, "getting the CPU params values");
1678     return -1;
1679   }
1680
1681   unsigned long long total_user_cpu_time = 0;
1682   unsigned long long total_syst_cpu_time = 0;
1683
1684   for (int i = 0; i < nparams; ++i) {
1685     if (!strcmp(param[i].field, "user_time"))
1686       total_user_cpu_time = param[i].value.ul;
1687     else if (!strcmp(param[i].field, "system_time"))
1688       total_syst_cpu_time = param[i].value.ul;
1689   }
1690
1691   if (total_user_cpu_time > 0 || total_syst_cpu_time > 0)
1692     submit_derive2("ps_cputime", total_user_cpu_time, total_syst_cpu_time, dom,
1693                    NULL);
1694
1695   virTypedParamsClear(param, nparams);
1696   sfree(param);
1697
1698   return 0;
1699 }
1700 #endif /* HAVE_CPU_STATS */
1701
1702 #ifdef HAVE_DOM_REASON
1703 static int submit_domain_state(virDomainPtr domain) {
1704   int domain_state = 0;
1705   int domain_reason = 0;
1706
1707   int status = virDomainGetState(domain, &domain_state, &domain_reason, 0);
1708   if (status != 0) {
1709     ERROR(PLUGIN_NAME " plugin: virDomainGetState failed with status %i.",
1710           status);
1711     return status;
1712   }
1713
1714   value_t values[] = {
1715       {.gauge = (gauge_t)domain_state},
1716       {.gauge = (gauge_t)domain_reason},
1717   };
1718
1719   submit(domain, "domain_state", NULL, values, STATIC_ARRAY_SIZE(values));
1720
1721   return 0;
1722 }
1723
1724 #ifdef HAVE_LIST_ALL_DOMAINS
1725 static int get_domain_state_notify(virDomainPtr domain) {
1726   int domain_state = 0;
1727   int domain_reason = 0;
1728
1729   int status = virDomainGetState(domain, &domain_state, &domain_reason, 0);
1730   if (status != 0) {
1731     ERROR(PLUGIN_NAME " plugin: virDomainGetState failed with status %i.",
1732           status);
1733     return status;
1734   }
1735
1736   domain_state_submit_notif(domain, domain_state, domain_reason);
1737
1738   return status;
1739 }
1740 #endif /* HAVE_LIST_ALL_DOMAINS */
1741 #endif /* HAVE_DOM_REASON */
1742
1743 static int get_memory_stats(virDomainPtr domain) {
1744   virDomainMemoryStatPtr minfo =
1745       calloc(VIR_DOMAIN_MEMORY_STAT_NR, sizeof(*minfo));
1746   if (minfo == NULL) {
1747     ERROR(PLUGIN_NAME " plugin: calloc failed.");
1748     return -1;
1749   }
1750
1751   int mem_stats =
1752       virDomainMemoryStats(domain, minfo, VIR_DOMAIN_MEMORY_STAT_NR, 0);
1753   if (mem_stats < 0) {
1754     ERROR(PLUGIN_NAME " plugin: virDomainMemoryStats failed with mem_stats %i.",
1755           mem_stats);
1756     sfree(minfo);
1757
1758     virErrorPtr err = virGetLastError();
1759     if (err->code == VIR_ERR_NO_SUPPORT) {
1760       ERROR(PLUGIN_NAME
1761             " plugin: Disabled unsupported ExtraStats selector: memory");
1762       extra_stats &= ~(ex_stats_memory);
1763     }
1764
1765     return -1;
1766   }
1767
1768   derive_t swap_in = -1;
1769   derive_t swap_out = -1;
1770   derive_t min_flt = -1;
1771   derive_t maj_flt = -1;
1772
1773   for (int i = 0; i < mem_stats; i++) {
1774     if (minfo[i].tag == VIR_DOMAIN_MEMORY_STAT_SWAP_IN)
1775       swap_in = minfo[i].val;
1776     else if (minfo[i].tag == VIR_DOMAIN_MEMORY_STAT_SWAP_OUT)
1777       swap_out = minfo[i].val;
1778     else if (minfo[i].tag == VIR_DOMAIN_MEMORY_STAT_MINOR_FAULT)
1779       min_flt = minfo[i].val;
1780     else if (minfo[i].tag == VIR_DOMAIN_MEMORY_STAT_MAJOR_FAULT)
1781       maj_flt = minfo[i].val;
1782 #ifdef LIBVIR_CHECK_VERSION
1783 #if LIBVIR_CHECK_VERSION(2, 1, 0)
1784     else if (minfo[i].tag == VIR_DOMAIN_MEMORY_STAT_LAST_UPDATE)
1785       /* Skip 'last_update' reporting as that is not memory but timestamp */
1786       continue;
1787 #endif
1788 #endif
1789     else
1790       memory_stats_submit((gauge_t)minfo[i].val * 1024, domain, minfo[i].tag);
1791   }
1792
1793   if (swap_in > 0 || swap_out > 0) {
1794     submit(domain, "swap_io", "in", &(value_t){.gauge = swap_in}, 1);
1795     submit(domain, "swap_io", "out", &(value_t){.gauge = swap_out}, 1);
1796   }
1797
1798   if (min_flt > 0 || maj_flt > 0) {
1799     value_t values[] = {
1800         {.gauge = (gauge_t)min_flt},
1801         {.gauge = (gauge_t)maj_flt},
1802     };
1803     submit(domain, "ps_pagefaults", NULL, values, STATIC_ARRAY_SIZE(values));
1804   }
1805
1806   sfree(minfo);
1807   return 0;
1808 }
1809
1810 #ifdef HAVE_DISK_ERR
1811 static void disk_err_submit(virDomainPtr domain,
1812                             virDomainDiskErrorPtr disk_err) {
1813   submit(domain, "disk_error", disk_err->disk,
1814          &(value_t){.gauge = disk_err->error}, 1);
1815 }
1816
1817 static int get_disk_err(virDomainPtr domain) {
1818   /* Get preferred size of disk errors array */
1819   int disk_err_count = virDomainGetDiskErrors(domain, NULL, 0, 0);
1820   if (disk_err_count == -1) {
1821     ERROR(PLUGIN_NAME
1822           " plugin: failed to get preferred size of disk errors array");
1823
1824     virErrorPtr err = virGetLastError();
1825
1826     if (err->code == VIR_ERR_NO_SUPPORT) {
1827       ERROR(PLUGIN_NAME
1828             " plugin: Disabled unsupported ExtraStats selector: disk_err");
1829       extra_stats &= ~(ex_stats_disk_err);
1830     }
1831
1832     return -1;
1833   }
1834
1835   DEBUG(PLUGIN_NAME
1836         " plugin: preferred size of disk errors array: %d for domain %s",
1837         disk_err_count, virDomainGetName(domain));
1838   virDomainDiskError disk_err[disk_err_count];
1839
1840   disk_err_count = virDomainGetDiskErrors(domain, disk_err, disk_err_count, 0);
1841   if (disk_err_count == -1) {
1842     ERROR(PLUGIN_NAME " plugin: virDomainGetDiskErrors failed with status %d",
1843           disk_err_count);
1844     return -1;
1845   }
1846
1847   DEBUG(PLUGIN_NAME " plugin: detected %d disk errors in domain %s",
1848         disk_err_count, virDomainGetName(domain));
1849
1850   for (int i = 0; i < disk_err_count; ++i) {
1851     disk_err_submit(domain, &disk_err[i]);
1852     sfree(disk_err[i].disk);
1853   }
1854
1855   return 0;
1856 }
1857 #endif /* HAVE_DISK_ERR */
1858
1859 static int get_block_device_stats(struct block_device *block_dev) {
1860   if (!block_dev) {
1861     ERROR(PLUGIN_NAME " plugin: get_block_stats NULL pointer");
1862     return -1;
1863   }
1864
1865   virDomainBlockInfo binfo;
1866   init_block_info(&binfo);
1867
1868   /* Fetching block info stats only if needed*/
1869   if (extra_stats & (ex_stats_disk_allocation | ex_stats_disk_capacity |
1870                      ex_stats_disk_physical)) {
1871     /* Block info statistics can be only fetched from devices with 'source'
1872      * defined */
1873     if (block_dev->has_source) {
1874       if (virDomainGetBlockInfo(block_dev->dom, block_dev->path, &binfo, 0) <
1875           0) {
1876         ERROR(PLUGIN_NAME " plugin: virDomainGetBlockInfo failed for path: %s",
1877               block_dev->path);
1878
1879         virErrorPtr err = virGetLastError();
1880         if (err->code == VIR_ERR_NO_SUPPORT) {
1881
1882           if (extra_stats & ex_stats_disk_allocation)
1883             ERROR(PLUGIN_NAME " plugin: Disabled unsupported ExtraStats "
1884                               "selector: disk_allocation");
1885           if (extra_stats & ex_stats_disk_capacity)
1886             ERROR(PLUGIN_NAME " plugin: Disabled unsupported ExtraStats "
1887                               "selector: disk_capacity");
1888           if (extra_stats & ex_stats_disk_physical)
1889             ERROR(PLUGIN_NAME " plugin: Disabled unsupported ExtraStats "
1890                               "selector: disk_physical");
1891
1892           extra_stats &= ~(ex_stats_disk_allocation | ex_stats_disk_capacity |
1893                            ex_stats_disk_physical);
1894         }
1895
1896         return -1;
1897       }
1898     }
1899   }
1900
1901   struct lv_block_stats bstats;
1902   init_block_stats(&bstats);
1903
1904   if (lv_domain_block_stats(block_dev->dom, block_dev->path, &bstats) < 0) {
1905     ERROR(PLUGIN_NAME " plugin: lv_domain_block_stats failed");
1906     return -1;
1907   }
1908
1909   disk_block_stats_submit(&bstats, block_dev->dom, block_dev->path, &binfo);
1910   return 0;
1911 }
1912
1913 #ifdef HAVE_FS_INFO
1914
1915 #define NM_ADD_ITEM(_fun, _name, _val)                                         \
1916   do {                                                                         \
1917     ret = _fun(&notif, _name, _val);                                           \
1918     if (ret != 0) {                                                            \
1919       ERROR(PLUGIN_NAME " plugin: failed to add notification metadata");       \
1920       goto cleanup;                                                            \
1921     }                                                                          \
1922   } while (0)
1923
1924 #define NM_ADD_STR_ITEMS(_items, _size)                                        \
1925   do {                                                                         \
1926     for (size_t _i = 0; _i < _size; ++_i) {                                    \
1927       DEBUG(PLUGIN_NAME                                                        \
1928             " plugin: Adding notification metadata name=%s value=%s",          \
1929             _items[_i].name, _items[_i].value);                                \
1930       NM_ADD_ITEM(plugin_notification_meta_add_string, _items[_i].name,        \
1931                   _items[_i].value);                                           \
1932     }                                                                          \
1933   } while (0)
1934
1935 static int fs_info_notify(virDomainPtr domain, virDomainFSInfoPtr fs_info) {
1936   notification_t notif;
1937   int ret = 0;
1938
1939   /* Local struct, just for the purpose of this function. */
1940   typedef struct nm_str_item_s {
1941     const char *name;
1942     const char *value;
1943   } nm_str_item_t;
1944
1945   nm_str_item_t fs_dev_alias[fs_info->ndevAlias];
1946   nm_str_item_t fs_str_items[] = {
1947       {.name = "mountpoint", .value = fs_info->mountpoint},
1948       {.name = "name", .value = fs_info->name},
1949       {.name = "fstype", .value = fs_info->fstype}};
1950
1951   for (size_t i = 0; i < fs_info->ndevAlias; ++i) {
1952     fs_dev_alias[i].name = "devAlias";
1953     fs_dev_alias[i].value = fs_info->devAlias[i];
1954   }
1955
1956   init_notif(&notif, domain, NOTIF_OKAY, "File system information",
1957              "file_system", NULL);
1958   NM_ADD_STR_ITEMS(fs_str_items, STATIC_ARRAY_SIZE(fs_str_items));
1959   NM_ADD_ITEM(plugin_notification_meta_add_unsigned_int, "ndevAlias",
1960               fs_info->ndevAlias);
1961   NM_ADD_STR_ITEMS(fs_dev_alias, fs_info->ndevAlias);
1962
1963   plugin_dispatch_notification(&notif);
1964
1965 cleanup:
1966   if (notif.meta)
1967     plugin_notification_meta_free(notif.meta);
1968   return ret;
1969 }
1970
1971 #undef RETURN_ON_ERR
1972 #undef NM_ADD_STR_ITEMS
1973
1974 static int get_fs_info(virDomainPtr domain) {
1975   virDomainFSInfoPtr *fs_info = NULL;
1976   int ret = 0;
1977
1978   int mount_points_cnt = virDomainGetFSInfo(domain, &fs_info, 0);
1979   if (mount_points_cnt == -1) {
1980     ERROR(PLUGIN_NAME " plugin: virDomainGetFSInfo failed: %d",
1981           mount_points_cnt);
1982
1983     virErrorPtr err = virGetLastError();
1984     if (err->code == VIR_ERR_NO_SUPPORT) {
1985       ERROR(PLUGIN_NAME
1986             " plugin: Disabled unsupported ExtraStats selector: fs_info");
1987       extra_stats &= ~(ex_stats_fs_info);
1988     }
1989
1990     return -1;
1991   }
1992
1993   for (int i = 0; i < mount_points_cnt; ++i) {
1994     if (fs_info_notify(domain, fs_info[i]) != 0) {
1995       ERROR(PLUGIN_NAME " plugin: failed to send file system notification "
1996                         "for mount point %s",
1997             fs_info[i]->mountpoint);
1998       ret = -1;
1999     }
2000     virDomainFSInfoFree(fs_info[i]);
2001   }
2002
2003   sfree(fs_info);
2004   return ret;
2005 }
2006
2007 #endif /* HAVE_FS_INFO */
2008
2009 #ifdef HAVE_JOB_STATS
2010 static void job_stats_submit(virDomainPtr domain, virTypedParameterPtr param) {
2011   value_t vl = {0};
2012
2013   if (param->type == VIR_TYPED_PARAM_INT)
2014     vl.derive = param->value.i;
2015   else if (param->type == VIR_TYPED_PARAM_UINT)
2016     vl.derive = param->value.ui;
2017   else if (param->type == VIR_TYPED_PARAM_LLONG)
2018     vl.derive = param->value.l;
2019   else if (param->type == VIR_TYPED_PARAM_ULLONG)
2020     vl.derive = param->value.ul;
2021   else if (param->type == VIR_TYPED_PARAM_DOUBLE)
2022     vl.derive = param->value.d;
2023   else if (param->type == VIR_TYPED_PARAM_BOOLEAN)
2024     vl.derive = param->value.b;
2025   else if (param->type == VIR_TYPED_PARAM_STRING) {
2026     submit_notif(domain, NOTIF_OKAY, param->value.s, "job_stats", param->field);
2027     return;
2028   } else {
2029     ERROR(PLUGIN_NAME " plugin: unrecognized virTypedParameterType");
2030     return;
2031   }
2032
2033   submit(domain, "job_stats", param->field, &vl, 1);
2034 }
2035
2036 static int get_job_stats(virDomainPtr domain) {
2037   int job_type = 0;
2038   int nparams = 0;
2039   virTypedParameterPtr params = NULL;
2040   int flags = (extra_stats & ex_stats_job_stats_completed)
2041                   ? VIR_DOMAIN_JOB_STATS_COMPLETED
2042                   : 0;
2043
2044   int ret = virDomainGetJobStats(domain, &job_type, &params, &nparams, flags);
2045   if (ret != 0) {
2046     ERROR(PLUGIN_NAME " plugin: virDomainGetJobStats failed: %d", ret);
2047
2048     virErrorPtr err = virGetLastError();
2049     // VIR_ERR_INVALID_ARG returned when VIR_DOMAIN_JOB_STATS_COMPLETED flag is
2050     // not supported by driver
2051     if (err->code == VIR_ERR_NO_SUPPORT || err->code == VIR_ERR_INVALID_ARG) {
2052       if (extra_stats & ex_stats_job_stats_completed)
2053         ERROR(PLUGIN_NAME " plugin: Disabled unsupported ExtraStats selector: "
2054                           "job_stats_completed");
2055       if (extra_stats & ex_stats_job_stats_background)
2056         ERROR(PLUGIN_NAME " plugin: Disabled unsupported ExtraStats selector: "
2057                           "job_stats_background");
2058       extra_stats &=
2059           ~(ex_stats_job_stats_completed | ex_stats_job_stats_background);
2060     }
2061     return -1;
2062   }
2063
2064   DEBUG(PLUGIN_NAME " plugin: job_type=%d nparams=%d", job_type, nparams);
2065
2066   for (int i = 0; i < nparams; ++i) {
2067     DEBUG(PLUGIN_NAME " plugin: param[%d] field=%s type=%d", i, params[i].field,
2068           params[i].type);
2069     job_stats_submit(domain, &params[i]);
2070   }
2071
2072   virTypedParamsFree(params, nparams);
2073   return 0;
2074 }
2075 #endif /* HAVE_JOB_STATS */
2076
2077 static int get_domain_metrics(domain_t *domain) {
2078   if (!domain || !domain->ptr) {
2079     ERROR(PLUGIN_NAME " plugin: get_domain_metrics: NULL pointer");
2080     return -1;
2081   }
2082
2083   virDomainInfo info;
2084   int status = virDomainGetInfo(domain->ptr, &info);
2085   if (status != 0) {
2086     ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
2087           status);
2088     return -1;
2089   }
2090
2091   if (extra_stats & ex_stats_domain_state) {
2092 #ifdef HAVE_DOM_REASON
2093     /* At this point we already know domain's state from virDomainGetInfo call,
2094      * however it doesn't provide a reason for entering particular state.
2095      * We need to get it from virDomainGetState.
2096      */
2097     GET_STATS(submit_domain_state, "domain reason", domain->ptr);
2098 #endif
2099   }
2100
2101   /* Gather remaining stats only for running domains */
2102   if (info.state != VIR_DOMAIN_RUNNING)
2103     return 0;
2104
2105 #ifdef HAVE_CPU_STATS
2106   if (extra_stats & ex_stats_pcpu)
2107     get_pcpu_stats(domain->ptr);
2108 #endif
2109
2110   cpu_submit(domain, info.cpuTime);
2111
2112   memory_submit(domain->ptr, (gauge_t)info.memory * 1024);
2113
2114   if (extra_stats & (ex_stats_vcpu | ex_stats_vcpupin))
2115     GET_STATS(get_vcpu_stats, "vcpu stats", domain->ptr, info.nrVirtCpu);
2116   if (extra_stats & ex_stats_memory)
2117     GET_STATS(get_memory_stats, "memory stats", domain->ptr);
2118
2119 #ifdef HAVE_PERF_STATS
2120   if (extra_stats & ex_stats_perf)
2121     GET_STATS(get_perf_events, "performance monitoring events", domain->ptr);
2122 #endif
2123
2124 #ifdef HAVE_FS_INFO
2125   if (extra_stats & ex_stats_fs_info)
2126     GET_STATS(get_fs_info, "file system info", domain->ptr);
2127 #endif
2128
2129 #ifdef HAVE_DISK_ERR
2130   if (extra_stats & ex_stats_disk_err)
2131     GET_STATS(get_disk_err, "disk errors", domain->ptr);
2132 #endif
2133
2134 #ifdef HAVE_JOB_STATS
2135   if (extra_stats &
2136       (ex_stats_job_stats_completed | ex_stats_job_stats_background))
2137     GET_STATS(get_job_stats, "job stats", domain->ptr);
2138 #endif
2139
2140   /* Update cached virDomainInfo. It has to be done after cpu_submit */
2141   memcpy(&domain->info, &info, sizeof(domain->info));
2142
2143   return 0;
2144 }
2145
2146 static int get_if_dev_stats(struct interface_device *if_dev) {
2147   virDomainInterfaceStatsStruct stats = {0};
2148   char *display_name = NULL;
2149
2150   if (!if_dev) {
2151     ERROR(PLUGIN_NAME " plugin: get_if_dev_stats: NULL pointer");
2152     return -1;
2153   }
2154
2155   switch (interface_format) {
2156   case if_address:
2157     display_name = if_dev->address;
2158     break;
2159   case if_number:
2160     display_name = if_dev->number;
2161     break;
2162   case if_name:
2163   default:
2164     display_name = if_dev->path;
2165   }
2166
2167   if (virDomainInterfaceStats(if_dev->dom, if_dev->path, &stats,
2168                               sizeof(stats)) != 0) {
2169     ERROR(PLUGIN_NAME " plugin: virDomainInterfaceStats failed");
2170     return -1;
2171   }
2172
2173   if ((stats.rx_bytes != -1) && (stats.tx_bytes != -1))
2174     submit_derive2("if_octets", (derive_t)stats.rx_bytes,
2175                    (derive_t)stats.tx_bytes, if_dev->dom, display_name);
2176
2177   if ((stats.rx_packets != -1) && (stats.tx_packets != -1))
2178     submit_derive2("if_packets", (derive_t)stats.rx_packets,
2179                    (derive_t)stats.tx_packets, if_dev->dom, display_name);
2180
2181   if ((stats.rx_errs != -1) && (stats.tx_errs != -1))
2182     submit_derive2("if_errors", (derive_t)stats.rx_errs,
2183                    (derive_t)stats.tx_errs, if_dev->dom, display_name);
2184
2185   if ((stats.rx_drop != -1) && (stats.tx_drop != -1))
2186     submit_derive2("if_dropped", (derive_t)stats.rx_drop,
2187                    (derive_t)stats.tx_drop, if_dev->dom, display_name);
2188   return 0;
2189 }
2190
2191 static int domain_lifecycle_event_cb(__attribute__((unused)) virConnectPtr con_,
2192                                      virDomainPtr dom, int event, int detail,
2193                                      __attribute__((unused)) void *opaque) {
2194   int domain_state = map_domain_event_to_state(event);
2195   int domain_reason = 0; /* 0 means UNKNOWN reason for any state */
2196 #ifdef HAVE_DOM_REASON
2197   domain_reason = map_domain_event_detail_to_reason(event, detail);
2198 #endif
2199   domain_state_submit_notif(dom, domain_state, domain_reason);
2200
2201   return 0;
2202 }
2203
2204 static void virt_eventloop_timeout_cb(int timer ATTRIBUTE_UNUSED,
2205                                       void *timer_info) {}
2206
2207 static int register_event_impl(void) {
2208   if (virEventRegisterDefaultImpl() < 0) {
2209     virErrorPtr err = virGetLastError();
2210     ERROR(PLUGIN_NAME
2211           " plugin: error while event implementation registering: %s",
2212           err && err->message ? err->message : "Unknown error");
2213     return -1;
2214   }
2215
2216   if (virEventAddTimeout(CDTIME_T_TO_MS(plugin_get_interval()),
2217                          virt_eventloop_timeout_cb, NULL, NULL) < 0) {
2218     virErrorPtr err = virGetLastError();
2219     ERROR(PLUGIN_NAME " plugin: virEventAddTimeout failed: %s",
2220           err && err->message ? err->message : "Unknown error");
2221     return -1;
2222   }
2223
2224   return 0;
2225 }
2226
2227 static void virt_notif_thread_set_active(virt_notif_thread_t *thread_data,
2228                                          const bool active) {
2229   assert(thread_data != NULL);
2230   pthread_mutex_lock(&thread_data->active_mutex);
2231   thread_data->is_active = active;
2232   pthread_mutex_unlock(&thread_data->active_mutex);
2233 }
2234
2235 static bool virt_notif_thread_is_active(virt_notif_thread_t *thread_data) {
2236   bool active = false;
2237
2238   assert(thread_data != NULL);
2239   pthread_mutex_lock(&thread_data->active_mutex);
2240   active = thread_data->is_active;
2241   pthread_mutex_unlock(&thread_data->active_mutex);
2242
2243   return active;
2244 }
2245
2246 /* worker function running default event implementation */
2247 static void *event_loop_worker(void *arg) {
2248   virt_notif_thread_t *thread_data = (virt_notif_thread_t *)arg;
2249
2250   while (virt_notif_thread_is_active(thread_data)) {
2251     if (virEventRunDefaultImpl() < 0) {
2252       virErrorPtr err = virGetLastError();
2253       ERROR(PLUGIN_NAME " plugin: failed to run event loop: %s\n",
2254             err && err->message ? err->message : "Unknown error");
2255     }
2256   }
2257
2258   return NULL;
2259 }
2260
2261 static int virt_notif_thread_init(virt_notif_thread_t *thread_data) {
2262   assert(thread_data != NULL);
2263
2264   int ret = pthread_mutex_init(&thread_data->active_mutex, NULL);
2265   if (ret != 0) {
2266     ERROR(PLUGIN_NAME " plugin: Failed to initialize mutex, err %u", ret);
2267     return ret;
2268   }
2269
2270   /**
2271    * '0' and positive integers are meaningful ID's, therefore setting
2272    * domain_event_cb_id to '-1'
2273    */
2274   thread_data->domain_event_cb_id = -1;
2275   pthread_mutex_lock(&thread_data->active_mutex);
2276   thread_data->is_active = false;
2277   pthread_mutex_unlock(&thread_data->active_mutex);
2278
2279   return 0;
2280 }
2281
2282 /* register domain event callback and start event loop thread */
2283 static int start_event_loop(virt_notif_thread_t *thread_data) {
2284   assert(thread_data != NULL);
2285   thread_data->domain_event_cb_id = virConnectDomainEventRegisterAny(
2286       conn, NULL, VIR_DOMAIN_EVENT_ID_LIFECYCLE,
2287       VIR_DOMAIN_EVENT_CALLBACK(domain_lifecycle_event_cb), NULL, NULL);
2288   if (thread_data->domain_event_cb_id == -1) {
2289     ERROR(PLUGIN_NAME " plugin: error while callback registering");
2290     return -1;
2291   }
2292
2293   DEBUG(PLUGIN_NAME " plugin: starting event loop");
2294
2295   virt_notif_thread_set_active(thread_data, 1);
2296   if (pthread_create(&thread_data->event_loop_tid, NULL, event_loop_worker,
2297                      thread_data)) {
2298     ERROR(PLUGIN_NAME " plugin: failed event loop thread creation");
2299     virt_notif_thread_set_active(thread_data, 0);
2300     virConnectDomainEventDeregisterAny(conn, thread_data->domain_event_cb_id);
2301     thread_data->domain_event_cb_id = -1;
2302     return -1;
2303   }
2304
2305   return 0;
2306 }
2307
2308 /* stop event loop thread and deregister callback */
2309 static void stop_event_loop(virt_notif_thread_t *thread_data) {
2310
2311   DEBUG(PLUGIN_NAME " plugin: stopping event loop");
2312
2313   /* Stopping loop */
2314   if (virt_notif_thread_is_active(thread_data)) {
2315     virt_notif_thread_set_active(thread_data, 0);
2316     if (pthread_join(notif_thread.event_loop_tid, NULL) != 0)
2317       ERROR(PLUGIN_NAME " plugin: stopping notification thread failed");
2318   }
2319
2320   /* ... and de-registering event handler */
2321   if (conn != NULL && thread_data->domain_event_cb_id != -1) {
2322     virConnectDomainEventDeregisterAny(conn, thread_data->domain_event_cb_id);
2323     thread_data->domain_event_cb_id = -1;
2324   }
2325 }
2326
2327 static int persistent_domains_state_notification(void) {
2328   int status = 0;
2329   int n;
2330 #ifdef HAVE_LIST_ALL_DOMAINS
2331   virDomainPtr *domains = NULL;
2332   n = virConnectListAllDomains(conn, &domains,
2333                                VIR_CONNECT_LIST_DOMAINS_PERSISTENT);
2334   if (n < 0) {
2335     VIRT_ERROR(conn, "reading list of persistent domains");
2336     status = -1;
2337   } else {
2338     DEBUG(PLUGIN_NAME " plugin: getting state of %i persistent domains", n);
2339     /* Fetch each persistent domain's state and notify it */
2340     int n_notified = n;
2341     for (int i = 0; i < n; ++i) {
2342       status = get_domain_state_notify(domains[i]);
2343       if (status != 0) {
2344         n_notified--;
2345         ERROR(PLUGIN_NAME " plugin: could not notify state of domain %s",
2346               virDomainGetName(domains[i]));
2347       }
2348       virDomainFree(domains[i]);
2349     }
2350
2351     sfree(domains);
2352     DEBUG(PLUGIN_NAME " plugin: notified state of %i persistent domains",
2353           n_notified);
2354   }
2355 #else
2356   n = virConnectNumOfDomains(conn);
2357   if (n > 0) {
2358     int *domids;
2359     /* Get list of domains. */
2360     domids = calloc(n, sizeof(*domids));
2361     if (domids == NULL) {
2362       ERROR(PLUGIN_NAME " plugin: calloc failed.");
2363       return -1;
2364     }
2365     n = virConnectListDomains(conn, domids, n);
2366     if (n < 0) {
2367       VIRT_ERROR(conn, "reading list of domains");
2368       sfree(domids);
2369       return -1;
2370     }
2371     /* Fetch info of each active domain and notify it */
2372     for (int i = 0; i < n; ++i) {
2373       virDomainInfo info;
2374       virDomainPtr dom = NULL;
2375       dom = virDomainLookupByID(conn, domids[i]);
2376       if (dom == NULL) {
2377         VIRT_ERROR(conn, "virDomainLookupByID");
2378         /* Could be that the domain went away -- ignore it anyway. */
2379         continue;
2380       }
2381       status = virDomainGetInfo(dom, &info);
2382       if (status == 0)
2383         /* virDomainGetState is not available. Submit 0, which corresponds to
2384          * unknown reason. */
2385         domain_state_submit_notif(dom, info.state, 0);
2386       else
2387         ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
2388               status);
2389
2390       virDomainFree(dom);
2391     }
2392     sfree(domids);
2393   }
2394 #endif
2395
2396   return status;
2397 }
2398
2399 static int lv_read(user_data_t *ud) {
2400   if (ud->data == NULL) {
2401     ERROR(PLUGIN_NAME " plugin: NULL userdata");
2402     return -1;
2403   }
2404
2405   struct lv_read_instance *inst = ud->data;
2406   struct lv_read_state *state = &inst->read_state;
2407
2408   if (inst->id == 0)
2409     if (lv_connect() < 0)
2410       return -1;
2411
2412   /* Wait until inst#0 establish connection */
2413   if (conn == NULL) {
2414     DEBUG(PLUGIN_NAME " plugin#%s: Wait until inst#0 establish connection",
2415           inst->tag);
2416     return 0;
2417   }
2418
2419   int ret = virConnectIsAlive(conn);
2420   if (ret == 0) { /* Connection lost */
2421     if (inst->id == 0) {
2422       c_complain(LOG_ERR, &conn_complain,
2423                  PLUGIN_NAME " plugin: Lost connection.");
2424
2425       if (!persistent_notification)
2426         stop_event_loop(&notif_thread);
2427
2428       lv_disconnect();
2429       last_refresh = 0;
2430     }
2431     return -1;
2432   }
2433
2434   time_t t;
2435   time(&t);
2436
2437   /* Need to refresh domain or device lists? */
2438   if ((last_refresh == (time_t)0) ||
2439       ((interval > 0) && ((last_refresh + interval) <= t))) {
2440     if (refresh_lists(inst) != 0) {
2441       if (inst->id == 0) {
2442         if (!persistent_notification)
2443           stop_event_loop(&notif_thread);
2444         lv_disconnect();
2445       }
2446       return -1;
2447     }
2448     last_refresh = t;
2449   }
2450
2451   /* persistent domains state notifications are handled by instance 0 */
2452   if (inst->id == 0 && persistent_notification) {
2453     int status = persistent_domains_state_notification();
2454     if (status != 0)
2455       DEBUG(PLUGIN_NAME " plugin: persistent_domains_state_notifications "
2456                         "returned with status %i",
2457             status);
2458   }
2459
2460 #if COLLECT_DEBUG
2461   for (int i = 0; i < state->nr_domains; ++i)
2462     DEBUG(PLUGIN_NAME " plugin: domain %s",
2463           virDomainGetName(state->domains[i].ptr));
2464   for (int i = 0; i < state->nr_block_devices; ++i)
2465     DEBUG(PLUGIN_NAME " plugin: block device %d %s:%s", i,
2466           virDomainGetName(state->block_devices[i].dom),
2467           state->block_devices[i].path);
2468   for (int i = 0; i < state->nr_interface_devices; ++i)
2469     DEBUG(PLUGIN_NAME " plugin: interface device %d %s:%s", i,
2470           virDomainGetName(state->interface_devices[i].dom),
2471           state->interface_devices[i].path);
2472 #endif
2473
2474   /* Get domains' metrics */
2475   for (int i = 0; i < state->nr_domains; ++i) {
2476     domain_t *dom = &state->domains[i];
2477     int status = 0;
2478     if (dom->active)
2479       status = get_domain_metrics(dom);
2480 #ifdef HAVE_DOM_REASON
2481     else if (extra_stats & ex_stats_domain_state)
2482       status = submit_domain_state(dom->ptr);
2483 #endif
2484
2485     if (status != 0)
2486       ERROR(PLUGIN_NAME " plugin: failed to get metrics for domain=%s",
2487             virDomainGetName(dom->ptr));
2488   }
2489
2490   /* Get block device stats for each domain. */
2491   for (int i = 0; i < state->nr_block_devices; ++i) {
2492     int status = get_block_device_stats(&state->block_devices[i]);
2493     if (status != 0)
2494       ERROR(PLUGIN_NAME
2495             " plugin: failed to get stats for block device (%s) in domain %s",
2496             state->block_devices[i].path,
2497             virDomainGetName(state->block_devices[i].dom));
2498   }
2499
2500   /* Get interface stats for each domain. */
2501   for (int i = 0; i < state->nr_interface_devices; ++i) {
2502     int status = get_if_dev_stats(&state->interface_devices[i]);
2503     if (status != 0)
2504       ERROR(
2505           PLUGIN_NAME
2506           " plugin: failed to get interface stats for device (%s) in domain %s",
2507           state->interface_devices[i].path,
2508           virDomainGetName(state->interface_devices[i].dom));
2509   }
2510
2511   return 0;
2512 }
2513
2514 static int lv_init_instance(size_t i, plugin_read_cb callback) {
2515   struct lv_user_data *lv_ud = &(lv_read_user_data[i]);
2516   struct lv_read_instance *inst = &(lv_ud->inst);
2517
2518   memset(lv_ud, 0, sizeof(*lv_ud));
2519
2520   ssnprintf(inst->tag, sizeof(inst->tag), "%s-%" PRIsz, PLUGIN_NAME, i);
2521   inst->id = i;
2522
2523   user_data_t *ud = &(lv_ud->ud);
2524   ud->data = inst;
2525   ud->free_func = NULL;
2526
2527   INFO(PLUGIN_NAME " plugin: reader %s initialized", inst->tag);
2528
2529   return plugin_register_complex_read(NULL, inst->tag, callback, 0, ud);
2530 }
2531
2532 static void lv_clean_read_state(struct lv_read_state *state) {
2533   free_block_devices(state);
2534   free_interface_devices(state);
2535   free_domains(state);
2536 }
2537
2538 static void lv_fini_instance(size_t i) {
2539   struct lv_read_instance *inst = &(lv_read_user_data[i].inst);
2540   struct lv_read_state *state = &(inst->read_state);
2541
2542   lv_clean_read_state(state);
2543
2544   INFO(PLUGIN_NAME " plugin: reader %s finalized", inst->tag);
2545 }
2546
2547 static int lv_init(void) {
2548   if (virInitialize() != 0)
2549     return -1;
2550
2551   /* Init ignorelists if there was no explicit configuration */
2552   if (lv_init_ignorelists() != 0)
2553     return -1;
2554
2555   if (!persistent_notification)
2556     if (virt_notif_thread_init(&notif_thread) != 0)
2557       return -1;
2558
2559   lv_connect();
2560
2561   DEBUG(PLUGIN_NAME " plugin: starting %i instances", nr_instances);
2562
2563   for (int i = 0; i < nr_instances; ++i)
2564     if (lv_init_instance(i, lv_read) != 0)
2565       return -1;
2566
2567   return 0;
2568 }
2569
2570 /*
2571  * returns 0 on success and <0 on error
2572  */
2573 static int lv_domain_get_tag(xmlXPathContextPtr xpath_ctx, const char *dom_name,
2574                              char *dom_tag) {
2575   char xpath_str[BUFFER_MAX_LEN] = {'\0'};
2576   xmlXPathObjectPtr xpath_obj = NULL;
2577   xmlNodePtr xml_node = NULL;
2578   int ret = -1;
2579   int err;
2580
2581   err = xmlXPathRegisterNs(xpath_ctx,
2582                            (const xmlChar *)METADATA_VM_PARTITION_PREFIX,
2583                            (const xmlChar *)METADATA_VM_PARTITION_URI);
2584   if (err) {
2585     ERROR(PLUGIN_NAME " plugin: xmlXpathRegisterNs(%s, %s) failed on domain %s",
2586           METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_URI, dom_name);
2587     goto done;
2588   }
2589
2590   ssnprintf(xpath_str, sizeof(xpath_str), "/domain/metadata/%s:%s/text()",
2591             METADATA_VM_PARTITION_PREFIX, METADATA_VM_PARTITION_ELEMENT);
2592   xpath_obj = xmlXPathEvalExpression((xmlChar *)xpath_str, xpath_ctx);
2593   if (xpath_obj == NULL) {
2594     ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) failed on domain %s",
2595           xpath_str, dom_name);
2596     goto done;
2597   }
2598
2599   if (xpath_obj->type != XPATH_NODESET) {
2600     ERROR(PLUGIN_NAME " plugin: xmlXPathEval(%s) unexpected return type %d "
2601                       "(wanted %d) on domain %s",
2602           xpath_str, xpath_obj->type, XPATH_NODESET, dom_name);
2603     goto done;
2604   }
2605
2606   /*
2607    * from now on there is no real error, it's ok if a domain
2608    * doesn't have the metadata partition tag.
2609    */
2610   ret = 0;
2611   if (xpath_obj->nodesetval == NULL || xpath_obj->nodesetval->nodeNr != 1) {
2612     DEBUG(PLUGIN_NAME " plugin: xmlXPathEval(%s) return nodeset size=%i "
2613                       "expected=1 on domain %s",
2614           xpath_str,
2615           (xpath_obj->nodesetval == NULL) ? 0 : xpath_obj->nodesetval->nodeNr,
2616           dom_name);
2617   } else {
2618     xml_node = xpath_obj->nodesetval->nodeTab[0];
2619     sstrncpy(dom_tag, (const char *)xml_node->content, PARTITION_TAG_MAX_LEN);
2620   }
2621
2622 done:
2623   /* deregister to clean up */
2624   err = xmlXPathRegisterNs(xpath_ctx,
2625                            (const xmlChar *)METADATA_VM_PARTITION_PREFIX, NULL);
2626   if (err) {
2627     /* we can't really recover here */
2628     ERROR(PLUGIN_NAME
2629           " plugin: deregistration of namespace %s failed for domain %s",
2630           METADATA_VM_PARTITION_PREFIX, dom_name);
2631   }
2632   if (xpath_obj)
2633     xmlXPathFreeObject(xpath_obj);
2634
2635   return ret;
2636 }
2637
2638 static int is_known_tag(const char *dom_tag) {
2639   for (int i = 0; i < nr_instances; ++i)
2640     if (!strcmp(dom_tag, lv_read_user_data[i].inst.tag))
2641       return 1;
2642   return 0;
2643 }
2644
2645 static int lv_instance_include_domain(struct lv_read_instance *inst,
2646                                       const char *dom_name,
2647                                       const char *dom_tag) {
2648   if ((dom_tag[0] != '\0') && (strcmp(dom_tag, inst->tag) == 0))
2649     return 1;
2650
2651   /* instance#0 will always be there, so it is in charge of extra duties */
2652   if (inst->id == 0) {
2653     if (dom_tag[0] == '\0' || !is_known_tag(dom_tag)) {
2654       DEBUG(PLUGIN_NAME " plugin#%s: refreshing domain %s "
2655                         "with unknown tag '%s'",
2656             inst->tag, dom_name, dom_tag);
2657       return 1;
2658     }
2659   }
2660
2661   return 0;
2662 }
2663
2664 static void lv_add_block_devices(struct lv_read_state *state, virDomainPtr dom,
2665                                  const char *domname,
2666                                  xmlXPathContextPtr xpath_ctx) {
2667   xmlXPathObjectPtr xpath_obj =
2668       xmlXPathEval((const xmlChar *)"/domain/devices/disk", xpath_ctx);
2669
2670   if (xpath_obj == NULL) {
2671     DEBUG(PLUGIN_NAME " plugin: no disk xpath-object found for domain %s",
2672           domname);
2673     return;
2674   }
2675
2676   if (xpath_obj->type != XPATH_NODESET || xpath_obj->nodesetval == NULL) {
2677     DEBUG(PLUGIN_NAME " plugin: no disk node found for domain %s", domname);
2678     goto cleanup;
2679   }
2680
2681   xmlNodeSetPtr xml_block_devices = xpath_obj->nodesetval;
2682   for (int i = 0; i < xml_block_devices->nodeNr; ++i) {
2683     xmlNodePtr xml_device = xpath_obj->nodesetval->nodeTab[i];
2684     char *path_str = NULL;
2685     char *source_str = NULL;
2686
2687     if (!xml_device)
2688       continue;
2689
2690     /* Fetching path and source for block device */
2691     for (xmlNodePtr child = xml_device->children; child; child = child->next) {
2692       if (child->type != XML_ELEMENT_NODE)
2693         continue;
2694
2695       /* we are interested only in either "target" or "source" elements */
2696       if (xmlStrEqual(child->name, (const xmlChar *)"target"))
2697         path_str = (char *)xmlGetProp(child, (const xmlChar *)"dev");
2698       else if (xmlStrEqual(child->name, (const xmlChar *)"source")) {
2699         /* name of the source is located in "dev" or "file" element (it depends
2700          * on type of source). Trying "dev" at first*/
2701         source_str = (char *)xmlGetProp(child, (const xmlChar *)"dev");
2702         if (!source_str)
2703           source_str = (char *)xmlGetProp(child, (const xmlChar *)"file");
2704       }
2705       /* ignoring any other element*/
2706     }
2707
2708     /* source_str will be interpreted as a device path if blockdevice_format
2709      *  param is set to 'source'. */
2710     const char *device_path =
2711         (blockdevice_format == source) ? source_str : path_str;
2712
2713     if (!device_path) {
2714       /* no path found and we can't add block_device without it */
2715       WARNING(PLUGIN_NAME " plugin: could not generate device path for disk in "
2716                           "domain %s - disk device will be ignored in reports",
2717               domname);
2718       goto cont;
2719     }
2720
2721     if (ignore_device_match(il_block_devices, domname, device_path) == 0) {
2722       /* we only have to store information whether 'source' exists or not */
2723       bool has_source = (source_str != NULL) ? true : false;
2724
2725       add_block_device(state, dom, device_path, has_source);
2726     }
2727
2728   cont:
2729     if (path_str)
2730       xmlFree(path_str);
2731
2732     if (source_str)
2733       xmlFree(source_str);
2734   }
2735
2736 cleanup:
2737   xmlXPathFreeObject(xpath_obj);
2738 }
2739
2740 static void lv_add_network_interfaces(struct lv_read_state *state,
2741                                       virDomainPtr dom, const char *domname,
2742                                       xmlXPathContextPtr xpath_ctx) {
2743   xmlXPathObjectPtr xpath_obj = xmlXPathEval(
2744       (xmlChar *)"/domain/devices/interface[target[@dev]]", xpath_ctx);
2745
2746   if (xpath_obj == NULL)
2747     return;
2748
2749   if (xpath_obj->type != XPATH_NODESET || xpath_obj->nodesetval == NULL) {
2750     xmlXPathFreeObject(xpath_obj);
2751     return;
2752   }
2753
2754   xmlNodeSetPtr xml_interfaces = xpath_obj->nodesetval;
2755
2756   for (int j = 0; j < xml_interfaces->nodeNr; ++j) {
2757     char *path = NULL;
2758     char *address = NULL;
2759     const int itf_number = j + 1;
2760
2761     xmlNodePtr xml_interface = xml_interfaces->nodeTab[j];
2762     if (!xml_interface)
2763       continue;
2764
2765     for (xmlNodePtr child = xml_interface->children; child;
2766          child = child->next) {
2767       if (child->type != XML_ELEMENT_NODE)
2768         continue;
2769
2770       if (xmlStrEqual(child->name, (const xmlChar *)"target")) {
2771         path = (char *)xmlGetProp(child, (const xmlChar *)"dev");
2772         if (!path)
2773           continue;
2774       } else if (xmlStrEqual(child->name, (const xmlChar *)"mac")) {
2775         address = (char *)xmlGetProp(child, (const xmlChar *)"address");
2776         if (!address)
2777           continue;
2778       }
2779     }
2780
2781     bool device_ignored = false;
2782     switch (interface_format) {
2783     case if_name:
2784       if (ignore_device_match(il_interface_devices, domname, path) != 0)
2785         device_ignored = true;
2786       break;
2787     case if_address:
2788       if (ignore_device_match(il_interface_devices, domname, address) != 0)
2789         device_ignored = true;
2790       break;
2791     case if_number: {
2792       char number_string[4];
2793       ssnprintf(number_string, sizeof(number_string), "%d", itf_number);
2794       if (ignore_device_match(il_interface_devices, domname, number_string) !=
2795           0)
2796         device_ignored = true;
2797     } break;
2798     default:
2799       ERROR(PLUGIN_NAME " plugin: Unknown interface_format option: %d",
2800             interface_format);
2801     }
2802
2803     if (!device_ignored)
2804       add_interface_device(state, dom, path, address, itf_number);
2805
2806     if (path)
2807       xmlFree(path);
2808     if (address)
2809       xmlFree(address);
2810   }
2811   xmlXPathFreeObject(xpath_obj);
2812 }
2813
2814 static bool is_domain_ignored(virDomainPtr dom) {
2815   const char *domname = virDomainGetName(dom);
2816
2817   if (domname == NULL) {
2818     VIRT_ERROR(conn, "virDomainGetName failed, ignoring domain");
2819     return true;
2820   }
2821
2822   if (ignorelist_match(il_domains, domname) != 0) {
2823     DEBUG(PLUGIN_NAME
2824           " plugin: ignoring domain '%s' because of ignorelist option",
2825           domname);
2826     return true;
2827   }
2828
2829   return false;
2830 }
2831
2832 static int refresh_lists(struct lv_read_instance *inst) {
2833   struct lv_read_state *state = &inst->read_state;
2834   int n;
2835
2836 #ifndef HAVE_LIST_ALL_DOMAINS
2837   n = virConnectNumOfDomains(conn);
2838   if (n < 0) {
2839     VIRT_ERROR(conn, "reading number of domains");
2840     return -1;
2841   }
2842 #endif
2843
2844   lv_clean_read_state(state);
2845
2846 #ifndef HAVE_LIST_ALL_DOMAINS
2847   if (n == 0)
2848     goto end;
2849 #endif
2850
2851 #ifdef HAVE_LIST_ALL_DOMAINS
2852   virDomainPtr *domains, *domains_inactive;
2853   int m = virConnectListAllDomains(conn, &domains_inactive,
2854                                    VIR_CONNECT_LIST_DOMAINS_INACTIVE);
2855   n = virConnectListAllDomains(conn, &domains, VIR_CONNECT_LIST_DOMAINS_ACTIVE);
2856 #else
2857   /* Get list of domains. */
2858   int *domids = calloc(n, sizeof(*domids));
2859   if (domids == NULL) {
2860     ERROR(PLUGIN_NAME " plugin: calloc failed.");
2861     return -1;
2862   }
2863
2864   n = virConnectListDomains(conn, domids, n);
2865 #endif
2866
2867   if (n < 0) {
2868     VIRT_ERROR(conn, "reading list of domains");
2869 #ifndef HAVE_LIST_ALL_DOMAINS
2870     sfree(domids);
2871 #else
2872     for (int i = 0; i < m; ++i)
2873       virDomainFree(domains_inactive[i]);
2874     sfree(domains_inactive);
2875 #endif
2876     return -1;
2877   }
2878
2879 #ifdef HAVE_LIST_ALL_DOMAINS
2880   for (int i = 0; i < m; ++i)
2881     if (is_domain_ignored(domains_inactive[i]) ||
2882         add_domain(state, domains_inactive[i], 0) < 0) {
2883       /* domain ignored or failed during adding to domains list*/
2884       virDomainFree(domains_inactive[i]);
2885       domains_inactive[i] = NULL;
2886       continue;
2887     }
2888 #endif
2889
2890   /* Fetch each domain and add it to the list, unless ignore. */
2891   for (int i = 0; i < n; ++i) {
2892
2893 #ifdef HAVE_LIST_ALL_DOMAINS
2894     virDomainPtr dom = domains[i];
2895 #else
2896     virDomainPtr dom = virDomainLookupByID(conn, domids[i]);
2897     if (dom == NULL) {
2898       VIRT_ERROR(conn, "virDomainLookupByID");
2899       /* Could be that the domain went away -- ignore it anyway. */
2900       continue;
2901     }
2902 #endif
2903
2904     if (is_domain_ignored(dom) || add_domain(state, dom, 1) < 0) {
2905       /*
2906        * domain ignored or failed during adding to domains list
2907        *
2908        * When domain is already tracked, then there is
2909        * no problem with memory handling (will be freed
2910        * with the rest of domains cached data)
2911        * But in case of error like this (error occurred
2912        * before adding domain to track) we have to take
2913        * care it ourselves and call virDomainFree
2914        */
2915       virDomainFree(dom);
2916       continue;
2917     }
2918
2919     const char *domname = virDomainGetName(dom);
2920     if (domname == NULL) {
2921       VIRT_ERROR(conn, "virDomainGetName");
2922       continue;
2923     }
2924
2925     virDomainInfo info;
2926     int status = virDomainGetInfo(dom, &info);
2927     if (status != 0) {
2928       ERROR(PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.",
2929             status);
2930       continue;
2931     }
2932
2933     if (info.state != VIR_DOMAIN_RUNNING) {
2934       DEBUG(PLUGIN_NAME " plugin: skipping inactive domain %s", domname);
2935       continue;
2936     }
2937
2938     /* Get a list of devices for this domain. */
2939     xmlDocPtr xml_doc = NULL;
2940     xmlXPathContextPtr xpath_ctx = NULL;
2941
2942     char *xml = virDomainGetXMLDesc(dom, 0);
2943     if (!xml) {
2944       VIRT_ERROR(conn, "virDomainGetXMLDesc");
2945       goto cont;
2946     }
2947
2948     /* Yuck, XML.  Parse out the devices. */
2949     xml_doc = xmlReadDoc((xmlChar *)xml, NULL, NULL, XML_PARSE_NONET);
2950     if (xml_doc == NULL) {
2951       VIRT_ERROR(conn, "xmlReadDoc");
2952       goto cont;
2953     }
2954
2955     xpath_ctx = xmlXPathNewContext(xml_doc);
2956
2957     char tag[PARTITION_TAG_MAX_LEN] = {'\0'};
2958     if (lv_domain_get_tag(xpath_ctx, domname, tag) < 0) {
2959       ERROR(PLUGIN_NAME " plugin: lv_domain_get_tag failed.");
2960       goto cont;
2961     }
2962
2963     if (!lv_instance_include_domain(inst, domname, tag))
2964       goto cont;
2965
2966     /* Block devices. */
2967     if (report_block_devices)
2968       lv_add_block_devices(state, dom, domname, xpath_ctx);
2969
2970     /* Network interfaces. */
2971     if (report_network_interfaces)
2972       lv_add_network_interfaces(state, dom, domname, xpath_ctx);
2973
2974   cont:
2975     if (xpath_ctx)
2976       xmlXPathFreeContext(xpath_ctx);
2977     if (xml_doc)
2978       xmlFreeDoc(xml_doc);
2979     sfree(xml);
2980   }
2981
2982 #ifdef HAVE_LIST_ALL_DOMAINS
2983   /* NOTE: domains_active and domains_inactive data will be cleared during
2984      refresh of all domains (inside lv_clean_read_state function) so we need
2985      to free here only allocated arrays */
2986   sfree(domains);
2987   sfree(domains_inactive);
2988 #else
2989   sfree(domids);
2990
2991 end:
2992 #endif
2993
2994   DEBUG(PLUGIN_NAME " plugin#%s: refreshing"
2995                     " domains=%i block_devices=%i iface_devices=%i",
2996         inst->tag, state->nr_domains, state->nr_block_devices,
2997         state->nr_interface_devices);
2998
2999   return 0;
3000 }
3001
3002 static void free_domains(struct lv_read_state *state) {
3003   if (state->domains) {
3004     for (int i = 0; i < state->nr_domains; ++i)
3005       virDomainFree(state->domains[i].ptr);
3006     sfree(state->domains);
3007   }
3008   state->domains = NULL;
3009   state->nr_domains = 0;
3010 }
3011
3012 static int add_domain(struct lv_read_state *state, virDomainPtr dom,
3013                       bool active) {
3014   int new_size = sizeof(state->domains[0]) * (state->nr_domains + 1);
3015
3016   domain_t *new_ptr = realloc(state->domains, new_size);
3017   if (new_ptr == NULL) {
3018     ERROR(PLUGIN_NAME " plugin: realloc failed in add_domain()");
3019     return -1;
3020   }
3021
3022   state->domains = new_ptr;
3023   state->domains[state->nr_domains].ptr = dom;
3024   state->domains[state->nr_domains].active = active;
3025   memset(&state->domains[state->nr_domains].info, 0,
3026          sizeof(state->domains[state->nr_domains].info));
3027
3028   return state->nr_domains++;
3029 }
3030
3031 static void free_block_devices(struct lv_read_state *state) {
3032   if (state->block_devices) {
3033     for (int i = 0; i < state->nr_block_devices; ++i)
3034       sfree(state->block_devices[i].path);
3035     sfree(state->block_devices);
3036   }
3037   state->block_devices = NULL;
3038   state->nr_block_devices = 0;
3039 }
3040
3041 static int add_block_device(struct lv_read_state *state, virDomainPtr dom,
3042                             const char *path, bool has_source) {
3043
3044   char *path_copy = strdup(path);
3045   if (!path_copy)
3046     return -1;
3047
3048   int new_size =
3049       sizeof(state->block_devices[0]) * (state->nr_block_devices + 1);
3050
3051   struct block_device *new_ptr = realloc(state->block_devices, new_size);
3052   if (new_ptr == NULL) {
3053     sfree(path_copy);
3054     return -1;
3055   }
3056   state->block_devices = new_ptr;
3057   state->block_devices[state->nr_block_devices].dom = dom;
3058   state->block_devices[state->nr_block_devices].path = path_copy;
3059   state->block_devices[state->nr_block_devices].has_source = has_source;
3060   return state->nr_block_devices++;
3061 }
3062
3063 static void free_interface_devices(struct lv_read_state *state) {
3064   if (state->interface_devices) {
3065     for (int i = 0; i < state->nr_interface_devices; ++i) {
3066       sfree(state->interface_devices[i].path);
3067       sfree(state->interface_devices[i].address);
3068       sfree(state->interface_devices[i].number);
3069     }
3070     sfree(state->interface_devices);
3071   }
3072   state->interface_devices = NULL;
3073   state->nr_interface_devices = 0;
3074 }
3075
3076 static int add_interface_device(struct lv_read_state *state, virDomainPtr dom,
3077                                 const char *path, const char *address,
3078                                 unsigned int number) {
3079
3080   if ((path == NULL) || (address == NULL))
3081     return EINVAL;
3082
3083   char *path_copy = strdup(path);
3084   if (!path_copy)
3085     return -1;
3086
3087   char *address_copy = strdup(address);
3088   if (!address_copy) {
3089     sfree(path_copy);
3090     return -1;
3091   }
3092
3093   char number_string[21];
3094   ssnprintf(number_string, sizeof(number_string), "interface-%u", number);
3095   char *number_copy = strdup(number_string);
3096   if (!number_copy) {
3097     sfree(path_copy);
3098     sfree(address_copy);
3099     return -1;
3100   }
3101
3102   int new_size =
3103       sizeof(state->interface_devices[0]) * (state->nr_interface_devices + 1);
3104
3105   struct interface_device *new_ptr =
3106       realloc(state->interface_devices, new_size);
3107   if (new_ptr == NULL) {
3108     sfree(path_copy);
3109     sfree(address_copy);
3110     sfree(number_copy);
3111     return -1;
3112   }
3113
3114   state->interface_devices = new_ptr;
3115   state->interface_devices[state->nr_interface_devices].dom = dom;
3116   state->interface_devices[state->nr_interface_devices].path = path_copy;
3117   state->interface_devices[state->nr_interface_devices].address = address_copy;
3118   state->interface_devices[state->nr_interface_devices].number = number_copy;
3119   return state->nr_interface_devices++;
3120 }
3121
3122 static int ignore_device_match(ignorelist_t *il, const char *domname,
3123                                const char *devpath) {
3124   if ((domname == NULL) || (devpath == NULL))
3125     return 0;
3126
3127   size_t n = strlen(domname) + strlen(devpath) + 2;
3128   char *name = malloc(n);
3129   if (name == NULL) {
3130     ERROR(PLUGIN_NAME " plugin: malloc failed.");
3131     return 0;
3132   }
3133   ssnprintf(name, n, "%s:%s", domname, devpath);
3134   int r = ignorelist_match(il, name);
3135   sfree(name);
3136   return r;
3137 }
3138
3139 static int lv_shutdown(void) {
3140   for (int i = 0; i < nr_instances; ++i) {
3141     lv_fini_instance(i);
3142   }
3143
3144   if (!persistent_notification)
3145     stop_event_loop(&notif_thread);
3146
3147   lv_disconnect();
3148
3149   ignorelist_free(il_domains);
3150   il_domains = NULL;
3151   ignorelist_free(il_block_devices);
3152   il_block_devices = NULL;
3153   ignorelist_free(il_interface_devices);
3154   il_interface_devices = NULL;
3155
3156   return 0;
3157 }
3158
3159 void module_register(void) {
3160   plugin_register_complex_config("virt", lv_config);
3161   plugin_register_init(PLUGIN_NAME, lv_init);
3162   plugin_register_shutdown(PLUGIN_NAME, lv_shutdown);
3163 }