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