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