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