2c784e400ade8d7cbaeb7e20e1847e0e081df823
[collectd.git] / src / daemon / plugin.c
1 /**
2  * collectd - src/plugin.c
3  * Copyright (C) 2005-2014  Florian octo Forster
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Florian octo Forster <octo at collectd.org>
25  *   Sebastian Harl <sh at tokkee.org>
26  **/
27
28 /* _GNU_SOURCE is needed in Linux to use pthread_setname_np */
29 #define _GNU_SOURCE
30
31 #include "collectd.h"
32
33 #include "configfile.h"
34 #include "filter_chain.h"
35 #include "plugin.h"
36 #include "utils/avltree/avltree.h"
37 #include "utils/common/common.h"
38 #include "utils/heap/heap.h"
39 #include "utils_cache.h"
40 #include "utils_complain.h"
41 #include "utils_llist.h"
42 #include "utils_random.h"
43 #include "utils_time.h"
44
45 #ifdef WIN32
46 #define EXPORT __declspec(dllexport)
47 #include <sys/stat.h>
48 #include <unistd.h>
49 #else
50 #define EXPORT
51 #endif
52
53 #if HAVE_PTHREAD_NP_H
54 #include <pthread_np.h> /* for pthread_set_name_np(3) */
55 #endif
56
57 #include <dlfcn.h>
58
59 /*
60  * Private structures
61  */
62 struct callback_func_s {
63   void *cf_callback;
64   user_data_t cf_udata;
65   plugin_ctx_t cf_ctx;
66 };
67 typedef struct callback_func_s callback_func_t;
68
69 #define RF_SIMPLE 0
70 #define RF_COMPLEX 1
71 #define RF_REMOVE 65535
72 struct read_func_s {
73 /* `read_func_t' "inherits" from `callback_func_t'.
74  * The `rf_super' member MUST be the first one in this structure! */
75 #define rf_callback rf_super.cf_callback
76 #define rf_udata rf_super.cf_udata
77 #define rf_ctx rf_super.cf_ctx
78   callback_func_t rf_super;
79   char rf_group[DATA_MAX_NAME_LEN];
80   char *rf_name;
81   int rf_type;
82   cdtime_t rf_interval;
83   cdtime_t rf_effective_interval;
84   cdtime_t rf_next_read;
85 };
86 typedef struct read_func_s read_func_t;
87
88 struct write_queue_s;
89 typedef struct write_queue_s write_queue_t;
90 struct write_queue_s {
91   value_list_t *vl;
92   plugin_ctx_t ctx;
93   write_queue_t *next;
94 };
95
96 struct flush_callback_s {
97   char *name;
98   cdtime_t timeout;
99 };
100 typedef struct flush_callback_s flush_callback_t;
101
102 /*
103  * Private variables
104  */
105 static c_avl_tree_t *plugins_loaded;
106
107 static llist_t *list_init;
108 static llist_t *list_write;
109 static llist_t *list_flush;
110 static llist_t *list_missing;
111 static llist_t *list_shutdown;
112 static llist_t *list_log;
113 static llist_t *list_notification;
114
115 static fc_chain_t *pre_cache_chain;
116 static fc_chain_t *post_cache_chain;
117
118 static c_avl_tree_t *data_sets;
119
120 static char *plugindir;
121
122 #ifndef DEFAULT_MAX_READ_INTERVAL
123 #define DEFAULT_MAX_READ_INTERVAL TIME_T_TO_CDTIME_T_STATIC(86400)
124 #endif
125 static c_heap_t *read_heap;
126 static llist_t *read_list;
127 static int read_loop = 1;
128 static pthread_mutex_t read_lock = PTHREAD_MUTEX_INITIALIZER;
129 static pthread_cond_t read_cond = PTHREAD_COND_INITIALIZER;
130 static pthread_t *read_threads;
131 static size_t read_threads_num;
132 static cdtime_t max_read_interval = DEFAULT_MAX_READ_INTERVAL;
133
134 static write_queue_t *write_queue_head;
135 static write_queue_t *write_queue_tail;
136 static long write_queue_length;
137 static bool write_loop = true;
138 static pthread_mutex_t write_lock = PTHREAD_MUTEX_INITIALIZER;
139 static pthread_cond_t write_cond = PTHREAD_COND_INITIALIZER;
140 static pthread_t *write_threads;
141 static size_t write_threads_num;
142
143 static pthread_key_t plugin_ctx_key;
144 static bool plugin_ctx_key_initialized;
145
146 static long write_limit_high;
147 static long write_limit_low;
148
149 static pthread_mutex_t statistics_lock = PTHREAD_MUTEX_INITIALIZER;
150 static derive_t stats_values_dropped;
151 static bool record_statistics;
152
153 /*
154  * Static functions
155  */
156 static int plugin_dispatch_values_internal(value_list_t *vl);
157
158 static const char *plugin_get_dir(void) {
159   if (plugindir == NULL)
160     return PLUGINDIR;
161   else
162     return plugindir;
163 }
164
165 static int plugin_update_internal_statistics(void) { /* {{{ */
166   gauge_t copy_write_queue_length = (gauge_t)write_queue_length;
167
168   /* Initialize `vl' */
169   value_list_t vl = VALUE_LIST_INIT;
170   sstrncpy(vl.plugin, "collectd", sizeof(vl.plugin));
171   vl.interval = plugin_get_interval();
172
173   /* Write queue */
174   sstrncpy(vl.plugin_instance, "write_queue", sizeof(vl.plugin_instance));
175
176   /* Write queue : queue length */
177   vl.values = &(value_t){.gauge = copy_write_queue_length};
178   vl.values_len = 1;
179   sstrncpy(vl.type, "queue_length", sizeof(vl.type));
180   vl.type_instance[0] = 0;
181   plugin_dispatch_values(&vl);
182
183   /* Write queue : Values dropped (queue length > low limit) */
184   vl.values = &(value_t){.gauge = (gauge_t)stats_values_dropped};
185   vl.values_len = 1;
186   sstrncpy(vl.type, "derive", sizeof(vl.type));
187   sstrncpy(vl.type_instance, "dropped", sizeof(vl.type_instance));
188   plugin_dispatch_values(&vl);
189
190   /* Cache */
191   sstrncpy(vl.plugin_instance, "cache", sizeof(vl.plugin_instance));
192
193   /* Cache : Nb entry in cache tree */
194   vl.values = &(value_t){.gauge = (gauge_t)uc_get_size()};
195   vl.values_len = 1;
196   sstrncpy(vl.type, "cache_size", sizeof(vl.type));
197   vl.type_instance[0] = 0;
198   plugin_dispatch_values(&vl);
199
200   return 0;
201 } /* }}} int plugin_update_internal_statistics */
202
203 static void free_userdata(user_data_t const *ud) /* {{{ */
204 {
205   if (ud == NULL)
206     return;
207
208   if ((ud->data != NULL) && (ud->free_func != NULL)) {
209     ud->free_func(ud->data);
210   }
211 } /* }}} void free_userdata */
212
213 static void destroy_callback(callback_func_t *cf) /* {{{ */
214 {
215   if (cf == NULL)
216     return;
217   free_userdata(&cf->cf_udata);
218   sfree(cf);
219 } /* }}} void destroy_callback */
220
221 static void destroy_all_callbacks(llist_t **list) /* {{{ */
222 {
223   llentry_t *le;
224
225   if (*list == NULL)
226     return;
227
228   le = llist_head(*list);
229   while (le != NULL) {
230     llentry_t *le_next;
231
232     le_next = le->next;
233
234     sfree(le->key);
235     destroy_callback(le->value);
236     le->value = NULL;
237
238     le = le_next;
239   }
240
241   llist_destroy(*list);
242   *list = NULL;
243 } /* }}} void destroy_all_callbacks */
244
245 static void destroy_read_heap(void) /* {{{ */
246 {
247   if (read_heap == NULL)
248     return;
249
250   while (42) {
251     read_func_t *rf;
252
253     rf = c_heap_get_root(read_heap);
254     if (rf == NULL)
255       break;
256     sfree(rf->rf_name);
257     destroy_callback((callback_func_t *)rf);
258   }
259
260   c_heap_destroy(read_heap);
261   read_heap = NULL;
262 } /* }}} void destroy_read_heap */
263
264 static int register_callback(llist_t **list, /* {{{ */
265                              const char *name, callback_func_t *cf) {
266   llentry_t *le;
267   char *key;
268
269   if (*list == NULL) {
270     *list = llist_create();
271     if (*list == NULL) {
272       ERROR("plugin: register_callback: "
273             "llist_create failed.");
274       destroy_callback(cf);
275       return -1;
276     }
277   }
278
279   key = strdup(name);
280   if (key == NULL) {
281     ERROR("plugin: register_callback: strdup failed.");
282     destroy_callback(cf);
283     return -1;
284   }
285
286   le = llist_search(*list, name);
287   if (le == NULL) {
288     le = llentry_create(key, cf);
289     if (le == NULL) {
290       ERROR("plugin: register_callback: "
291             "llentry_create failed.");
292       sfree(key);
293       destroy_callback(cf);
294       return -1;
295     }
296
297     llist_append(*list, le);
298   } else {
299     callback_func_t *old_cf;
300
301     old_cf = le->value;
302     le->value = cf;
303
304     P_WARNING("register_callback: "
305               "a callback named `%s' already exists - "
306               "overwriting the old entry!",
307               name);
308
309     destroy_callback(old_cf);
310     sfree(key);
311   }
312
313   return 0;
314 } /* }}} int register_callback */
315
316 static void log_list_callbacks(llist_t **list, /* {{{ */
317                                const char *comment) {
318   char *str;
319   int len;
320   int i;
321   llentry_t *le;
322   int n;
323
324   n = llist_size(*list);
325   if (n == 0) {
326     INFO("%s: [none]", comment);
327     return;
328   }
329
330   char **keys = calloc(n, sizeof(*keys));
331   if (keys == NULL) {
332     ERROR("%s: failed to allocate memory for list of callbacks", comment);
333     return;
334   }
335
336   for (le = llist_head(*list), i = 0, len = 0; le != NULL; le = le->next, i++) {
337     keys[i] = le->key;
338     len += strlen(le->key) + 6;
339   }
340   str = malloc(len + 10);
341   if (str == NULL) {
342     ERROR("%s: failed to allocate memory for list of callbacks", comment);
343   } else {
344     *str = '\0';
345     strjoin(str, len, keys, n, "', '");
346     INFO("%s ['%s']", comment, str);
347     sfree(str);
348   }
349   sfree(keys);
350 } /* }}} void log_list_callbacks */
351
352 static int create_register_callback(llist_t **list, /* {{{ */
353                                     const char *name, void *callback,
354                                     user_data_t const *ud) {
355
356   if (name == NULL || callback == NULL)
357     return EINVAL;
358
359   callback_func_t *cf = calloc(1, sizeof(*cf));
360   if (cf == NULL) {
361     free_userdata(ud);
362     ERROR("plugin: create_register_callback: calloc failed.");
363     return ENOMEM;
364   }
365
366   cf->cf_callback = callback;
367   if (ud == NULL) {
368     cf->cf_udata = (user_data_t){
369         .data = NULL,
370         .free_func = NULL,
371     };
372   } else {
373     cf->cf_udata = *ud;
374   }
375
376   cf->cf_ctx = plugin_get_ctx();
377
378   return register_callback(list, name, cf);
379 } /* }}} int create_register_callback */
380
381 static int plugin_unregister(llist_t *list, const char *name) /* {{{ */
382 {
383   llentry_t *e;
384
385   if (list == NULL)
386     return -1;
387
388   e = llist_search(list, name);
389   if (e == NULL)
390     return -1;
391
392   llist_remove(list, e);
393
394   sfree(e->key);
395   destroy_callback(e->value);
396
397   llentry_destroy(e);
398
399   return 0;
400 } /* }}} int plugin_unregister */
401
402 /* plugin_load_file loads the shared object "file" and calls its
403  * "module_register" function. Returns zero on success, non-zero otherwise. */
404 static int plugin_load_file(char const *file, bool global) {
405   int flags = RTLD_NOW;
406   if (global)
407     flags |= RTLD_GLOBAL;
408
409   void *dlh = dlopen(file, flags);
410   if (dlh == NULL) {
411     char errbuf[1024] = "";
412
413     snprintf(errbuf, sizeof(errbuf),
414              "dlopen(\"%s\") failed: %s. "
415              "The most common cause for this problem is missing dependencies. "
416              "Use ldd(1) to check the dependencies of the plugin / shared "
417              "object.",
418              file, dlerror());
419
420     /* This error is printed to STDERR unconditionally. If list_log is NULL,
421      * plugin_log() will also print to STDERR. We avoid duplicate output by
422      * checking that the list of log handlers, list_log, is not NULL. */
423     fprintf(stderr, "ERROR: %s\n", errbuf);
424     if (list_log != NULL) {
425       ERROR("%s", errbuf);
426     }
427
428     return ENOENT;
429   }
430
431   void (*reg_handle)(void) = dlsym(dlh, "module_register");
432   if (reg_handle == NULL) {
433     ERROR("Couldn't find symbol \"module_register\" in \"%s\": %s\n", file,
434           dlerror());
435     dlclose(dlh);
436     return ENOENT;
437   }
438
439   (*reg_handle)();
440   return 0;
441 }
442
443 static void *plugin_read_thread(void __attribute__((unused)) * args) {
444   while (read_loop != 0) {
445     read_func_t *rf;
446     plugin_ctx_t old_ctx;
447     cdtime_t start;
448     cdtime_t now;
449     cdtime_t elapsed;
450     int status;
451     int rf_type;
452     int rc;
453
454     /* Get the read function that needs to be read next.
455      * We don't need to hold "read_lock" for the heap, but we need
456      * to call c_heap_get_root() and pthread_cond_wait() in the
457      * same protected block. */
458     pthread_mutex_lock(&read_lock);
459     rf = c_heap_get_root(read_heap);
460     if (rf == NULL) {
461       pthread_cond_wait(&read_cond, &read_lock);
462       pthread_mutex_unlock(&read_lock);
463       continue;
464     }
465     pthread_mutex_unlock(&read_lock);
466
467     if (rf->rf_interval == 0) {
468       /* this should not happen, because the interval is set
469        * for each plugin when loading it
470        * XXX: issue a warning? */
471       rf->rf_interval = plugin_get_interval();
472       rf->rf_effective_interval = rf->rf_interval;
473
474       rf->rf_next_read = cdtime();
475     }
476
477     /* sleep until this entry is due,
478      * using pthread_cond_timedwait */
479     pthread_mutex_lock(&read_lock);
480     /* In pthread_cond_timedwait, spurious wakeups are possible
481      * (and really happen, at least on NetBSD with > 1 CPU), thus
482      * we need to re-evaluate the condition every time
483      * pthread_cond_timedwait returns. */
484     rc = 0;
485     while ((read_loop != 0) && (cdtime() < rf->rf_next_read) && rc == 0) {
486       rc = pthread_cond_timedwait(&read_cond, &read_lock,
487                                   &CDTIME_T_TO_TIMESPEC(rf->rf_next_read));
488     }
489
490     /* Must hold `read_lock' when accessing `rf->rf_type'. */
491     rf_type = rf->rf_type;
492     pthread_mutex_unlock(&read_lock);
493
494     /* Check if we're supposed to stop.. This may have interrupted
495      * the sleep, too. */
496     if (read_loop == 0) {
497       /* Insert `rf' again, so it can be free'd correctly */
498       c_heap_insert(read_heap, rf);
499       break;
500     }
501
502     /* The entry has been marked for deletion. The linked list
503      * entry has already been removed by `plugin_unregister_read'.
504      * All we have to do here is free the `read_func_t' and
505      * continue. */
506     if (rf_type == RF_REMOVE) {
507       DEBUG("plugin_read_thread: Destroying the `%s' "
508             "callback.",
509             rf->rf_name);
510       sfree(rf->rf_name);
511       destroy_callback((callback_func_t *)rf);
512       rf = NULL;
513       continue;
514     }
515
516     DEBUG("plugin_read_thread: Handling `%s'.", rf->rf_name);
517
518     start = cdtime();
519
520     old_ctx = plugin_set_ctx(rf->rf_ctx);
521
522     if (rf_type == RF_SIMPLE) {
523       int (*callback)(void);
524
525       callback = rf->rf_callback;
526       status = (*callback)();
527     } else {
528       plugin_read_cb callback;
529
530       assert(rf_type == RF_COMPLEX);
531
532       callback = rf->rf_callback;
533       status = (*callback)(&rf->rf_udata);
534     }
535
536     plugin_set_ctx(old_ctx);
537
538     /* If the function signals failure, we will increase the
539      * intervals in which it will be called. */
540     if (status != 0) {
541       rf->rf_effective_interval *= 2;
542       if (rf->rf_effective_interval > max_read_interval)
543         rf->rf_effective_interval = max_read_interval;
544
545       NOTICE("read-function of plugin `%s' failed. "
546              "Will suspend it for %.3f seconds.",
547              rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
548     } else {
549       /* Success: Restore the interval, if it was changed. */
550       rf->rf_effective_interval = rf->rf_interval;
551     }
552
553     /* update the ``next read due'' field */
554     now = cdtime();
555
556     /* calculate the time spent in the read function */
557     elapsed = (now - start);
558
559     if (elapsed > rf->rf_effective_interval)
560       WARNING(
561           "plugin_read_thread: read-function of the `%s' plugin took %.3f "
562           "seconds, which is above its read interval (%.3f seconds). You might "
563           "want to adjust the `Interval' or `ReadThreads' settings.",
564           rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed),
565           CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
566
567     DEBUG("plugin_read_thread: read-function of the `%s' plugin took "
568           "%.6f seconds.",
569           rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed));
570
571     DEBUG("plugin_read_thread: Effective interval of the "
572           "`%s' plugin is %.3f seconds.",
573           rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
574
575     /* Calculate the next (absolute) time at which this function
576      * should be called. */
577     rf->rf_next_read += rf->rf_effective_interval;
578
579     /* Check, if `rf_next_read' is in the past. */
580     if (rf->rf_next_read < now) {
581       /* `rf_next_read' is in the past. Insert `now'
582        * so this value doesn't trail off into the
583        * past too much. */
584       rf->rf_next_read = now;
585     }
586
587     DEBUG("plugin_read_thread: Next read of the `%s' plugin at %.3f.",
588           rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_next_read));
589
590     /* Re-insert this read function into the heap again. */
591     c_heap_insert(read_heap, rf);
592   } /* while (read_loop) */
593
594   pthread_exit(NULL);
595   return (void *)0;
596 } /* void *plugin_read_thread */
597
598 #ifdef PTHREAD_MAX_NAMELEN_NP
599 #define THREAD_NAME_MAX PTHREAD_MAX_NAMELEN_NP
600 #else
601 #define THREAD_NAME_MAX 16
602 #endif
603
604 static void set_thread_name(pthread_t tid, char const *name) {
605 #if defined(HAVE_PTHREAD_SETNAME_NP) || defined(HAVE_PTHREAD_SET_NAME_NP)
606
607   /* glibc limits the length of the name and fails if the passed string
608    * is too long, so we truncate it here. */
609   char n[THREAD_NAME_MAX];
610   if (strlen(name) >= THREAD_NAME_MAX)
611     WARNING("set_thread_name(\"%s\"): name too long", name);
612   sstrncpy(n, name, sizeof(n));
613
614 #if defined(HAVE_PTHREAD_SETNAME_NP)
615   int status = pthread_setname_np(tid, n);
616   if (status != 0) {
617     ERROR("set_thread_name(\"%s\"): %s", n, STRERROR(status));
618   }
619 #else /* if defined(HAVE_PTHREAD_SET_NAME_NP) */
620   pthread_set_name_np(tid, n);
621 #endif
622
623 #endif
624 }
625
626 static void start_read_threads(size_t num) /* {{{ */
627 {
628   if (read_threads != NULL)
629     return;
630
631   read_threads = calloc(num, sizeof(*read_threads));
632   if (read_threads == NULL) {
633     ERROR("plugin: start_read_threads: calloc failed.");
634     return;
635   }
636
637   read_threads_num = 0;
638   for (size_t i = 0; i < num; i++) {
639     int status = pthread_create(read_threads + read_threads_num,
640                                 /* attr = */ NULL, plugin_read_thread,
641                                 /* arg = */ NULL);
642     if (status != 0) {
643       ERROR("plugin: start_read_threads: pthread_create failed with status %i "
644             "(%s).",
645             status, STRERROR(status));
646       return;
647     }
648
649     char name[THREAD_NAME_MAX];
650     ssnprintf(name, sizeof(name), "reader#%" PRIu64,
651               (uint64_t)read_threads_num);
652     set_thread_name(read_threads[read_threads_num], name);
653
654     read_threads_num++;
655   } /* for (i) */
656 } /* }}} void start_read_threads */
657
658 static void stop_read_threads(void) {
659   if (read_threads == NULL)
660     return;
661
662   INFO("collectd: Stopping %" PRIsz " read threads.", read_threads_num);
663
664   pthread_mutex_lock(&read_lock);
665   read_loop = 0;
666   DEBUG("plugin: stop_read_threads: Signalling `read_cond'");
667   pthread_cond_broadcast(&read_cond);
668   pthread_mutex_unlock(&read_lock);
669
670   for (size_t i = 0; i < read_threads_num; i++) {
671     if (pthread_join(read_threads[i], NULL) != 0) {
672       ERROR("plugin: stop_read_threads: pthread_join failed.");
673     }
674     read_threads[i] = (pthread_t)0;
675   }
676   sfree(read_threads);
677   read_threads_num = 0;
678 } /* void stop_read_threads */
679
680 static void plugin_value_list_free(value_list_t *vl) /* {{{ */
681 {
682   if (vl == NULL)
683     return;
684
685   meta_data_destroy(vl->meta);
686   sfree(vl->values);
687   sfree(vl);
688 } /* }}} void plugin_value_list_free */
689
690 static value_list_t *
691 plugin_value_list_clone(value_list_t const *vl_orig) /* {{{ */
692 {
693   value_list_t *vl;
694
695   if (vl_orig == NULL)
696     return NULL;
697
698   vl = malloc(sizeof(*vl));
699   if (vl == NULL)
700     return NULL;
701   memcpy(vl, vl_orig, sizeof(*vl));
702
703   if (vl->host[0] == 0)
704     sstrncpy(vl->host, hostname_g, sizeof(vl->host));
705
706   vl->values = calloc(vl_orig->values_len, sizeof(*vl->values));
707   if (vl->values == NULL) {
708     plugin_value_list_free(vl);
709     return NULL;
710   }
711   memcpy(vl->values, vl_orig->values,
712          vl_orig->values_len * sizeof(*vl->values));
713
714   vl->meta = meta_data_clone(vl->meta);
715   if ((vl_orig->meta != NULL) && (vl->meta == NULL)) {
716     plugin_value_list_free(vl);
717     return NULL;
718   }
719
720   if (vl->time == 0)
721     vl->time = cdtime();
722
723   /* Fill in the interval from the thread context, if it is zero. */
724   if (vl->interval == 0)
725     vl->interval = plugin_get_interval();
726
727   return vl;
728 } /* }}} value_list_t *plugin_value_list_clone */
729
730 static int plugin_write_enqueue(value_list_t const *vl) /* {{{ */
731 {
732   write_queue_t *q;
733
734   q = malloc(sizeof(*q));
735   if (q == NULL)
736     return ENOMEM;
737   q->next = NULL;
738
739   q->vl = plugin_value_list_clone(vl);
740   if (q->vl == NULL) {
741     sfree(q);
742     return ENOMEM;
743   }
744
745   /* Store context of caller (read plugin); otherwise, it would not be
746    * available to the write plugins when actually dispatching the
747    * value-list later on. */
748   q->ctx = plugin_get_ctx();
749
750   pthread_mutex_lock(&write_lock);
751
752   if (write_queue_tail == NULL) {
753     write_queue_head = q;
754     write_queue_tail = q;
755     write_queue_length = 1;
756   } else {
757     write_queue_tail->next = q;
758     write_queue_tail = q;
759     write_queue_length += 1;
760   }
761
762   pthread_cond_signal(&write_cond);
763   pthread_mutex_unlock(&write_lock);
764
765   return 0;
766 } /* }}} int plugin_write_enqueue */
767
768 static value_list_t *plugin_write_dequeue(void) /* {{{ */
769 {
770   write_queue_t *q;
771   value_list_t *vl;
772
773   pthread_mutex_lock(&write_lock);
774
775   while (write_loop && (write_queue_head == NULL))
776     pthread_cond_wait(&write_cond, &write_lock);
777
778   if (write_queue_head == NULL) {
779     pthread_mutex_unlock(&write_lock);
780     return NULL;
781   }
782
783   q = write_queue_head;
784   write_queue_head = q->next;
785   write_queue_length -= 1;
786   if (write_queue_head == NULL) {
787     write_queue_tail = NULL;
788     assert(0 == write_queue_length);
789   }
790
791   pthread_mutex_unlock(&write_lock);
792
793   (void)plugin_set_ctx(q->ctx);
794
795   vl = q->vl;
796   sfree(q);
797   return vl;
798 } /* }}} value_list_t *plugin_write_dequeue */
799
800 static void *plugin_write_thread(void __attribute__((unused)) * args) /* {{{ */
801 {
802   while (write_loop) {
803     value_list_t *vl = plugin_write_dequeue();
804     if (vl == NULL)
805       continue;
806
807     plugin_dispatch_values_internal(vl);
808
809     plugin_value_list_free(vl);
810   }
811
812   pthread_exit(NULL);
813   return (void *)0;
814 } /* }}} void *plugin_write_thread */
815
816 static void start_write_threads(size_t num) /* {{{ */
817 {
818   if (write_threads != NULL)
819     return;
820
821   write_threads = calloc(num, sizeof(*write_threads));
822   if (write_threads == NULL) {
823     ERROR("plugin: start_write_threads: calloc failed.");
824     return;
825   }
826
827   write_threads_num = 0;
828   for (size_t i = 0; i < num; i++) {
829     int status = pthread_create(write_threads + write_threads_num,
830                                 /* attr = */ NULL, plugin_write_thread,
831                                 /* arg = */ NULL);
832     if (status != 0) {
833       ERROR("plugin: start_write_threads: pthread_create failed with status %i "
834             "(%s).",
835             status, STRERROR(status));
836       return;
837     }
838
839     char name[THREAD_NAME_MAX];
840     ssnprintf(name, sizeof(name), "writer#%" PRIu64,
841               (uint64_t)write_threads_num);
842     set_thread_name(write_threads[write_threads_num], name);
843
844     write_threads_num++;
845   } /* for (i) */
846 } /* }}} void start_write_threads */
847
848 static void stop_write_threads(void) /* {{{ */
849 {
850   write_queue_t *q;
851   size_t i;
852
853   if (write_threads == NULL)
854     return;
855
856   INFO("collectd: Stopping %" PRIsz " write threads.", write_threads_num);
857
858   pthread_mutex_lock(&write_lock);
859   write_loop = false;
860   DEBUG("plugin: stop_write_threads: Signalling `write_cond'");
861   pthread_cond_broadcast(&write_cond);
862   pthread_mutex_unlock(&write_lock);
863
864   for (i = 0; i < write_threads_num; i++) {
865     if (pthread_join(write_threads[i], NULL) != 0) {
866       ERROR("plugin: stop_write_threads: pthread_join failed.");
867     }
868     write_threads[i] = (pthread_t)0;
869   }
870   sfree(write_threads);
871   write_threads_num = 0;
872
873   pthread_mutex_lock(&write_lock);
874   i = 0;
875   for (q = write_queue_head; q != NULL;) {
876     write_queue_t *q1 = q;
877     plugin_value_list_free(q->vl);
878     q = q->next;
879     sfree(q1);
880     i++;
881   }
882   write_queue_head = NULL;
883   write_queue_tail = NULL;
884   write_queue_length = 0;
885   pthread_mutex_unlock(&write_lock);
886
887   if (i > 0) {
888     WARNING("plugin: %" PRIsz " value list%s left after shutting down "
889             "the write threads.",
890             i, (i == 1) ? " was" : "s were");
891   }
892 } /* }}} void stop_write_threads */
893
894 /*
895  * Public functions
896  */
897 void plugin_set_dir(const char *dir) {
898   sfree(plugindir);
899
900   if (dir == NULL) {
901     plugindir = NULL;
902     return;
903   }
904
905   plugindir = strdup(dir);
906   if (plugindir == NULL)
907     ERROR("plugin_set_dir: strdup(\"%s\") failed", dir);
908 }
909
910 static bool plugin_is_loaded(char const *name) {
911   int status;
912
913   if (plugins_loaded == NULL)
914     plugins_loaded =
915         c_avl_create((int (*)(const void *, const void *))strcasecmp);
916   assert(plugins_loaded != NULL);
917
918   status = c_avl_get(plugins_loaded, name, /* ret_value = */ NULL);
919   return status == 0;
920 }
921
922 static int plugin_mark_loaded(char const *name) {
923   char *name_copy;
924   int status;
925
926   name_copy = strdup(name);
927   if (name_copy == NULL)
928     return ENOMEM;
929
930   status = c_avl_insert(plugins_loaded,
931                         /* key = */ name_copy, /* value = */ NULL);
932   return status;
933 }
934
935 static void plugin_free_loaded(void) {
936   void *key;
937   void *value;
938
939   if (plugins_loaded == NULL)
940     return;
941
942   while (c_avl_pick(plugins_loaded, &key, &value) == 0) {
943     sfree(key);
944     assert(value == NULL);
945   }
946
947   c_avl_destroy(plugins_loaded);
948   plugins_loaded = NULL;
949 }
950
951 #define BUFSIZE 512
952 #ifdef WIN32
953 #define SHLIB_SUFFIX ".dll"
954 #else
955 #define SHLIB_SUFFIX ".so"
956 #endif
957 int plugin_load(char const *plugin_name, bool global) {
958   DIR *dh;
959   const char *dir;
960   char filename[BUFSIZE] = "";
961   char typename[BUFSIZE];
962   int ret;
963   struct stat statbuf;
964   struct dirent *de;
965   int status;
966
967   if (plugin_name == NULL)
968     return EINVAL;
969
970   /* Check if plugin is already loaded and don't do anything in this
971    * case. */
972   if (plugin_is_loaded(plugin_name))
973     return 0;
974
975   dir = plugin_get_dir();
976   ret = 1;
977
978   /*
979    * XXX: Magic at work:
980    *
981    * Some of the language bindings, for example the Python and Perl
982    * plugins, need to be able to export symbols to the scripts they run.
983    * For this to happen, the "Globals" flag needs to be set.
984    * Unfortunately, this technical detail is hard to explain to the
985    * average user and she shouldn't have to worry about this, ideally.
986    * So in order to save everyone's sanity use a different default for a
987    * handful of special plugins. --octo
988    */
989   if ((strcasecmp("perl", plugin_name) == 0) ||
990       (strcasecmp("python", plugin_name) == 0))
991     global = true;
992
993   /* `cpu' should not match `cpufreq'. To solve this we add SHLIB_SUFFIX to the
994    * type when matching the filename */
995   status = snprintf(typename, sizeof(typename), "%s" SHLIB_SUFFIX, plugin_name);
996   if ((status < 0) || ((size_t)status >= sizeof(typename))) {
997     WARNING("plugin_load: Filename too long: \"%s" SHLIB_SUFFIX "\"",
998             plugin_name);
999     return -1;
1000   }
1001
1002   if ((dh = opendir(dir)) == NULL) {
1003     ERROR("plugin_load: opendir (%s) failed: %s", dir, STRERRNO);
1004     return -1;
1005   }
1006
1007   while ((de = readdir(dh)) != NULL) {
1008     if (strcasecmp(de->d_name, typename))
1009       continue;
1010
1011     status = snprintf(filename, sizeof(filename), "%s/%s", dir, de->d_name);
1012     if ((status < 0) || ((size_t)status >= sizeof(filename))) {
1013       WARNING("plugin_load: Filename too long: \"%s/%s\"", dir, de->d_name);
1014       continue;
1015     }
1016
1017     if (lstat(filename, &statbuf) == -1) {
1018       WARNING("plugin_load: stat (\"%s\") failed: %s", filename, STRERRNO);
1019       continue;
1020     } else if (!S_ISREG(statbuf.st_mode)) {
1021       /* don't follow symlinks */
1022       WARNING("plugin_load: %s is not a regular file.", filename);
1023       continue;
1024     }
1025
1026     status = plugin_load_file(filename, global);
1027     if (status == 0) {
1028       /* success */
1029       plugin_mark_loaded(plugin_name);
1030       ret = 0;
1031       INFO("plugin_load: plugin \"%s\" successfully loaded.", plugin_name);
1032       break;
1033     } else {
1034       ERROR("plugin_load: Load plugin \"%s\" failed with "
1035             "status %i.",
1036             plugin_name, status);
1037     }
1038   }
1039
1040   closedir(dh);
1041
1042   if (filename[0] == 0)
1043     ERROR("plugin_load: Could not find plugin \"%s\" in %s", plugin_name, dir);
1044
1045   return ret;
1046 }
1047
1048 /*
1049  * The `register_*' functions follow
1050  */
1051 EXPORT int plugin_register_config(const char *name,
1052                                   int (*callback)(const char *key,
1053                                                   const char *val),
1054                                   const char **keys, int keys_num) {
1055   cf_register(name, callback, keys, keys_num);
1056   return 0;
1057 } /* int plugin_register_config */
1058
1059 EXPORT int plugin_register_complex_config(const char *type,
1060                                           int (*callback)(oconfig_item_t *)) {
1061   return cf_register_complex(type, callback);
1062 } /* int plugin_register_complex_config */
1063
1064 EXPORT int plugin_register_init(const char *name, int (*callback)(void)) {
1065   return create_register_callback(&list_init, name, (void *)callback, NULL);
1066 } /* plugin_register_init */
1067
1068 static int plugin_compare_read_func(const void *arg0, const void *arg1) {
1069   const read_func_t *rf0;
1070   const read_func_t *rf1;
1071
1072   rf0 = arg0;
1073   rf1 = arg1;
1074
1075   if (rf0->rf_next_read < rf1->rf_next_read)
1076     return -1;
1077   else if (rf0->rf_next_read > rf1->rf_next_read)
1078     return 1;
1079   else
1080     return 0;
1081 } /* int plugin_compare_read_func */
1082
1083 /* Add a read function to both, the heap and a linked list. The linked list if
1084  * used to look-up read functions, especially for the remove function. The heap
1085  * is used to determine which plugin to read next. */
1086 static int plugin_insert_read(read_func_t *rf) {
1087   int status;
1088   llentry_t *le;
1089
1090   rf->rf_next_read = cdtime();
1091   rf->rf_effective_interval = rf->rf_interval;
1092
1093   pthread_mutex_lock(&read_lock);
1094
1095   if (read_list == NULL) {
1096     read_list = llist_create();
1097     if (read_list == NULL) {
1098       pthread_mutex_unlock(&read_lock);
1099       ERROR("plugin_insert_read: read_list failed.");
1100       return -1;
1101     }
1102   }
1103
1104   if (read_heap == NULL) {
1105     read_heap = c_heap_create(plugin_compare_read_func);
1106     if (read_heap == NULL) {
1107       pthread_mutex_unlock(&read_lock);
1108       ERROR("plugin_insert_read: c_heap_create failed.");
1109       return -1;
1110     }
1111   }
1112
1113   le = llist_search(read_list, rf->rf_name);
1114   if (le != NULL) {
1115     pthread_mutex_unlock(&read_lock);
1116     P_WARNING("The read function \"%s\" is already registered. "
1117               "Check for duplicates in your configuration!",
1118               rf->rf_name);
1119     return EINVAL;
1120   }
1121
1122   le = llentry_create(rf->rf_name, rf);
1123   if (le == NULL) {
1124     pthread_mutex_unlock(&read_lock);
1125     ERROR("plugin_insert_read: llentry_create failed.");
1126     return -1;
1127   }
1128
1129   status = c_heap_insert(read_heap, rf);
1130   if (status != 0) {
1131     pthread_mutex_unlock(&read_lock);
1132     ERROR("plugin_insert_read: c_heap_insert failed.");
1133     llentry_destroy(le);
1134     return -1;
1135   }
1136
1137   /* This does not fail. */
1138   llist_append(read_list, le);
1139
1140   /* Wake up all the read threads. */
1141   pthread_cond_broadcast(&read_cond);
1142   pthread_mutex_unlock(&read_lock);
1143   return 0;
1144 } /* int plugin_insert_read */
1145
1146 EXPORT int plugin_register_read(const char *name, int (*callback)(void)) {
1147   read_func_t *rf;
1148   int status;
1149
1150   rf = calloc(1, sizeof(*rf));
1151   if (rf == NULL) {
1152     ERROR("plugin_register_read: calloc failed.");
1153     return ENOMEM;
1154   }
1155
1156   rf->rf_callback = (void *)callback;
1157   rf->rf_udata.data = NULL;
1158   rf->rf_udata.free_func = NULL;
1159   rf->rf_ctx = plugin_get_ctx();
1160   rf->rf_group[0] = '\0';
1161   rf->rf_name = strdup(name);
1162   rf->rf_type = RF_SIMPLE;
1163   rf->rf_interval = plugin_get_interval();
1164   rf->rf_ctx.interval = rf->rf_interval;
1165
1166   status = plugin_insert_read(rf);
1167   if (status != 0) {
1168     sfree(rf->rf_name);
1169     sfree(rf);
1170   }
1171
1172   return status;
1173 } /* int plugin_register_read */
1174
1175 EXPORT int plugin_register_complex_read(const char *group, const char *name,
1176                                         plugin_read_cb callback,
1177                                         cdtime_t interval,
1178                                         user_data_t const *user_data) {
1179   read_func_t *rf;
1180   int status;
1181
1182   rf = calloc(1, sizeof(*rf));
1183   if (rf == NULL) {
1184     free_userdata(user_data);
1185     ERROR("plugin_register_complex_read: calloc failed.");
1186     return ENOMEM;
1187   }
1188
1189   rf->rf_callback = (void *)callback;
1190   if (group != NULL)
1191     sstrncpy(rf->rf_group, group, sizeof(rf->rf_group));
1192   else
1193     rf->rf_group[0] = '\0';
1194   rf->rf_name = strdup(name);
1195   rf->rf_type = RF_COMPLEX;
1196   rf->rf_interval = (interval != 0) ? interval : plugin_get_interval();
1197
1198   /* Set user data */
1199   if (user_data == NULL) {
1200     rf->rf_udata.data = NULL;
1201     rf->rf_udata.free_func = NULL;
1202   } else {
1203     rf->rf_udata = *user_data;
1204   }
1205
1206   rf->rf_ctx = plugin_get_ctx();
1207   rf->rf_ctx.interval = rf->rf_interval;
1208
1209   status = plugin_insert_read(rf);
1210   if (status != 0) {
1211     free_userdata(&rf->rf_udata);
1212     sfree(rf->rf_name);
1213     sfree(rf);
1214   }
1215
1216   return status;
1217 } /* int plugin_register_complex_read */
1218
1219 EXPORT int plugin_register_write(const char *name, plugin_write_cb callback,
1220                                  user_data_t const *ud) {
1221   return create_register_callback(&list_write, name, (void *)callback, ud);
1222 } /* int plugin_register_write */
1223
1224 static int plugin_flush_timeout_callback(user_data_t *ud) {
1225   flush_callback_t *cb = ud->data;
1226
1227   return plugin_flush(cb->name, cb->timeout, NULL);
1228 } /* static int plugin_flush_callback */
1229
1230 static void plugin_flush_timeout_callback_free(void *data) {
1231   flush_callback_t *cb = data;
1232
1233   if (cb == NULL)
1234     return;
1235
1236   sfree(cb->name);
1237   sfree(cb);
1238 } /* static void plugin_flush_callback_free */
1239
1240 static char *plugin_flush_callback_name(const char *name) {
1241   const char *flush_prefix = "flush/";
1242   size_t prefix_size;
1243   char *flush_name;
1244   size_t name_size;
1245
1246   prefix_size = strlen(flush_prefix);
1247   name_size = strlen(name);
1248
1249   flush_name = malloc(name_size + prefix_size + 1);
1250   if (flush_name == NULL) {
1251     ERROR("plugin_flush_callback_name: malloc failed.");
1252     return NULL;
1253   }
1254
1255   sstrncpy(flush_name, flush_prefix, prefix_size + 1);
1256   sstrncpy(flush_name + prefix_size, name, name_size + 1);
1257
1258   return flush_name;
1259 } /* static char *plugin_flush_callback_name */
1260
1261 EXPORT int plugin_register_flush(const char *name, plugin_flush_cb callback,
1262                                  user_data_t const *ud) {
1263   int status;
1264   plugin_ctx_t ctx = plugin_get_ctx();
1265
1266   status = create_register_callback(&list_flush, name, (void *)callback, ud);
1267   if (status != 0)
1268     return status;
1269
1270   if (ctx.flush_interval != 0) {
1271     char *flush_name;
1272     flush_callback_t *cb;
1273
1274     flush_name = plugin_flush_callback_name(name);
1275     if (flush_name == NULL)
1276       return -1;
1277
1278     cb = malloc(sizeof(*cb));
1279     if (cb == NULL) {
1280       ERROR("plugin_register_flush: malloc failed.");
1281       sfree(flush_name);
1282       return -1;
1283     }
1284
1285     cb->name = strdup(name);
1286     if (cb->name == NULL) {
1287       ERROR("plugin_register_flush: strdup failed.");
1288       sfree(cb);
1289       sfree(flush_name);
1290       return -1;
1291     }
1292     cb->timeout = ctx.flush_timeout;
1293
1294     status = plugin_register_complex_read(
1295         /* group     = */ "flush",
1296         /* name      = */ flush_name,
1297         /* callback  = */ plugin_flush_timeout_callback,
1298         /* interval  = */ ctx.flush_interval,
1299         /* user data = */
1300         &(user_data_t){
1301             .data = cb,
1302             .free_func = plugin_flush_timeout_callback_free,
1303         });
1304
1305     sfree(flush_name);
1306     return status;
1307   }
1308
1309   return 0;
1310 } /* int plugin_register_flush */
1311
1312 EXPORT int plugin_register_missing(const char *name, plugin_missing_cb callback,
1313                                    user_data_t const *ud) {
1314   return create_register_callback(&list_missing, name, (void *)callback, ud);
1315 } /* int plugin_register_missing */
1316
1317 EXPORT int plugin_register_shutdown(const char *name, int (*callback)(void)) {
1318   return create_register_callback(&list_shutdown, name, (void *)callback, NULL);
1319 } /* int plugin_register_shutdown */
1320
1321 static void plugin_free_data_sets(void) {
1322   void *key;
1323   void *value;
1324
1325   if (data_sets == NULL)
1326     return;
1327
1328   while (c_avl_pick(data_sets, &key, &value) == 0) {
1329     data_set_t *ds = value;
1330     /* key is a pointer to ds->type */
1331
1332     sfree(ds->ds);
1333     sfree(ds);
1334   }
1335
1336   c_avl_destroy(data_sets);
1337   data_sets = NULL;
1338 } /* void plugin_free_data_sets */
1339
1340 EXPORT int plugin_register_data_set(const data_set_t *ds) {
1341   data_set_t *ds_copy;
1342
1343   if ((data_sets != NULL) && (c_avl_get(data_sets, ds->type, NULL) == 0)) {
1344     NOTICE("Replacing DS `%s' with another version.", ds->type);
1345     plugin_unregister_data_set(ds->type);
1346   } else if (data_sets == NULL) {
1347     data_sets = c_avl_create((int (*)(const void *, const void *))strcmp);
1348     if (data_sets == NULL)
1349       return -1;
1350   }
1351
1352   ds_copy = malloc(sizeof(*ds_copy));
1353   if (ds_copy == NULL)
1354     return -1;
1355   memcpy(ds_copy, ds, sizeof(data_set_t));
1356
1357   ds_copy->ds = malloc(sizeof(*ds_copy->ds) * ds->ds_num);
1358   if (ds_copy->ds == NULL) {
1359     sfree(ds_copy);
1360     return -1;
1361   }
1362
1363   for (size_t i = 0; i < ds->ds_num; i++)
1364     memcpy(ds_copy->ds + i, ds->ds + i, sizeof(data_source_t));
1365
1366   return c_avl_insert(data_sets, (void *)ds_copy->type, (void *)ds_copy);
1367 } /* int plugin_register_data_set */
1368
1369 EXPORT int plugin_register_log(const char *name, plugin_log_cb callback,
1370                                user_data_t const *ud) {
1371   return create_register_callback(&list_log, name, (void *)callback, ud);
1372 } /* int plugin_register_log */
1373
1374 EXPORT int plugin_register_notification(const char *name,
1375                                         plugin_notification_cb callback,
1376                                         user_data_t const *ud) {
1377   return create_register_callback(&list_notification, name, (void *)callback,
1378                                   ud);
1379 } /* int plugin_register_log */
1380
1381 EXPORT int plugin_unregister_config(const char *name) {
1382   cf_unregister(name);
1383   return 0;
1384 } /* int plugin_unregister_config */
1385
1386 EXPORT int plugin_unregister_complex_config(const char *name) {
1387   cf_unregister_complex(name);
1388   return 0;
1389 } /* int plugin_unregister_complex_config */
1390
1391 EXPORT int plugin_unregister_init(const char *name) {
1392   return plugin_unregister(list_init, name);
1393 }
1394
1395 EXPORT int plugin_unregister_read(const char *name) /* {{{ */
1396 {
1397   llentry_t *le;
1398   read_func_t *rf;
1399
1400   if (name == NULL)
1401     return -ENOENT;
1402
1403   pthread_mutex_lock(&read_lock);
1404
1405   if (read_list == NULL) {
1406     pthread_mutex_unlock(&read_lock);
1407     return -ENOENT;
1408   }
1409
1410   le = llist_search(read_list, name);
1411   if (le == NULL) {
1412     pthread_mutex_unlock(&read_lock);
1413     WARNING("plugin_unregister_read: No such read function: %s", name);
1414     return -ENOENT;
1415   }
1416
1417   llist_remove(read_list, le);
1418
1419   rf = le->value;
1420   assert(rf != NULL);
1421   rf->rf_type = RF_REMOVE;
1422
1423   pthread_mutex_unlock(&read_lock);
1424
1425   llentry_destroy(le);
1426
1427   DEBUG("plugin_unregister_read: Marked `%s' for removal.", name);
1428
1429   return 0;
1430 } /* }}} int plugin_unregister_read */
1431
1432 EXPORT void plugin_log_available_writers(void) {
1433   log_list_callbacks(&list_write, "Available write targets:");
1434 }
1435
1436 static int compare_read_func_group(llentry_t *e, void *ud) /* {{{ */
1437 {
1438   read_func_t *rf = e->value;
1439   char *group = ud;
1440
1441   return strcmp(rf->rf_group, (const char *)group);
1442 } /* }}} int compare_read_func_group */
1443
1444 EXPORT int plugin_unregister_read_group(const char *group) /* {{{ */
1445 {
1446   llentry_t *le;
1447   read_func_t *rf;
1448
1449   int found = 0;
1450
1451   if (group == NULL)
1452     return -ENOENT;
1453
1454   pthread_mutex_lock(&read_lock);
1455
1456   if (read_list == NULL) {
1457     pthread_mutex_unlock(&read_lock);
1458     return -ENOENT;
1459   }
1460
1461   while (42) {
1462     le = llist_search_custom(read_list, compare_read_func_group, (void *)group);
1463
1464     if (le == NULL)
1465       break;
1466
1467     ++found;
1468
1469     llist_remove(read_list, le);
1470
1471     rf = le->value;
1472     assert(rf != NULL);
1473     rf->rf_type = RF_REMOVE;
1474
1475     llentry_destroy(le);
1476
1477     DEBUG("plugin_unregister_read_group: "
1478           "Marked `%s' (group `%s') for removal.",
1479           rf->rf_name, group);
1480   }
1481
1482   pthread_mutex_unlock(&read_lock);
1483
1484   if (found == 0) {
1485     WARNING("plugin_unregister_read_group: No such "
1486             "group of read function: %s",
1487             group);
1488     return -ENOENT;
1489   }
1490
1491   return 0;
1492 } /* }}} int plugin_unregister_read_group */
1493
1494 EXPORT int plugin_unregister_write(const char *name) {
1495   return plugin_unregister(list_write, name);
1496 }
1497
1498 EXPORT int plugin_unregister_flush(const char *name) {
1499   plugin_ctx_t ctx = plugin_get_ctx();
1500
1501   if (ctx.flush_interval != 0) {
1502     char *flush_name;
1503
1504     flush_name = plugin_flush_callback_name(name);
1505     if (flush_name != NULL) {
1506       plugin_unregister_read(flush_name);
1507       sfree(flush_name);
1508     }
1509   }
1510
1511   return plugin_unregister(list_flush, name);
1512 }
1513
1514 EXPORT int plugin_unregister_missing(const char *name) {
1515   return plugin_unregister(list_missing, name);
1516 }
1517
1518 EXPORT int plugin_unregister_shutdown(const char *name) {
1519   return plugin_unregister(list_shutdown, name);
1520 }
1521
1522 EXPORT int plugin_unregister_data_set(const char *name) {
1523   data_set_t *ds;
1524
1525   if (data_sets == NULL)
1526     return -1;
1527
1528   if (c_avl_remove(data_sets, name, NULL, (void *)&ds) != 0)
1529     return -1;
1530
1531   sfree(ds->ds);
1532   sfree(ds);
1533
1534   return 0;
1535 } /* int plugin_unregister_data_set */
1536
1537 EXPORT int plugin_unregister_log(const char *name) {
1538   return plugin_unregister(list_log, name);
1539 }
1540
1541 EXPORT int plugin_unregister_notification(const char *name) {
1542   return plugin_unregister(list_notification, name);
1543 }
1544
1545 EXPORT int plugin_init_all(void) {
1546   char const *chain_name;
1547   llentry_t *le;
1548   int status;
1549   int ret = 0;
1550
1551   /* Init the value cache */
1552   uc_init();
1553
1554   if (IS_TRUE(global_option_get("CollectInternalStats"))) {
1555     record_statistics = true;
1556     plugin_register_read("collectd", plugin_update_internal_statistics);
1557   }
1558
1559   chain_name = global_option_get("PreCacheChain");
1560   pre_cache_chain = fc_chain_get_by_name(chain_name);
1561
1562   chain_name = global_option_get("PostCacheChain");
1563   post_cache_chain = fc_chain_get_by_name(chain_name);
1564
1565   write_limit_high = global_option_get_long("WriteQueueLimitHigh",
1566                                             /* default = */ 0);
1567   if (write_limit_high < 0) {
1568     ERROR("WriteQueueLimitHigh must be positive or zero.");
1569     write_limit_high = 0;
1570   }
1571
1572   write_limit_low =
1573       global_option_get_long("WriteQueueLimitLow",
1574                              /* default = */ write_limit_high / 2);
1575   if (write_limit_low < 0) {
1576     ERROR("WriteQueueLimitLow must be positive or zero.");
1577     write_limit_low = write_limit_high / 2;
1578   } else if (write_limit_low > write_limit_high) {
1579     ERROR("WriteQueueLimitLow must not be larger than "
1580           "WriteQueueLimitHigh.");
1581     write_limit_low = write_limit_high;
1582   }
1583
1584   write_threads_num = global_option_get_long("WriteThreads",
1585                                              /* default = */ 5);
1586   if (write_threads_num < 1) {
1587     ERROR("WriteThreads must be positive.");
1588     write_threads_num = 5;
1589   }
1590
1591   if ((list_init == NULL) && (read_heap == NULL))
1592     return ret;
1593
1594   /* Calling all init callbacks before checking if read callbacks
1595    * are available allows the init callbacks to register the read
1596    * callback. */
1597   le = llist_head(list_init);
1598   while (le != NULL) {
1599     callback_func_t *cf;
1600     plugin_init_cb callback;
1601     plugin_ctx_t old_ctx;
1602
1603     cf = le->value;
1604     old_ctx = plugin_set_ctx(cf->cf_ctx);
1605     callback = cf->cf_callback;
1606     status = (*callback)();
1607     plugin_set_ctx(old_ctx);
1608
1609     if (status != 0) {
1610       ERROR("Initialization of plugin `%s' "
1611             "failed with status %i. "
1612             "Plugin will be unloaded.",
1613             le->key, status);
1614       /* Plugins that register read callbacks from the init
1615        * callback should take care of appropriate error
1616        * handling themselves. */
1617       /* FIXME: Unload _all_ functions */
1618       plugin_unregister_read(le->key);
1619       ret = -1;
1620     }
1621
1622     le = le->next;
1623   }
1624
1625   start_write_threads((size_t)write_threads_num);
1626
1627   max_read_interval =
1628       global_option_get_time("MaxReadInterval", DEFAULT_MAX_READ_INTERVAL);
1629
1630   /* Start read-threads */
1631   if (read_heap != NULL) {
1632     const char *rt;
1633     int num;
1634
1635     rt = global_option_get("ReadThreads");
1636     num = atoi(rt);
1637     if (num != -1)
1638       start_read_threads((num > 0) ? ((size_t)num) : 5);
1639   }
1640   return ret;
1641 } /* void plugin_init_all */
1642
1643 /* TODO: Rename this function. */
1644 EXPORT void plugin_read_all(void) {
1645   uc_check_timeout();
1646
1647   return;
1648 } /* void plugin_read_all */
1649
1650 /* Read function called when the `-T' command line argument is given. */
1651 EXPORT int plugin_read_all_once(void) {
1652   int status;
1653   int return_status = 0;
1654
1655   if (read_heap == NULL) {
1656     NOTICE("No read-functions are registered.");
1657     return 0;
1658   }
1659
1660   while (42) {
1661     read_func_t *rf;
1662     plugin_ctx_t old_ctx;
1663
1664     rf = c_heap_get_root(read_heap);
1665     if (rf == NULL)
1666       break;
1667
1668     old_ctx = plugin_set_ctx(rf->rf_ctx);
1669
1670     if (rf->rf_type == RF_SIMPLE) {
1671       int (*callback)(void);
1672
1673       callback = rf->rf_callback;
1674       status = (*callback)();
1675     } else {
1676       plugin_read_cb callback;
1677
1678       callback = rf->rf_callback;
1679       status = (*callback)(&rf->rf_udata);
1680     }
1681
1682     plugin_set_ctx(old_ctx);
1683
1684     if (status != 0) {
1685       NOTICE("read-function of plugin `%s' failed.", rf->rf_name);
1686       return_status = -1;
1687     }
1688
1689     sfree(rf->rf_name);
1690     destroy_callback((void *)rf);
1691   }
1692
1693   return return_status;
1694 } /* int plugin_read_all_once */
1695
1696 EXPORT int plugin_write(const char *plugin, /* {{{ */
1697                         const data_set_t *ds, const value_list_t *vl) {
1698   llentry_t *le;
1699   int status;
1700
1701   if (vl == NULL)
1702     return EINVAL;
1703
1704   if (list_write == NULL)
1705     return ENOENT;
1706
1707   if (ds == NULL) {
1708     ds = plugin_get_ds(vl->type);
1709     if (ds == NULL) {
1710       ERROR("plugin_write: Unable to lookup type `%s'.", vl->type);
1711       return ENOENT;
1712     }
1713   }
1714
1715   if (plugin == NULL) {
1716     int success = 0;
1717     int failure = 0;
1718
1719     le = llist_head(list_write);
1720     while (le != NULL) {
1721       callback_func_t *cf = le->value;
1722       plugin_write_cb callback;
1723
1724       /* Keep the read plugin's interval and flush information but update the
1725        * plugin name. */
1726       plugin_ctx_t old_ctx = plugin_get_ctx();
1727       plugin_ctx_t ctx = old_ctx;
1728       ctx.name = cf->cf_ctx.name;
1729       plugin_set_ctx(ctx);
1730
1731       DEBUG("plugin: plugin_write: Writing values via %s.", le->key);
1732       callback = cf->cf_callback;
1733       status = (*callback)(ds, vl, &cf->cf_udata);
1734       if (status != 0)
1735         failure++;
1736       else
1737         success++;
1738
1739       plugin_set_ctx(old_ctx);
1740       le = le->next;
1741     }
1742
1743     if ((success == 0) && (failure != 0))
1744       status = -1;
1745     else
1746       status = 0;
1747   } else /* plugin != NULL */
1748   {
1749     callback_func_t *cf;
1750     plugin_write_cb callback;
1751
1752     le = llist_head(list_write);
1753     while (le != NULL) {
1754       if (strcasecmp(plugin, le->key) == 0)
1755         break;
1756
1757       le = le->next;
1758     }
1759
1760     if (le == NULL)
1761       return ENOENT;
1762
1763     cf = le->value;
1764
1765     /* do not switch plugin context; rather keep the context (interval)
1766      * information of the calling read plugin */
1767
1768     DEBUG("plugin: plugin_write: Writing values via %s.", le->key);
1769     callback = cf->cf_callback;
1770     status = (*callback)(ds, vl, &cf->cf_udata);
1771   }
1772
1773   return status;
1774 } /* }}} int plugin_write */
1775
1776 EXPORT int plugin_flush(const char *plugin, cdtime_t timeout,
1777                         const char *identifier) {
1778   llentry_t *le;
1779
1780   if (list_flush == NULL)
1781     return 0;
1782
1783   le = llist_head(list_flush);
1784   while (le != NULL) {
1785     callback_func_t *cf;
1786     plugin_flush_cb callback;
1787     plugin_ctx_t old_ctx;
1788
1789     if ((plugin != NULL) && (strcmp(plugin, le->key) != 0)) {
1790       le = le->next;
1791       continue;
1792     }
1793
1794     cf = le->value;
1795     old_ctx = plugin_set_ctx(cf->cf_ctx);
1796     callback = cf->cf_callback;
1797
1798     (*callback)(timeout, identifier, &cf->cf_udata);
1799
1800     plugin_set_ctx(old_ctx);
1801
1802     le = le->next;
1803   }
1804   return 0;
1805 } /* int plugin_flush */
1806
1807 EXPORT int plugin_shutdown_all(void) {
1808   llentry_t *le;
1809   int ret = 0; // Assume success.
1810
1811   destroy_all_callbacks(&list_init);
1812
1813   stop_read_threads();
1814
1815   pthread_mutex_lock(&read_lock);
1816   llist_destroy(read_list);
1817   read_list = NULL;
1818   pthread_mutex_unlock(&read_lock);
1819
1820   destroy_read_heap();
1821
1822   /* blocks until all write threads have shut down. */
1823   stop_write_threads();
1824
1825   /* ask all plugins to write out the state they kept. */
1826   plugin_flush(/* plugin = */ NULL,
1827                /* timeout = */ 0,
1828                /* identifier = */ NULL);
1829
1830   le = NULL;
1831   if (list_shutdown != NULL)
1832     le = llist_head(list_shutdown);
1833
1834   while (le != NULL) {
1835     callback_func_t *cf;
1836     plugin_shutdown_cb callback;
1837     plugin_ctx_t old_ctx;
1838
1839     cf = le->value;
1840     old_ctx = plugin_set_ctx(cf->cf_ctx);
1841     callback = cf->cf_callback;
1842
1843     /* Advance the pointer before calling the callback allows
1844      * shutdown functions to unregister themselves. If done the
1845      * other way around the memory `le' points to will be freed
1846      * after callback returns. */
1847     le = le->next;
1848
1849     if ((*callback)() != 0)
1850       ret = -1;
1851
1852     plugin_set_ctx(old_ctx);
1853   }
1854
1855   /* Write plugins which use the `user_data' pointer usually need the
1856    * same data available to the flush callback. If this is the case, set
1857    * the free_function to NULL when registering the flush callback and to
1858    * the real free function when registering the write callback. This way
1859    * the data isn't freed twice. */
1860   destroy_all_callbacks(&list_flush);
1861   destroy_all_callbacks(&list_missing);
1862   destroy_all_callbacks(&list_write);
1863
1864   destroy_all_callbacks(&list_notification);
1865   destroy_all_callbacks(&list_shutdown);
1866   destroy_all_callbacks(&list_log);
1867
1868   plugin_free_loaded();
1869   plugin_free_data_sets();
1870   return ret;
1871 } /* void plugin_shutdown_all */
1872
1873 EXPORT int plugin_dispatch_missing(const value_list_t *vl) /* {{{ */
1874 {
1875   if (list_missing == NULL)
1876     return 0;
1877
1878   llentry_t *le = llist_head(list_missing);
1879   while (le != NULL) {
1880     callback_func_t *cf = le->value;
1881     plugin_ctx_t old_ctx = plugin_set_ctx(cf->cf_ctx);
1882     plugin_missing_cb callback = cf->cf_callback;
1883
1884     int status = (*callback)(vl, &cf->cf_udata);
1885     plugin_set_ctx(old_ctx);
1886     if (status != 0) {
1887       if (status < 0) {
1888         ERROR("plugin_dispatch_missing: Callback function \"%s\" "
1889               "failed with status %i.",
1890               le->key, status);
1891         return status;
1892       } else {
1893         return 0;
1894       }
1895     }
1896
1897     le = le->next;
1898   }
1899   return 0;
1900 } /* int }}} plugin_dispatch_missing */
1901
1902 static int plugin_dispatch_values_internal(value_list_t *vl) {
1903   int status;
1904   static c_complain_t no_write_complaint = C_COMPLAIN_INIT_STATIC;
1905
1906   bool free_meta_data = false;
1907
1908   assert(vl != NULL);
1909
1910   /* These fields are initialized by plugin_value_list_clone() if needed: */
1911   assert(vl->host[0] != 0);
1912   assert(vl->time != 0); /* The time is determined at _enqueue_ time. */
1913   assert(vl->interval != 0);
1914
1915   if (vl->type[0] == 0 || vl->values == NULL || vl->values_len < 1) {
1916     ERROR("plugin_dispatch_values: Invalid value list "
1917           "from plugin %s.",
1918           vl->plugin);
1919     return -1;
1920   }
1921
1922   /* Free meta data only if the calling function didn't specify any. In
1923    * this case matches and targets may add some and the calling function
1924    * may not expect (and therefore free) that data. */
1925   if (vl->meta == NULL)
1926     free_meta_data = true;
1927
1928   if (list_write == NULL)
1929     c_complain_once(LOG_WARNING, &no_write_complaint,
1930                     "plugin_dispatch_values: No write callback has been "
1931                     "registered. Please load at least one output plugin, "
1932                     "if you want the collected data to be stored.");
1933
1934   if (data_sets == NULL) {
1935     ERROR("plugin_dispatch_values: No data sets registered. "
1936           "Could the types database be read? Check "
1937           "your `TypesDB' setting!");
1938     return -1;
1939   }
1940
1941   data_set_t *ds = NULL;
1942   if (c_avl_get(data_sets, vl->type, (void *)&ds) != 0) {
1943     char ident[6 * DATA_MAX_NAME_LEN];
1944
1945     FORMAT_VL(ident, sizeof(ident), vl);
1946     INFO("plugin_dispatch_values: Dataset not found: %s "
1947          "(from \"%s\"), check your types.db!",
1948          vl->type, ident);
1949     return -1;
1950   }
1951
1952   DEBUG("plugin_dispatch_values: time = %.3f; interval = %.3f; "
1953         "host = %s; "
1954         "plugin = %s; plugin_instance = %s; "
1955         "type = %s; type_instance = %s;",
1956         CDTIME_T_TO_DOUBLE(vl->time), CDTIME_T_TO_DOUBLE(vl->interval),
1957         vl->host, vl->plugin, vl->plugin_instance, vl->type, vl->type_instance);
1958
1959 #if COLLECT_DEBUG
1960   assert(0 == strcmp(ds->type, vl->type));
1961 #else
1962   if (0 != strcmp(ds->type, vl->type))
1963     WARNING("plugin_dispatch_values: (ds->type = %s) != (vl->type = %s)",
1964             ds->type, vl->type);
1965 #endif
1966
1967 #if COLLECT_DEBUG
1968   assert(ds->ds_num == vl->values_len);
1969 #else
1970   if (ds->ds_num != vl->values_len) {
1971     ERROR("plugin_dispatch_values: ds->type = %s: "
1972           "(ds->ds_num = %" PRIsz ") != "
1973           "(vl->values_len = %" PRIsz ")",
1974           ds->type, ds->ds_num, vl->values_len);
1975     return -1;
1976   }
1977 #endif
1978
1979   escape_slashes(vl->host, sizeof(vl->host));
1980   escape_slashes(vl->plugin, sizeof(vl->plugin));
1981   escape_slashes(vl->plugin_instance, sizeof(vl->plugin_instance));
1982   escape_slashes(vl->type, sizeof(vl->type));
1983   escape_slashes(vl->type_instance, sizeof(vl->type_instance));
1984
1985   if (pre_cache_chain != NULL) {
1986     status = fc_process_chain(ds, vl, pre_cache_chain);
1987     if (status < 0) {
1988       WARNING("plugin_dispatch_values: Running the "
1989               "pre-cache chain failed with "
1990               "status %i (%#x).",
1991               status, status);
1992     } else if (status == FC_TARGET_STOP)
1993       return 0;
1994   }
1995
1996   /* Update the value cache */
1997   uc_update(ds, vl);
1998
1999   if (post_cache_chain != NULL) {
2000     status = fc_process_chain(ds, vl, post_cache_chain);
2001     if (status < 0) {
2002       WARNING("plugin_dispatch_values: Running the "
2003               "post-cache chain failed with "
2004               "status %i (%#x).",
2005               status, status);
2006     }
2007   } else
2008     fc_default_action(ds, vl);
2009
2010   if ((free_meta_data == true) && (vl->meta != NULL)) {
2011     meta_data_destroy(vl->meta);
2012     vl->meta = NULL;
2013   }
2014
2015   return 0;
2016 } /* int plugin_dispatch_values_internal */
2017
2018 static double get_drop_probability(void) /* {{{ */
2019 {
2020   long pos;
2021   long size;
2022   long wql;
2023
2024   pthread_mutex_lock(&write_lock);
2025   wql = write_queue_length;
2026   pthread_mutex_unlock(&write_lock);
2027
2028   if (wql < write_limit_low)
2029     return 0.0;
2030   if (wql >= write_limit_high)
2031     return 1.0;
2032
2033   pos = 1 + wql - write_limit_low;
2034   size = 1 + write_limit_high - write_limit_low;
2035
2036   return (double)pos / (double)size;
2037 } /* }}} double get_drop_probability */
2038
2039 static bool check_drop_value(void) /* {{{ */
2040 {
2041   static cdtime_t last_message_time;
2042   static pthread_mutex_t last_message_lock = PTHREAD_MUTEX_INITIALIZER;
2043
2044   double p;
2045   double q;
2046   int status;
2047
2048   if (write_limit_high == 0)
2049     return false;
2050
2051   p = get_drop_probability();
2052   if (p == 0.0)
2053     return false;
2054
2055   status = pthread_mutex_trylock(&last_message_lock);
2056   if (status == 0) {
2057     cdtime_t now;
2058
2059     now = cdtime();
2060     if ((now - last_message_time) > TIME_T_TO_CDTIME_T(1)) {
2061       last_message_time = now;
2062       ERROR("plugin_dispatch_values: Low water mark "
2063             "reached. Dropping %.0f%% of metrics.",
2064             100.0 * p);
2065     }
2066     pthread_mutex_unlock(&last_message_lock);
2067   }
2068
2069   if (p == 1.0)
2070     return true;
2071
2072   q = cdrand_d();
2073   if (q > p)
2074     return true;
2075   else
2076     return false;
2077 } /* }}} bool check_drop_value */
2078
2079 EXPORT int plugin_dispatch_values(value_list_t const *vl) {
2080   int status;
2081
2082   if (check_drop_value()) {
2083     if (record_statistics) {
2084       pthread_mutex_lock(&statistics_lock);
2085       stats_values_dropped++;
2086       pthread_mutex_unlock(&statistics_lock);
2087     }
2088     return 0;
2089   }
2090
2091   status = plugin_write_enqueue(vl);
2092   if (status != 0) {
2093     ERROR("plugin_dispatch_values: plugin_write_enqueue failed with status %i "
2094           "(%s).",
2095           status, STRERROR(status));
2096     return status;
2097   }
2098
2099   return 0;
2100 }
2101
2102 __attribute__((sentinel)) int
2103 plugin_dispatch_multivalue(value_list_t const *template, /* {{{ */
2104                            bool store_percentage, int store_type, ...) {
2105   value_list_t *vl;
2106   int failed = 0;
2107   gauge_t sum = 0.0;
2108   va_list ap;
2109
2110   if (check_drop_value()) {
2111     if (record_statistics) {
2112       pthread_mutex_lock(&statistics_lock);
2113       stats_values_dropped++;
2114       pthread_mutex_unlock(&statistics_lock);
2115     }
2116     return 0;
2117   }
2118
2119   assert(template->values_len == 1);
2120
2121   /* Calculate sum for Gauge to calculate percent if needed */
2122   if (DS_TYPE_GAUGE == store_type) {
2123     va_start(ap, store_type);
2124     while (42) {
2125       char const *name;
2126       gauge_t value;
2127
2128       name = va_arg(ap, char const *);
2129       if (name == NULL)
2130         break;
2131
2132       value = va_arg(ap, gauge_t);
2133       if (!isnan(value))
2134         sum += value;
2135     }
2136     va_end(ap);
2137   }
2138
2139   vl = plugin_value_list_clone(template);
2140   /* plugin_value_list_clone makes sure vl->time is set to non-zero. */
2141   if (store_percentage)
2142     sstrncpy(vl->type, "percent", sizeof(vl->type));
2143
2144   va_start(ap, store_type);
2145   while (42) {
2146     char const *name;
2147     int status;
2148
2149     /* Set the type instance. */
2150     name = va_arg(ap, char const *);
2151     if (name == NULL)
2152       break;
2153     sstrncpy(vl->type_instance, name, sizeof(vl->type_instance));
2154
2155     /* Set the value. */
2156     switch (store_type) {
2157     case DS_TYPE_GAUGE:
2158       vl->values[0].gauge = va_arg(ap, gauge_t);
2159       if (store_percentage)
2160         vl->values[0].gauge *= sum ? (100.0 / sum) : NAN;
2161       break;
2162     case DS_TYPE_ABSOLUTE:
2163       vl->values[0].absolute = va_arg(ap, absolute_t);
2164       break;
2165     case DS_TYPE_COUNTER:
2166       vl->values[0].counter = va_arg(ap, counter_t);
2167       break;
2168     case DS_TYPE_DERIVE:
2169       vl->values[0].derive = va_arg(ap, derive_t);
2170       break;
2171     default:
2172       ERROR("plugin_dispatch_multivalue: given store_type is incorrect.");
2173       failed++;
2174     }
2175
2176     status = plugin_write_enqueue(vl);
2177     if (status != 0)
2178       failed++;
2179   }
2180   va_end(ap);
2181
2182   plugin_value_list_free(vl);
2183   return failed;
2184 } /* }}} int plugin_dispatch_multivalue */
2185
2186 EXPORT int plugin_dispatch_notification(const notification_t *notif) {
2187   llentry_t *le;
2188   /* Possible TODO: Add flap detection here */
2189
2190   DEBUG("plugin_dispatch_notification: severity = %i; message = %s; "
2191         "time = %.3f; host = %s;",
2192         notif->severity, notif->message, CDTIME_T_TO_DOUBLE(notif->time),
2193         notif->host);
2194
2195   /* Nobody cares for notifications */
2196   if (list_notification == NULL)
2197     return -1;
2198
2199   le = llist_head(list_notification);
2200   while (le != NULL) {
2201     callback_func_t *cf;
2202     plugin_notification_cb callback;
2203     int status;
2204
2205     /* do not switch plugin context; rather keep the context
2206      * (interval) information of the calling plugin */
2207
2208     cf = le->value;
2209     callback = cf->cf_callback;
2210     status = (*callback)(notif, &cf->cf_udata);
2211     if (status != 0) {
2212       WARNING("plugin_dispatch_notification: Notification "
2213               "callback %s returned %i.",
2214               le->key, status);
2215     }
2216
2217     le = le->next;
2218   }
2219
2220   return 0;
2221 } /* int plugin_dispatch_notification */
2222
2223 EXPORT void plugin_log(int level, const char *format, ...) {
2224   char msg[1024];
2225   va_list ap;
2226   llentry_t *le;
2227
2228 #if !COLLECT_DEBUG
2229   if (level >= LOG_DEBUG)
2230     return;
2231 #endif
2232
2233   va_start(ap, format);
2234   vsnprintf(msg, sizeof(msg), format, ap);
2235   msg[sizeof(msg) - 1] = '\0';
2236   va_end(ap);
2237
2238   if (list_log == NULL) {
2239     fprintf(stderr, "%s\n", msg);
2240     return;
2241   }
2242
2243   le = llist_head(list_log);
2244   while (le != NULL) {
2245     callback_func_t *cf;
2246     plugin_log_cb callback;
2247
2248     cf = le->value;
2249     callback = cf->cf_callback;
2250
2251     /* do not switch plugin context; rather keep the context
2252      * (interval) information of the calling plugin */
2253
2254     (*callback)(level, msg, &cf->cf_udata);
2255
2256     le = le->next;
2257   }
2258 } /* void plugin_log */
2259
2260 void daemon_log(int level, const char *format, ...) {
2261   char msg[1024] = ""; // Size inherits from plugin_log()
2262
2263   char const *name = plugin_get_ctx().name;
2264   if (name == NULL)
2265     name = "UNKNOWN";
2266
2267   va_list ap;
2268   va_start(ap, format);
2269   vsnprintf(msg, sizeof(msg), format, ap);
2270   va_end(ap);
2271
2272   plugin_log(level, "%s plugin: %s", name, msg);
2273 } /* void daemon_log */
2274
2275 int parse_log_severity(const char *severity) {
2276   int log_level = -1;
2277
2278   if ((0 == strcasecmp(severity, "emerg")) ||
2279       (0 == strcasecmp(severity, "alert")) ||
2280       (0 == strcasecmp(severity, "crit")) || (0 == strcasecmp(severity, "err")))
2281     log_level = LOG_ERR;
2282   else if (0 == strcasecmp(severity, "warning"))
2283     log_level = LOG_WARNING;
2284   else if (0 == strcasecmp(severity, "notice"))
2285     log_level = LOG_NOTICE;
2286   else if (0 == strcasecmp(severity, "info"))
2287     log_level = LOG_INFO;
2288 #if COLLECT_DEBUG
2289   else if (0 == strcasecmp(severity, "debug"))
2290     log_level = LOG_DEBUG;
2291 #endif /* COLLECT_DEBUG */
2292
2293   return log_level;
2294 } /* int parse_log_severity */
2295
2296 EXPORT int parse_notif_severity(const char *severity) {
2297   int notif_severity = -1;
2298
2299   if (strcasecmp(severity, "FAILURE") == 0)
2300     notif_severity = NOTIF_FAILURE;
2301   else if (strcmp(severity, "OKAY") == 0)
2302     notif_severity = NOTIF_OKAY;
2303   else if ((strcmp(severity, "WARNING") == 0) ||
2304            (strcmp(severity, "WARN") == 0))
2305     notif_severity = NOTIF_WARNING;
2306
2307   return notif_severity;
2308 } /* int parse_notif_severity */
2309
2310 EXPORT const data_set_t *plugin_get_ds(const char *name) {
2311   data_set_t *ds;
2312
2313   if (data_sets == NULL) {
2314     P_ERROR("plugin_get_ds: No data sets are defined yet.");
2315     return NULL;
2316   }
2317
2318   if (c_avl_get(data_sets, name, (void *)&ds) != 0) {
2319     DEBUG("No such dataset registered: %s", name);
2320     return NULL;
2321   }
2322
2323   return ds;
2324 } /* data_set_t *plugin_get_ds */
2325
2326 static int plugin_notification_meta_add(notification_t *n, const char *name,
2327                                         enum notification_meta_type_e type,
2328                                         const void *value) {
2329   notification_meta_t *meta;
2330   notification_meta_t *tail;
2331
2332   if ((n == NULL) || (name == NULL) || (value == NULL)) {
2333     ERROR("plugin_notification_meta_add: A pointer is NULL!");
2334     return -1;
2335   }
2336
2337   meta = calloc(1, sizeof(*meta));
2338   if (meta == NULL) {
2339     ERROR("plugin_notification_meta_add: calloc failed.");
2340     return -1;
2341   }
2342
2343   sstrncpy(meta->name, name, sizeof(meta->name));
2344   meta->type = type;
2345
2346   switch (type) {
2347   case NM_TYPE_STRING: {
2348     meta->nm_value.nm_string = strdup((const char *)value);
2349     if (meta->nm_value.nm_string == NULL) {
2350       ERROR("plugin_notification_meta_add: strdup failed.");
2351       sfree(meta);
2352       return -1;
2353     }
2354     break;
2355   }
2356   case NM_TYPE_SIGNED_INT: {
2357     meta->nm_value.nm_signed_int = *((int64_t *)value);
2358     break;
2359   }
2360   case NM_TYPE_UNSIGNED_INT: {
2361     meta->nm_value.nm_unsigned_int = *((uint64_t *)value);
2362     break;
2363   }
2364   case NM_TYPE_DOUBLE: {
2365     meta->nm_value.nm_double = *((double *)value);
2366     break;
2367   }
2368   case NM_TYPE_BOOLEAN: {
2369     meta->nm_value.nm_boolean = *((bool *)value);
2370     break;
2371   }
2372   default: {
2373     ERROR("plugin_notification_meta_add: Unknown type: %i", type);
2374     sfree(meta);
2375     return -1;
2376   }
2377   } /* switch (type) */
2378
2379   meta->next = NULL;
2380   tail = n->meta;
2381   while ((tail != NULL) && (tail->next != NULL))
2382     tail = tail->next;
2383
2384   if (tail == NULL)
2385     n->meta = meta;
2386   else
2387     tail->next = meta;
2388
2389   return 0;
2390 } /* int plugin_notification_meta_add */
2391
2392 int plugin_notification_meta_add_string(notification_t *n, const char *name,
2393                                         const char *value) {
2394   return plugin_notification_meta_add(n, name, NM_TYPE_STRING, value);
2395 }
2396
2397 int plugin_notification_meta_add_signed_int(notification_t *n, const char *name,
2398                                             int64_t value) {
2399   return plugin_notification_meta_add(n, name, NM_TYPE_SIGNED_INT, &value);
2400 }
2401
2402 int plugin_notification_meta_add_unsigned_int(notification_t *n,
2403                                               const char *name,
2404                                               uint64_t value) {
2405   return plugin_notification_meta_add(n, name, NM_TYPE_UNSIGNED_INT, &value);
2406 }
2407
2408 int plugin_notification_meta_add_double(notification_t *n, const char *name,
2409                                         double value) {
2410   return plugin_notification_meta_add(n, name, NM_TYPE_DOUBLE, &value);
2411 }
2412
2413 int plugin_notification_meta_add_boolean(notification_t *n, const char *name,
2414                                          bool value) {
2415   return plugin_notification_meta_add(n, name, NM_TYPE_BOOLEAN, &value);
2416 }
2417
2418 int plugin_notification_meta_copy(notification_t *dst,
2419                                   const notification_t *src) {
2420   assert(dst != NULL);
2421   assert(src != NULL);
2422   assert(dst != src);
2423   assert((src->meta == NULL) || (src->meta != dst->meta));
2424
2425   for (notification_meta_t *meta = src->meta; meta != NULL; meta = meta->next) {
2426     if (meta->type == NM_TYPE_STRING)
2427       plugin_notification_meta_add_string(dst, meta->name,
2428                                           meta->nm_value.nm_string);
2429     else if (meta->type == NM_TYPE_SIGNED_INT)
2430       plugin_notification_meta_add_signed_int(dst, meta->name,
2431                                               meta->nm_value.nm_signed_int);
2432     else if (meta->type == NM_TYPE_UNSIGNED_INT)
2433       plugin_notification_meta_add_unsigned_int(dst, meta->name,
2434                                                 meta->nm_value.nm_unsigned_int);
2435     else if (meta->type == NM_TYPE_DOUBLE)
2436       plugin_notification_meta_add_double(dst, meta->name,
2437                                           meta->nm_value.nm_double);
2438     else if (meta->type == NM_TYPE_BOOLEAN)
2439       plugin_notification_meta_add_boolean(dst, meta->name,
2440                                            meta->nm_value.nm_boolean);
2441   }
2442
2443   return 0;
2444 } /* int plugin_notification_meta_copy */
2445
2446 int plugin_notification_meta_free(notification_meta_t *n) {
2447   notification_meta_t *this;
2448   notification_meta_t *next;
2449
2450   if (n == NULL) {
2451     ERROR("plugin_notification_meta_free: n == NULL!");
2452     return -1;
2453   }
2454
2455   this = n;
2456   while (this != NULL) {
2457     next = this->next;
2458
2459     if (this->type == NM_TYPE_STRING) {
2460       /* Assign to a temporary variable to work around nm_string's const
2461        * modifier. */
2462       void *tmp = (void *)this->nm_value.nm_string;
2463
2464       sfree(tmp);
2465       this->nm_value.nm_string = NULL;
2466     }
2467     sfree(this);
2468
2469     this = next;
2470   }
2471
2472   return 0;
2473 } /* int plugin_notification_meta_free */
2474
2475 static void plugin_ctx_destructor(void *ctx) {
2476   sfree(ctx);
2477 } /* void plugin_ctx_destructor */
2478
2479 static plugin_ctx_t ctx_init = {/* interval = */ 0};
2480
2481 static plugin_ctx_t *plugin_ctx_create(void) {
2482   plugin_ctx_t *ctx;
2483
2484   ctx = malloc(sizeof(*ctx));
2485   if (ctx == NULL) {
2486     ERROR("Failed to allocate plugin context: %s", STRERRNO);
2487     return NULL;
2488   }
2489
2490   *ctx = ctx_init;
2491   assert(plugin_ctx_key_initialized);
2492   pthread_setspecific(plugin_ctx_key, ctx);
2493   DEBUG("Created new plugin context.");
2494   return ctx;
2495 } /* int plugin_ctx_create */
2496
2497 EXPORT void plugin_init_ctx(void) {
2498   pthread_key_create(&plugin_ctx_key, plugin_ctx_destructor);
2499   plugin_ctx_key_initialized = true;
2500 } /* void plugin_init_ctx */
2501
2502 EXPORT plugin_ctx_t plugin_get_ctx(void) {
2503   plugin_ctx_t *ctx;
2504
2505   assert(plugin_ctx_key_initialized);
2506   ctx = pthread_getspecific(plugin_ctx_key);
2507
2508   if (ctx == NULL) {
2509     ctx = plugin_ctx_create();
2510     /* this must no happen -- exit() instead? */
2511     if (ctx == NULL)
2512       return ctx_init;
2513   }
2514
2515   return *ctx;
2516 } /* plugin_ctx_t plugin_get_ctx */
2517
2518 EXPORT plugin_ctx_t plugin_set_ctx(plugin_ctx_t ctx) {
2519   plugin_ctx_t *c;
2520   plugin_ctx_t old;
2521
2522   assert(plugin_ctx_key_initialized);
2523   c = pthread_getspecific(plugin_ctx_key);
2524
2525   if (c == NULL) {
2526     c = plugin_ctx_create();
2527     /* this must no happen -- exit() instead? */
2528     if (c == NULL)
2529       return ctx_init;
2530   }
2531
2532   old = *c;
2533   *c = ctx;
2534
2535   return old;
2536 } /* void plugin_set_ctx */
2537
2538 EXPORT cdtime_t plugin_get_interval(void) {
2539   cdtime_t interval;
2540
2541   interval = plugin_get_ctx().interval;
2542   if (interval > 0)
2543     return interval;
2544
2545   P_ERROR("plugin_get_interval: Unable to determine Interval from context.");
2546
2547   return cf_get_default_interval();
2548 } /* cdtime_t plugin_get_interval */
2549
2550 typedef struct {
2551   plugin_ctx_t ctx;
2552   void *(*start_routine)(void *);
2553   void *arg;
2554 } plugin_thread_t;
2555
2556 static void *plugin_thread_start(void *arg) {
2557   plugin_thread_t *plugin_thread = arg;
2558
2559   void *(*start_routine)(void *) = plugin_thread->start_routine;
2560   void *plugin_arg = plugin_thread->arg;
2561
2562   plugin_set_ctx(plugin_thread->ctx);
2563
2564   sfree(plugin_thread);
2565
2566   return start_routine(plugin_arg);
2567 } /* void *plugin_thread_start */
2568
2569 int plugin_thread_create(pthread_t *thread, const pthread_attr_t *attr,
2570                          void *(*start_routine)(void *), void *arg,
2571                          char const *name) {
2572   plugin_thread_t *plugin_thread;
2573
2574   plugin_thread = malloc(sizeof(*plugin_thread));
2575   if (plugin_thread == NULL)
2576     return ENOMEM;
2577
2578   plugin_thread->ctx = plugin_get_ctx();
2579   plugin_thread->start_routine = start_routine;
2580   plugin_thread->arg = arg;
2581
2582   int ret = pthread_create(thread, attr, plugin_thread_start, plugin_thread);
2583   if (ret != 0) {
2584     sfree(plugin_thread);
2585     return ret;
2586   }
2587
2588   if (name != NULL)
2589     set_thread_name(*thread, name);
2590
2591   return 0;
2592 } /* int plugin_thread_create */