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