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