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