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