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