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