Merge pull request #3238 from ccin2p3/f/syslog-debug-level
[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     snprintf(name, sizeof(name), "reader#%" PRIu64, (uint64_t)read_threads_num);
651     set_thread_name(read_threads[read_threads_num], name);
652
653     read_threads_num++;
654   } /* for (i) */
655 } /* }}} void start_read_threads */
656
657 static void stop_read_threads(void) {
658   if (read_threads == NULL)
659     return;
660
661   INFO("collectd: Stopping %" PRIsz " read threads.", read_threads_num);
662
663   pthread_mutex_lock(&read_lock);
664   read_loop = 0;
665   DEBUG("plugin: stop_read_threads: Signalling `read_cond'");
666   pthread_cond_broadcast(&read_cond);
667   pthread_mutex_unlock(&read_lock);
668
669   for (size_t i = 0; i < read_threads_num; i++) {
670     if (pthread_join(read_threads[i], NULL) != 0) {
671       ERROR("plugin: stop_read_threads: pthread_join failed.");
672     }
673     read_threads[i] = (pthread_t)0;
674   }
675   sfree(read_threads);
676   read_threads_num = 0;
677 } /* void stop_read_threads */
678
679 static void plugin_value_list_free(value_list_t *vl) /* {{{ */
680 {
681   if (vl == NULL)
682     return;
683
684   meta_data_destroy(vl->meta);
685   sfree(vl->values);
686   sfree(vl);
687 } /* }}} void plugin_value_list_free */
688
689 static value_list_t *
690 plugin_value_list_clone(value_list_t const *vl_orig) /* {{{ */
691 {
692   value_list_t *vl;
693
694   if (vl_orig == NULL)
695     return NULL;
696
697   vl = malloc(sizeof(*vl));
698   if (vl == NULL)
699     return NULL;
700   memcpy(vl, vl_orig, sizeof(*vl));
701
702   if (vl->host[0] == 0)
703     sstrncpy(vl->host, hostname_g, sizeof(vl->host));
704
705   vl->values = calloc(vl_orig->values_len, sizeof(*vl->values));
706   if (vl->values == NULL) {
707     plugin_value_list_free(vl);
708     return NULL;
709   }
710   memcpy(vl->values, vl_orig->values,
711          vl_orig->values_len * sizeof(*vl->values));
712
713   vl->meta = meta_data_clone(vl->meta);
714   if ((vl_orig->meta != NULL) && (vl->meta == NULL)) {
715     plugin_value_list_free(vl);
716     return NULL;
717   }
718
719   if (vl->time == 0)
720     vl->time = cdtime();
721
722   /* Fill in the interval from the thread context, if it is zero. */
723   if (vl->interval == 0)
724     vl->interval = plugin_get_interval();
725
726   return vl;
727 } /* }}} value_list_t *plugin_value_list_clone */
728
729 static int plugin_write_enqueue(value_list_t const *vl) /* {{{ */
730 {
731   write_queue_t *q;
732
733   q = malloc(sizeof(*q));
734   if (q == NULL)
735     return ENOMEM;
736   q->next = NULL;
737
738   q->vl = plugin_value_list_clone(vl);
739   if (q->vl == NULL) {
740     sfree(q);
741     return ENOMEM;
742   }
743
744   /* Store context of caller (read plugin); otherwise, it would not be
745    * available to the write plugins when actually dispatching the
746    * value-list later on. */
747   q->ctx = plugin_get_ctx();
748
749   pthread_mutex_lock(&write_lock);
750
751   if (write_queue_tail == NULL) {
752     write_queue_head = q;
753     write_queue_tail = q;
754     write_queue_length = 1;
755   } else {
756     write_queue_tail->next = q;
757     write_queue_tail = q;
758     write_queue_length += 1;
759   }
760
761   pthread_cond_signal(&write_cond);
762   pthread_mutex_unlock(&write_lock);
763
764   return 0;
765 } /* }}} int plugin_write_enqueue */
766
767 static value_list_t *plugin_write_dequeue(void) /* {{{ */
768 {
769   write_queue_t *q;
770   value_list_t *vl;
771
772   pthread_mutex_lock(&write_lock);
773
774   while (write_loop && (write_queue_head == NULL))
775     pthread_cond_wait(&write_cond, &write_lock);
776
777   if (write_queue_head == NULL) {
778     pthread_mutex_unlock(&write_lock);
779     return NULL;
780   }
781
782   q = write_queue_head;
783   write_queue_head = q->next;
784   write_queue_length -= 1;
785   if (write_queue_head == NULL) {
786     write_queue_tail = NULL;
787     assert(0 == write_queue_length);
788   }
789
790   pthread_mutex_unlock(&write_lock);
791
792   (void)plugin_set_ctx(q->ctx);
793
794   vl = q->vl;
795   sfree(q);
796   return vl;
797 } /* }}} value_list_t *plugin_write_dequeue */
798
799 static void *plugin_write_thread(void __attribute__((unused)) * args) /* {{{ */
800 {
801   while (write_loop) {
802     value_list_t *vl = plugin_write_dequeue();
803     if (vl == NULL)
804       continue;
805
806     plugin_dispatch_values_internal(vl);
807
808     plugin_value_list_free(vl);
809   }
810
811   pthread_exit(NULL);
812   return (void *)0;
813 } /* }}} void *plugin_write_thread */
814
815 static void start_write_threads(size_t num) /* {{{ */
816 {
817   if (write_threads != NULL)
818     return;
819
820   write_threads = calloc(num, sizeof(*write_threads));
821   if (write_threads == NULL) {
822     ERROR("plugin: start_write_threads: calloc failed.");
823     return;
824   }
825
826   write_threads_num = 0;
827   for (size_t i = 0; i < num; i++) {
828     int status = pthread_create(write_threads + write_threads_num,
829                                 /* attr = */ NULL, plugin_write_thread,
830                                 /* arg = */ NULL);
831     if (status != 0) {
832       ERROR("plugin: start_write_threads: pthread_create failed with status %i "
833             "(%s).",
834             status, STRERROR(status));
835       return;
836     }
837
838     char name[THREAD_NAME_MAX];
839     snprintf(name, sizeof(name), "writer#%" PRIu64,
840              (uint64_t)write_threads_num);
841     set_thread_name(write_threads[write_threads_num], name);
842
843     write_threads_num++;
844   } /* for (i) */
845 } /* }}} void start_write_threads */
846
847 static void stop_write_threads(void) /* {{{ */
848 {
849   write_queue_t *q;
850   size_t i;
851
852   if (write_threads == NULL)
853     return;
854
855   INFO("collectd: Stopping %" PRIsz " write threads.", write_threads_num);
856
857   pthread_mutex_lock(&write_lock);
858   write_loop = false;
859   DEBUG("plugin: stop_write_threads: Signalling `write_cond'");
860   pthread_cond_broadcast(&write_cond);
861   pthread_mutex_unlock(&write_lock);
862
863   for (i = 0; i < write_threads_num; i++) {
864     if (pthread_join(write_threads[i], NULL) != 0) {
865       ERROR("plugin: stop_write_threads: pthread_join failed.");
866     }
867     write_threads[i] = (pthread_t)0;
868   }
869   sfree(write_threads);
870   write_threads_num = 0;
871
872   pthread_mutex_lock(&write_lock);
873   i = 0;
874   for (q = write_queue_head; q != NULL;) {
875     write_queue_t *q1 = q;
876     plugin_value_list_free(q->vl);
877     q = q->next;
878     sfree(q1);
879     i++;
880   }
881   write_queue_head = NULL;
882   write_queue_tail = NULL;
883   write_queue_length = 0;
884   pthread_mutex_unlock(&write_lock);
885
886   if (i > 0) {
887     WARNING("plugin: %" PRIsz " value list%s left after shutting down "
888             "the write threads.",
889             i, (i == 1) ? " was" : "s were");
890   }
891 } /* }}} void stop_write_threads */
892
893 /*
894  * Public functions
895  */
896 void plugin_set_dir(const char *dir) {
897   sfree(plugindir);
898
899   if (dir == NULL) {
900     plugindir = NULL;
901     return;
902   }
903
904   plugindir = strdup(dir);
905   if (plugindir == NULL)
906     ERROR("plugin_set_dir: strdup(\"%s\") failed", dir);
907 }
908
909 bool plugin_is_loaded(char const *name) {
910   if (plugins_loaded == NULL)
911     plugins_loaded =
912         c_avl_create((int (*)(const void *, const void *))strcasecmp);
913   assert(plugins_loaded != NULL);
914
915   int status = c_avl_get(plugins_loaded, name, /* ret_value = */ NULL);
916   return status == 0;
917 }
918
919 static int plugin_mark_loaded(char const *name) {
920   char *name_copy;
921   int status;
922
923   name_copy = strdup(name);
924   if (name_copy == NULL)
925     return ENOMEM;
926
927   status = c_avl_insert(plugins_loaded,
928                         /* key = */ name_copy, /* value = */ NULL);
929   return status;
930 }
931
932 static void plugin_free_loaded(void) {
933   void *key;
934   void *value;
935
936   if (plugins_loaded == NULL)
937     return;
938
939   while (c_avl_pick(plugins_loaded, &key, &value) == 0) {
940     sfree(key);
941     assert(value == NULL);
942   }
943
944   c_avl_destroy(plugins_loaded);
945   plugins_loaded = NULL;
946 }
947
948 #define BUFSIZE 512
949 #ifdef WIN32
950 #define SHLIB_SUFFIX ".dll"
951 #else
952 #define SHLIB_SUFFIX ".so"
953 #endif
954 int plugin_load(char const *plugin_name, bool global) {
955   DIR *dh;
956   const char *dir;
957   char filename[BUFSIZE] = "";
958   char typename[BUFSIZE];
959   int ret;
960   struct stat statbuf;
961   struct dirent *de;
962   int status;
963
964   if (plugin_name == NULL)
965     return EINVAL;
966
967   /* Check if plugin is already loaded and don't do anything in this
968    * case. */
969   if (plugin_is_loaded(plugin_name))
970     return 0;
971
972   dir = plugin_get_dir();
973   ret = 1;
974
975   /*
976    * XXX: Magic at work:
977    *
978    * Some of the language bindings, for example the Python and Perl
979    * plugins, need to be able to export symbols to the scripts they run.
980    * For this to happen, the "Globals" flag needs to be set.
981    * Unfortunately, this technical detail is hard to explain to the
982    * average user and she shouldn't have to worry about this, ideally.
983    * So in order to save everyone's sanity use a different default for a
984    * handful of special plugins. --octo
985    */
986   if ((strcasecmp("perl", plugin_name) == 0) ||
987       (strcasecmp("python", plugin_name) == 0))
988     global = true;
989
990   /* `cpu' should not match `cpufreq'. To solve this we add SHLIB_SUFFIX to the
991    * type when matching the filename */
992   status = snprintf(typename, sizeof(typename), "%s" SHLIB_SUFFIX, plugin_name);
993   if ((status < 0) || ((size_t)status >= sizeof(typename))) {
994     WARNING("plugin_load: Filename too long: \"%s" SHLIB_SUFFIX "\"",
995             plugin_name);
996     return -1;
997   }
998
999   if ((dh = opendir(dir)) == NULL) {
1000     ERROR("plugin_load: opendir (%s) failed: %s", dir, STRERRNO);
1001     return -1;
1002   }
1003
1004   while ((de = readdir(dh)) != NULL) {
1005     if (strcasecmp(de->d_name, typename))
1006       continue;
1007
1008     status = snprintf(filename, sizeof(filename), "%s/%s", dir, de->d_name);
1009     if ((status < 0) || ((size_t)status >= sizeof(filename))) {
1010       WARNING("plugin_load: Filename too long: \"%s/%s\"", dir, de->d_name);
1011       continue;
1012     }
1013
1014     if (lstat(filename, &statbuf) == -1) {
1015       WARNING("plugin_load: stat (\"%s\") failed: %s", filename, STRERRNO);
1016       continue;
1017     } else if (!S_ISREG(statbuf.st_mode)) {
1018       /* don't follow symlinks */
1019       WARNING("plugin_load: %s is not a regular file.", filename);
1020       continue;
1021     }
1022
1023     status = plugin_load_file(filename, global);
1024     if (status == 0) {
1025       /* success */
1026       plugin_mark_loaded(plugin_name);
1027       ret = 0;
1028       INFO("plugin_load: plugin \"%s\" successfully loaded.", plugin_name);
1029       break;
1030     } else {
1031       ERROR("plugin_load: Load plugin \"%s\" failed with "
1032             "status %i.",
1033             plugin_name, status);
1034     }
1035   }
1036
1037   closedir(dh);
1038
1039   if (filename[0] == 0)
1040     ERROR("plugin_load: Could not find plugin \"%s\" in %s", plugin_name, dir);
1041
1042   return ret;
1043 }
1044
1045 /*
1046  * The `register_*' functions follow
1047  */
1048 EXPORT int plugin_register_config(const char *name,
1049                                   int (*callback)(const char *key,
1050                                                   const char *val),
1051                                   const char **keys, int keys_num) {
1052   cf_register(name, callback, keys, keys_num);
1053   return 0;
1054 } /* int plugin_register_config */
1055
1056 EXPORT int plugin_register_complex_config(const char *type,
1057                                           int (*callback)(oconfig_item_t *)) {
1058   return cf_register_complex(type, callback);
1059 } /* int plugin_register_complex_config */
1060
1061 EXPORT int plugin_register_init(const char *name, int (*callback)(void)) {
1062   return create_register_callback(&list_init, name, (void *)callback, NULL);
1063 } /* plugin_register_init */
1064
1065 static int plugin_compare_read_func(const void *arg0, const void *arg1) {
1066   const read_func_t *rf0;
1067   const read_func_t *rf1;
1068
1069   rf0 = arg0;
1070   rf1 = arg1;
1071
1072   if (rf0->rf_next_read < rf1->rf_next_read)
1073     return -1;
1074   else if (rf0->rf_next_read > rf1->rf_next_read)
1075     return 1;
1076   else
1077     return 0;
1078 } /* int plugin_compare_read_func */
1079
1080 /* Add a read function to both, the heap and a linked list. The linked list if
1081  * used to look-up read functions, especially for the remove function. The heap
1082  * is used to determine which plugin to read next. */
1083 static int plugin_insert_read(read_func_t *rf) {
1084   int status;
1085   llentry_t *le;
1086
1087   rf->rf_next_read = cdtime();
1088   rf->rf_effective_interval = rf->rf_interval;
1089
1090   pthread_mutex_lock(&read_lock);
1091
1092   if (read_list == NULL) {
1093     read_list = llist_create();
1094     if (read_list == NULL) {
1095       pthread_mutex_unlock(&read_lock);
1096       ERROR("plugin_insert_read: read_list failed.");
1097       return -1;
1098     }
1099   }
1100
1101   if (read_heap == NULL) {
1102     read_heap = c_heap_create(plugin_compare_read_func);
1103     if (read_heap == NULL) {
1104       pthread_mutex_unlock(&read_lock);
1105       ERROR("plugin_insert_read: c_heap_create failed.");
1106       return -1;
1107     }
1108   }
1109
1110   le = llist_search(read_list, rf->rf_name);
1111   if (le != NULL) {
1112     pthread_mutex_unlock(&read_lock);
1113     P_WARNING("The read function \"%s\" is already registered. "
1114               "Check for duplicates in your configuration!",
1115               rf->rf_name);
1116     return EINVAL;
1117   }
1118
1119   le = llentry_create(rf->rf_name, rf);
1120   if (le == NULL) {
1121     pthread_mutex_unlock(&read_lock);
1122     ERROR("plugin_insert_read: llentry_create failed.");
1123     return -1;
1124   }
1125
1126   status = c_heap_insert(read_heap, rf);
1127   if (status != 0) {
1128     pthread_mutex_unlock(&read_lock);
1129     ERROR("plugin_insert_read: c_heap_insert failed.");
1130     llentry_destroy(le);
1131     return -1;
1132   }
1133
1134   /* This does not fail. */
1135   llist_append(read_list, le);
1136
1137   /* Wake up all the read threads. */
1138   pthread_cond_broadcast(&read_cond);
1139   pthread_mutex_unlock(&read_lock);
1140   return 0;
1141 } /* int plugin_insert_read */
1142
1143 EXPORT int plugin_register_read(const char *name, int (*callback)(void)) {
1144   read_func_t *rf;
1145   int status;
1146
1147   rf = calloc(1, sizeof(*rf));
1148   if (rf == NULL) {
1149     ERROR("plugin_register_read: calloc failed.");
1150     return ENOMEM;
1151   }
1152
1153   rf->rf_callback = (void *)callback;
1154   rf->rf_udata.data = NULL;
1155   rf->rf_udata.free_func = NULL;
1156   rf->rf_ctx = plugin_get_ctx();
1157   rf->rf_group[0] = '\0';
1158   rf->rf_name = strdup(name);
1159   rf->rf_type = RF_SIMPLE;
1160   rf->rf_interval = plugin_get_interval();
1161   rf->rf_ctx.interval = rf->rf_interval;
1162
1163   status = plugin_insert_read(rf);
1164   if (status != 0) {
1165     sfree(rf->rf_name);
1166     sfree(rf);
1167   }
1168
1169   return status;
1170 } /* int plugin_register_read */
1171
1172 EXPORT int plugin_register_complex_read(const char *group, const char *name,
1173                                         plugin_read_cb callback,
1174                                         cdtime_t interval,
1175                                         user_data_t const *user_data) {
1176   read_func_t *rf;
1177   int status;
1178
1179   rf = calloc(1, sizeof(*rf));
1180   if (rf == NULL) {
1181     free_userdata(user_data);
1182     ERROR("plugin_register_complex_read: calloc failed.");
1183     return ENOMEM;
1184   }
1185
1186   rf->rf_callback = (void *)callback;
1187   if (group != NULL)
1188     sstrncpy(rf->rf_group, group, sizeof(rf->rf_group));
1189   else
1190     rf->rf_group[0] = '\0';
1191   rf->rf_name = strdup(name);
1192   rf->rf_type = RF_COMPLEX;
1193   rf->rf_interval = (interval != 0) ? interval : plugin_get_interval();
1194
1195   /* Set user data */
1196   if (user_data == NULL) {
1197     rf->rf_udata.data = NULL;
1198     rf->rf_udata.free_func = NULL;
1199   } else {
1200     rf->rf_udata = *user_data;
1201   }
1202
1203   rf->rf_ctx = plugin_get_ctx();
1204   rf->rf_ctx.interval = rf->rf_interval;
1205
1206   status = plugin_insert_read(rf);
1207   if (status != 0) {
1208     free_userdata(&rf->rf_udata);
1209     sfree(rf->rf_name);
1210     sfree(rf);
1211   }
1212
1213   return status;
1214 } /* int plugin_register_complex_read */
1215
1216 EXPORT int plugin_register_write(const char *name, plugin_write_cb callback,
1217                                  user_data_t const *ud) {
1218   return create_register_callback(&list_write, name, (void *)callback, ud);
1219 } /* int plugin_register_write */
1220
1221 static int plugin_flush_timeout_callback(user_data_t *ud) {
1222   flush_callback_t *cb = ud->data;
1223
1224   return plugin_flush(cb->name, cb->timeout, NULL);
1225 } /* static int plugin_flush_callback */
1226
1227 static void plugin_flush_timeout_callback_free(void *data) {
1228   flush_callback_t *cb = data;
1229
1230   if (cb == NULL)
1231     return;
1232
1233   sfree(cb->name);
1234   sfree(cb);
1235 } /* static void plugin_flush_callback_free */
1236
1237 static char *plugin_flush_callback_name(const char *name) {
1238   const char *flush_prefix = "flush/";
1239   size_t prefix_size;
1240   char *flush_name;
1241   size_t name_size;
1242
1243   prefix_size = strlen(flush_prefix);
1244   name_size = strlen(name);
1245
1246   flush_name = malloc(name_size + prefix_size + 1);
1247   if (flush_name == NULL) {
1248     ERROR("plugin_flush_callback_name: malloc failed.");
1249     return NULL;
1250   }
1251
1252   sstrncpy(flush_name, flush_prefix, prefix_size + 1);
1253   sstrncpy(flush_name + prefix_size, name, name_size + 1);
1254
1255   return flush_name;
1256 } /* static char *plugin_flush_callback_name */
1257
1258 EXPORT int plugin_register_flush(const char *name, plugin_flush_cb callback,
1259                                  user_data_t const *ud) {
1260   int status;
1261   plugin_ctx_t ctx = plugin_get_ctx();
1262
1263   status = create_register_callback(&list_flush, name, (void *)callback, ud);
1264   if (status != 0)
1265     return status;
1266
1267   if (ctx.flush_interval != 0) {
1268     char *flush_name;
1269     flush_callback_t *cb;
1270
1271     flush_name = plugin_flush_callback_name(name);
1272     if (flush_name == NULL)
1273       return -1;
1274
1275     cb = malloc(sizeof(*cb));
1276     if (cb == NULL) {
1277       ERROR("plugin_register_flush: malloc failed.");
1278       sfree(flush_name);
1279       return -1;
1280     }
1281
1282     cb->name = strdup(name);
1283     if (cb->name == NULL) {
1284       ERROR("plugin_register_flush: strdup failed.");
1285       sfree(cb);
1286       sfree(flush_name);
1287       return -1;
1288     }
1289     cb->timeout = ctx.flush_timeout;
1290
1291     status = plugin_register_complex_read(
1292         /* group     = */ "flush",
1293         /* name      = */ flush_name,
1294         /* callback  = */ plugin_flush_timeout_callback,
1295         /* interval  = */ ctx.flush_interval,
1296         /* user data = */
1297         &(user_data_t){
1298             .data = cb,
1299             .free_func = plugin_flush_timeout_callback_free,
1300         });
1301
1302     sfree(flush_name);
1303     return status;
1304   }
1305
1306   return 0;
1307 } /* int plugin_register_flush */
1308
1309 EXPORT int plugin_register_missing(const char *name, plugin_missing_cb callback,
1310                                    user_data_t const *ud) {
1311   return create_register_callback(&list_missing, name, (void *)callback, ud);
1312 } /* int plugin_register_missing */
1313
1314 EXPORT int plugin_register_shutdown(const char *name, int (*callback)(void)) {
1315   return create_register_callback(&list_shutdown, name, (void *)callback, NULL);
1316 } /* int plugin_register_shutdown */
1317
1318 static void plugin_free_data_sets(void) {
1319   void *key;
1320   void *value;
1321
1322   if (data_sets == NULL)
1323     return;
1324
1325   while (c_avl_pick(data_sets, &key, &value) == 0) {
1326     data_set_t *ds = value;
1327     /* key is a pointer to ds->type */
1328
1329     sfree(ds->ds);
1330     sfree(ds);
1331   }
1332
1333   c_avl_destroy(data_sets);
1334   data_sets = NULL;
1335 } /* void plugin_free_data_sets */
1336
1337 EXPORT int plugin_register_data_set(const data_set_t *ds) {
1338   data_set_t *ds_copy;
1339
1340   if ((data_sets != NULL) && (c_avl_get(data_sets, ds->type, NULL) == 0)) {
1341     NOTICE("Replacing DS `%s' with another version.", ds->type);
1342     plugin_unregister_data_set(ds->type);
1343   } else if (data_sets == NULL) {
1344     data_sets = c_avl_create((int (*)(const void *, const void *))strcmp);
1345     if (data_sets == NULL)
1346       return -1;
1347   }
1348
1349   ds_copy = malloc(sizeof(*ds_copy));
1350   if (ds_copy == NULL)
1351     return -1;
1352   memcpy(ds_copy, ds, sizeof(data_set_t));
1353
1354   ds_copy->ds = malloc(sizeof(*ds_copy->ds) * ds->ds_num);
1355   if (ds_copy->ds == NULL) {
1356     sfree(ds_copy);
1357     return -1;
1358   }
1359
1360   for (size_t i = 0; i < ds->ds_num; i++)
1361     memcpy(ds_copy->ds + i, ds->ds + i, sizeof(data_source_t));
1362
1363   return c_avl_insert(data_sets, (void *)ds_copy->type, (void *)ds_copy);
1364 } /* int plugin_register_data_set */
1365
1366 EXPORT int plugin_register_log(const char *name, plugin_log_cb callback,
1367                                user_data_t const *ud) {
1368   return create_register_callback(&list_log, name, (void *)callback, ud);
1369 } /* int plugin_register_log */
1370
1371 EXPORT int plugin_register_notification(const char *name,
1372                                         plugin_notification_cb callback,
1373                                         user_data_t const *ud) {
1374   return create_register_callback(&list_notification, name, (void *)callback,
1375                                   ud);
1376 } /* int plugin_register_log */
1377
1378 EXPORT int plugin_unregister_config(const char *name) {
1379   cf_unregister(name);
1380   return 0;
1381 } /* int plugin_unregister_config */
1382
1383 EXPORT int plugin_unregister_complex_config(const char *name) {
1384   cf_unregister_complex(name);
1385   return 0;
1386 } /* int plugin_unregister_complex_config */
1387
1388 EXPORT int plugin_unregister_init(const char *name) {
1389   return plugin_unregister(list_init, name);
1390 }
1391
1392 EXPORT int plugin_unregister_read(const char *name) /* {{{ */
1393 {
1394   llentry_t *le;
1395   read_func_t *rf;
1396
1397   if (name == NULL)
1398     return -ENOENT;
1399
1400   pthread_mutex_lock(&read_lock);
1401
1402   if (read_list == NULL) {
1403     pthread_mutex_unlock(&read_lock);
1404     return -ENOENT;
1405   }
1406
1407   le = llist_search(read_list, name);
1408   if (le == NULL) {
1409     pthread_mutex_unlock(&read_lock);
1410     WARNING("plugin_unregister_read: No such read function: %s", name);
1411     return -ENOENT;
1412   }
1413
1414   llist_remove(read_list, le);
1415
1416   rf = le->value;
1417   assert(rf != NULL);
1418   rf->rf_type = RF_REMOVE;
1419
1420   pthread_mutex_unlock(&read_lock);
1421
1422   llentry_destroy(le);
1423
1424   DEBUG("plugin_unregister_read: Marked `%s' for removal.", name);
1425
1426   return 0;
1427 } /* }}} int plugin_unregister_read */
1428
1429 EXPORT void plugin_log_available_writers(void) {
1430   log_list_callbacks(&list_write, "Available write targets:");
1431 }
1432
1433 static int compare_read_func_group(llentry_t *e, void *ud) /* {{{ */
1434 {
1435   read_func_t *rf = e->value;
1436   char *group = ud;
1437
1438   return strcmp(rf->rf_group, (const char *)group);
1439 } /* }}} int compare_read_func_group */
1440
1441 EXPORT int plugin_unregister_read_group(const char *group) /* {{{ */
1442 {
1443   llentry_t *le;
1444   read_func_t *rf;
1445
1446   int found = 0;
1447
1448   if (group == NULL)
1449     return -ENOENT;
1450
1451   pthread_mutex_lock(&read_lock);
1452
1453   if (read_list == NULL) {
1454     pthread_mutex_unlock(&read_lock);
1455     return -ENOENT;
1456   }
1457
1458   while (42) {
1459     le = llist_search_custom(read_list, compare_read_func_group, (void *)group);
1460
1461     if (le == NULL)
1462       break;
1463
1464     ++found;
1465
1466     llist_remove(read_list, le);
1467
1468     rf = le->value;
1469     assert(rf != NULL);
1470     rf->rf_type = RF_REMOVE;
1471
1472     llentry_destroy(le);
1473
1474     DEBUG("plugin_unregister_read_group: "
1475           "Marked `%s' (group `%s') for removal.",
1476           rf->rf_name, group);
1477   }
1478
1479   pthread_mutex_unlock(&read_lock);
1480
1481   if (found == 0) {
1482     WARNING("plugin_unregister_read_group: No such "
1483             "group of read function: %s",
1484             group);
1485     return -ENOENT;
1486   }
1487
1488   return 0;
1489 } /* }}} int plugin_unregister_read_group */
1490
1491 EXPORT int plugin_unregister_write(const char *name) {
1492   return plugin_unregister(list_write, name);
1493 }
1494
1495 EXPORT int plugin_unregister_flush(const char *name) {
1496   plugin_ctx_t ctx = plugin_get_ctx();
1497
1498   if (ctx.flush_interval != 0) {
1499     char *flush_name;
1500
1501     flush_name = plugin_flush_callback_name(name);
1502     if (flush_name != NULL) {
1503       plugin_unregister_read(flush_name);
1504       sfree(flush_name);
1505     }
1506   }
1507
1508   return plugin_unregister(list_flush, name);
1509 }
1510
1511 EXPORT int plugin_unregister_missing(const char *name) {
1512   return plugin_unregister(list_missing, name);
1513 }
1514
1515 EXPORT int plugin_unregister_shutdown(const char *name) {
1516   return plugin_unregister(list_shutdown, name);
1517 }
1518
1519 EXPORT int plugin_unregister_data_set(const char *name) {
1520   data_set_t *ds;
1521
1522   if (data_sets == NULL)
1523     return -1;
1524
1525   if (c_avl_remove(data_sets, name, NULL, (void *)&ds) != 0)
1526     return -1;
1527
1528   sfree(ds->ds);
1529   sfree(ds);
1530
1531   return 0;
1532 } /* int plugin_unregister_data_set */
1533
1534 EXPORT int plugin_unregister_log(const char *name) {
1535   return plugin_unregister(list_log, name);
1536 }
1537
1538 EXPORT int plugin_unregister_notification(const char *name) {
1539   return plugin_unregister(list_notification, name);
1540 }
1541
1542 EXPORT int plugin_init_all(void) {
1543   char const *chain_name;
1544   llentry_t *le;
1545   int status;
1546   int ret = 0;
1547
1548   /* Init the value cache */
1549   uc_init();
1550
1551   if (IS_TRUE(global_option_get("CollectInternalStats"))) {
1552     record_statistics = true;
1553     plugin_register_read("collectd", plugin_update_internal_statistics);
1554   }
1555
1556   chain_name = global_option_get("PreCacheChain");
1557   pre_cache_chain = fc_chain_get_by_name(chain_name);
1558
1559   chain_name = global_option_get("PostCacheChain");
1560   post_cache_chain = fc_chain_get_by_name(chain_name);
1561
1562   write_limit_high = global_option_get_long("WriteQueueLimitHigh",
1563                                             /* default = */ 0);
1564   if (write_limit_high < 0) {
1565     ERROR("WriteQueueLimitHigh must be positive or zero.");
1566     write_limit_high = 0;
1567   }
1568
1569   write_limit_low =
1570       global_option_get_long("WriteQueueLimitLow",
1571                              /* default = */ write_limit_high / 2);
1572   if (write_limit_low < 0) {
1573     ERROR("WriteQueueLimitLow must be positive or zero.");
1574     write_limit_low = write_limit_high / 2;
1575   } else if (write_limit_low > write_limit_high) {
1576     ERROR("WriteQueueLimitLow must not be larger than "
1577           "WriteQueueLimitHigh.");
1578     write_limit_low = write_limit_high;
1579   }
1580
1581   write_threads_num = global_option_get_long("WriteThreads",
1582                                              /* default = */ 5);
1583   if (write_threads_num < 1) {
1584     ERROR("WriteThreads must be positive.");
1585     write_threads_num = 5;
1586   }
1587
1588   if ((list_init == NULL) && (read_heap == NULL))
1589     return ret;
1590
1591   /* Calling all init callbacks before checking if read callbacks
1592    * are available allows the init callbacks to register the read
1593    * callback. */
1594   le = llist_head(list_init);
1595   while (le != NULL) {
1596     callback_func_t *cf;
1597     plugin_init_cb callback;
1598     plugin_ctx_t old_ctx;
1599
1600     cf = le->value;
1601     old_ctx = plugin_set_ctx(cf->cf_ctx);
1602     callback = cf->cf_callback;
1603     status = (*callback)();
1604     plugin_set_ctx(old_ctx);
1605
1606     if (status != 0) {
1607       ERROR("Initialization of plugin `%s' "
1608             "failed with status %i. "
1609             "Plugin will be unloaded.",
1610             le->key, status);
1611       /* Plugins that register read callbacks from the init
1612        * callback should take care of appropriate error
1613        * handling themselves. */
1614       /* FIXME: Unload _all_ functions */
1615       plugin_unregister_read(le->key);
1616       ret = -1;
1617     }
1618
1619     le = le->next;
1620   }
1621
1622   start_write_threads((size_t)write_threads_num);
1623
1624   max_read_interval =
1625       global_option_get_time("MaxReadInterval", DEFAULT_MAX_READ_INTERVAL);
1626
1627   /* Start read-threads */
1628   if (read_heap != NULL) {
1629     const char *rt;
1630     int num;
1631
1632     rt = global_option_get("ReadThreads");
1633     num = atoi(rt);
1634     if (num != -1)
1635       start_read_threads((num > 0) ? ((size_t)num) : 5);
1636   }
1637   return ret;
1638 } /* void plugin_init_all */
1639
1640 /* TODO: Rename this function. */
1641 EXPORT void plugin_read_all(void) {
1642   uc_check_timeout();
1643
1644   return;
1645 } /* void plugin_read_all */
1646
1647 /* Read function called when the `-T' command line argument is given. */
1648 EXPORT int plugin_read_all_once(void) {
1649   int status;
1650   int return_status = 0;
1651
1652   if (read_heap == NULL) {
1653     NOTICE("No read-functions are registered.");
1654     return 0;
1655   }
1656
1657   while (42) {
1658     read_func_t *rf;
1659     plugin_ctx_t old_ctx;
1660
1661     rf = c_heap_get_root(read_heap);
1662     if (rf == NULL)
1663       break;
1664
1665     old_ctx = plugin_set_ctx(rf->rf_ctx);
1666
1667     if (rf->rf_type == RF_SIMPLE) {
1668       int (*callback)(void);
1669
1670       callback = rf->rf_callback;
1671       status = (*callback)();
1672     } else {
1673       plugin_read_cb callback;
1674
1675       callback = rf->rf_callback;
1676       status = (*callback)(&rf->rf_udata);
1677     }
1678
1679     plugin_set_ctx(old_ctx);
1680
1681     if (status != 0) {
1682       NOTICE("read-function of plugin `%s' failed.", rf->rf_name);
1683       return_status = -1;
1684     }
1685
1686     sfree(rf->rf_name);
1687     destroy_callback((void *)rf);
1688   }
1689
1690   return return_status;
1691 } /* int plugin_read_all_once */
1692
1693 EXPORT int plugin_write(const char *plugin, /* {{{ */
1694                         const data_set_t *ds, const value_list_t *vl) {
1695   llentry_t *le;
1696   int status;
1697
1698   if (vl == NULL)
1699     return EINVAL;
1700
1701   if (list_write == NULL)
1702     return ENOENT;
1703
1704   if (ds == NULL) {
1705     ds = plugin_get_ds(vl->type);
1706     if (ds == NULL) {
1707       ERROR("plugin_write: Unable to lookup type `%s'.", vl->type);
1708       return ENOENT;
1709     }
1710   }
1711
1712   if (plugin == NULL) {
1713     int success = 0;
1714     int failure = 0;
1715
1716     le = llist_head(list_write);
1717     while (le != NULL) {
1718       callback_func_t *cf = le->value;
1719       plugin_write_cb callback;
1720
1721       /* Keep the read plugin's interval and flush information but update the
1722        * plugin name. */
1723       plugin_ctx_t old_ctx = plugin_get_ctx();
1724       plugin_ctx_t ctx = old_ctx;
1725       ctx.name = cf->cf_ctx.name;
1726       plugin_set_ctx(ctx);
1727
1728       DEBUG("plugin: plugin_write: Writing values via %s.", le->key);
1729       callback = cf->cf_callback;
1730       status = (*callback)(ds, vl, &cf->cf_udata);
1731       if (status != 0)
1732         failure++;
1733       else
1734         success++;
1735
1736       plugin_set_ctx(old_ctx);
1737       le = le->next;
1738     }
1739
1740     if ((success == 0) && (failure != 0))
1741       status = -1;
1742     else
1743       status = 0;
1744   } else /* plugin != NULL */
1745   {
1746     callback_func_t *cf;
1747     plugin_write_cb callback;
1748
1749     le = llist_head(list_write);
1750     while (le != NULL) {
1751       if (strcasecmp(plugin, le->key) == 0)
1752         break;
1753
1754       le = le->next;
1755     }
1756
1757     if (le == NULL)
1758       return ENOENT;
1759
1760     cf = le->value;
1761
1762     /* do not switch plugin context; rather keep the context (interval)
1763      * information of the calling read plugin */
1764
1765     DEBUG("plugin: plugin_write: Writing values via %s.", le->key);
1766     callback = cf->cf_callback;
1767     status = (*callback)(ds, vl, &cf->cf_udata);
1768   }
1769
1770   return status;
1771 } /* }}} int plugin_write */
1772
1773 EXPORT int plugin_flush(const char *plugin, cdtime_t timeout,
1774                         const char *identifier) {
1775   llentry_t *le;
1776
1777   if (list_flush == NULL)
1778     return 0;
1779
1780   le = llist_head(list_flush);
1781   while (le != NULL) {
1782     callback_func_t *cf;
1783     plugin_flush_cb callback;
1784     plugin_ctx_t old_ctx;
1785
1786     if ((plugin != NULL) && (strcmp(plugin, le->key) != 0)) {
1787       le = le->next;
1788       continue;
1789     }
1790
1791     cf = le->value;
1792     old_ctx = plugin_set_ctx(cf->cf_ctx);
1793     callback = cf->cf_callback;
1794
1795     (*callback)(timeout, identifier, &cf->cf_udata);
1796
1797     plugin_set_ctx(old_ctx);
1798
1799     le = le->next;
1800   }
1801   return 0;
1802 } /* int plugin_flush */
1803
1804 EXPORT int plugin_shutdown_all(void) {
1805   llentry_t *le;
1806   int ret = 0; // Assume success.
1807
1808   destroy_all_callbacks(&list_init);
1809
1810   stop_read_threads();
1811
1812   pthread_mutex_lock(&read_lock);
1813   llist_destroy(read_list);
1814   read_list = NULL;
1815   pthread_mutex_unlock(&read_lock);
1816
1817   destroy_read_heap();
1818
1819   /* blocks until all write threads have shut down. */
1820   stop_write_threads();
1821
1822   /* ask all plugins to write out the state they kept. */
1823   plugin_flush(/* plugin = */ NULL,
1824                /* timeout = */ 0,
1825                /* identifier = */ NULL);
1826
1827   le = NULL;
1828   if (list_shutdown != NULL)
1829     le = llist_head(list_shutdown);
1830
1831   while (le != NULL) {
1832     callback_func_t *cf;
1833     plugin_shutdown_cb callback;
1834     plugin_ctx_t old_ctx;
1835
1836     cf = le->value;
1837     old_ctx = plugin_set_ctx(cf->cf_ctx);
1838     callback = cf->cf_callback;
1839
1840     /* Advance the pointer before calling the callback allows
1841      * shutdown functions to unregister themselves. If done the
1842      * other way around the memory `le' points to will be freed
1843      * after callback returns. */
1844     le = le->next;
1845
1846     if ((*callback)() != 0)
1847       ret = -1;
1848
1849     plugin_set_ctx(old_ctx);
1850   }
1851
1852   /* Write plugins which use the `user_data' pointer usually need the
1853    * same data available to the flush callback. If this is the case, set
1854    * the free_function to NULL when registering the flush callback and to
1855    * the real free function when registering the write callback. This way
1856    * the data isn't freed twice. */
1857   destroy_all_callbacks(&list_flush);
1858   destroy_all_callbacks(&list_missing);
1859   destroy_all_callbacks(&list_write);
1860
1861   destroy_all_callbacks(&list_notification);
1862   destroy_all_callbacks(&list_shutdown);
1863   destroy_all_callbacks(&list_log);
1864
1865   plugin_free_loaded();
1866   plugin_free_data_sets();
1867   return ret;
1868 } /* void plugin_shutdown_all */
1869
1870 EXPORT int plugin_dispatch_missing(const value_list_t *vl) /* {{{ */
1871 {
1872   if (list_missing == NULL)
1873     return 0;
1874
1875   llentry_t *le = llist_head(list_missing);
1876   while (le != NULL) {
1877     callback_func_t *cf = le->value;
1878     plugin_ctx_t old_ctx = plugin_set_ctx(cf->cf_ctx);
1879     plugin_missing_cb callback = cf->cf_callback;
1880
1881     int status = (*callback)(vl, &cf->cf_udata);
1882     plugin_set_ctx(old_ctx);
1883     if (status != 0) {
1884       if (status < 0) {
1885         ERROR("plugin_dispatch_missing: Callback function \"%s\" "
1886               "failed with status %i.",
1887               le->key, status);
1888         return status;
1889       } else {
1890         return 0;
1891       }
1892     }
1893
1894     le = le->next;
1895   }
1896   return 0;
1897 } /* int }}} plugin_dispatch_missing */
1898
1899 static int plugin_dispatch_values_internal(value_list_t *vl) {
1900   int status;
1901   static c_complain_t no_write_complaint = C_COMPLAIN_INIT_STATIC;
1902
1903   bool free_meta_data = false;
1904
1905   assert(vl != NULL);
1906
1907   /* These fields are initialized by plugin_value_list_clone() if needed: */
1908   assert(vl->host[0] != 0);
1909   assert(vl->time != 0); /* The time is determined at _enqueue_ time. */
1910   assert(vl->interval != 0);
1911
1912   if (vl->type[0] == 0 || vl->values == NULL || vl->values_len < 1) {
1913     ERROR("plugin_dispatch_values: Invalid value list "
1914           "from plugin %s.",
1915           vl->plugin);
1916     return -1;
1917   }
1918
1919   /* Free meta data only if the calling function didn't specify any. In
1920    * this case matches and targets may add some and the calling function
1921    * may not expect (and therefore free) that data. */
1922   if (vl->meta == NULL)
1923     free_meta_data = true;
1924
1925   if (list_write == NULL)
1926     c_complain_once(LOG_WARNING, &no_write_complaint,
1927                     "plugin_dispatch_values: No write callback has been "
1928                     "registered. Please load at least one output plugin, "
1929                     "if you want the collected data to be stored.");
1930
1931   if (data_sets == NULL) {
1932     ERROR("plugin_dispatch_values: No data sets registered. "
1933           "Could the types database be read? Check "
1934           "your `TypesDB' setting!");
1935     return -1;
1936   }
1937
1938   data_set_t *ds = NULL;
1939   if (c_avl_get(data_sets, vl->type, (void *)&ds) != 0) {
1940     char ident[6 * DATA_MAX_NAME_LEN];
1941
1942     FORMAT_VL(ident, sizeof(ident), vl);
1943     INFO("plugin_dispatch_values: Dataset not found: %s "
1944          "(from \"%s\"), check your types.db!",
1945          vl->type, ident);
1946     return -1;
1947   }
1948
1949   DEBUG("plugin_dispatch_values: time = %.3f; interval = %.3f; "
1950         "host = %s; "
1951         "plugin = %s; plugin_instance = %s; "
1952         "type = %s; type_instance = %s;",
1953         CDTIME_T_TO_DOUBLE(vl->time), CDTIME_T_TO_DOUBLE(vl->interval),
1954         vl->host, vl->plugin, vl->plugin_instance, vl->type, vl->type_instance);
1955
1956 #if COLLECT_DEBUG
1957   assert(0 == strcmp(ds->type, vl->type));
1958 #else
1959   if (0 != strcmp(ds->type, vl->type))
1960     WARNING("plugin_dispatch_values: (ds->type = %s) != (vl->type = %s)",
1961             ds->type, vl->type);
1962 #endif
1963
1964 #if COLLECT_DEBUG
1965   assert(ds->ds_num == vl->values_len);
1966 #else
1967   if (ds->ds_num != vl->values_len) {
1968     ERROR("plugin_dispatch_values: ds->type = %s: "
1969           "(ds->ds_num = %" PRIsz ") != "
1970           "(vl->values_len = %" PRIsz ")",
1971           ds->type, ds->ds_num, vl->values_len);
1972     return -1;
1973   }
1974 #endif
1975
1976   escape_slashes(vl->host, sizeof(vl->host));
1977   escape_slashes(vl->plugin, sizeof(vl->plugin));
1978   escape_slashes(vl->plugin_instance, sizeof(vl->plugin_instance));
1979   escape_slashes(vl->type, sizeof(vl->type));
1980   escape_slashes(vl->type_instance, sizeof(vl->type_instance));
1981
1982   if (pre_cache_chain != NULL) {
1983     status = fc_process_chain(ds, vl, pre_cache_chain);
1984     if (status < 0) {
1985       WARNING("plugin_dispatch_values: Running the "
1986               "pre-cache chain failed with "
1987               "status %i (%#x).",
1988               status, status);
1989     } else if (status == FC_TARGET_STOP)
1990       return 0;
1991   }
1992
1993   /* Update the value cache */
1994   uc_update(ds, vl);
1995
1996   if (post_cache_chain != NULL) {
1997     status = fc_process_chain(ds, vl, post_cache_chain);
1998     if (status < 0) {
1999       WARNING("plugin_dispatch_values: Running the "
2000               "post-cache chain failed with "
2001               "status %i (%#x).",
2002               status, status);
2003     }
2004   } else
2005     fc_default_action(ds, vl);
2006
2007   if ((free_meta_data == true) && (vl->meta != NULL)) {
2008     meta_data_destroy(vl->meta);
2009     vl->meta = NULL;
2010   }
2011
2012   return 0;
2013 } /* int plugin_dispatch_values_internal */
2014
2015 static double get_drop_probability(void) /* {{{ */
2016 {
2017   long pos;
2018   long size;
2019   long wql;
2020
2021   pthread_mutex_lock(&write_lock);
2022   wql = write_queue_length;
2023   pthread_mutex_unlock(&write_lock);
2024
2025   if (wql < write_limit_low)
2026     return 0.0;
2027   if (wql >= write_limit_high)
2028     return 1.0;
2029
2030   pos = 1 + wql - write_limit_low;
2031   size = 1 + write_limit_high - write_limit_low;
2032
2033   return (double)pos / (double)size;
2034 } /* }}} double get_drop_probability */
2035
2036 static bool check_drop_value(void) /* {{{ */
2037 {
2038   static cdtime_t last_message_time;
2039   static pthread_mutex_t last_message_lock = PTHREAD_MUTEX_INITIALIZER;
2040
2041   double p;
2042   double q;
2043   int status;
2044
2045   if (write_limit_high == 0)
2046     return false;
2047
2048   p = get_drop_probability();
2049   if (p == 0.0)
2050     return false;
2051
2052   status = pthread_mutex_trylock(&last_message_lock);
2053   if (status == 0) {
2054     cdtime_t now;
2055
2056     now = cdtime();
2057     if ((now - last_message_time) > TIME_T_TO_CDTIME_T(1)) {
2058       last_message_time = now;
2059       ERROR("plugin_dispatch_values: Low water mark "
2060             "reached. Dropping %.0f%% of metrics.",
2061             100.0 * p);
2062     }
2063     pthread_mutex_unlock(&last_message_lock);
2064   }
2065
2066   if (p == 1.0)
2067     return true;
2068
2069   q = cdrand_d();
2070   if (q > p)
2071     return true;
2072   else
2073     return false;
2074 } /* }}} bool check_drop_value */
2075
2076 EXPORT int plugin_dispatch_values(value_list_t const *vl) {
2077   int status;
2078
2079   if (check_drop_value()) {
2080     if (record_statistics) {
2081       pthread_mutex_lock(&statistics_lock);
2082       stats_values_dropped++;
2083       pthread_mutex_unlock(&statistics_lock);
2084     }
2085     return 0;
2086   }
2087
2088   status = plugin_write_enqueue(vl);
2089   if (status != 0) {
2090     ERROR("plugin_dispatch_values: plugin_write_enqueue failed with status %i "
2091           "(%s).",
2092           status, STRERROR(status));
2093     return status;
2094   }
2095
2096   return 0;
2097 }
2098
2099 __attribute__((sentinel)) int
2100 plugin_dispatch_multivalue(value_list_t const *template, /* {{{ */
2101                            bool store_percentage, int store_type, ...) {
2102   value_list_t *vl;
2103   int failed = 0;
2104   gauge_t sum = 0.0;
2105   va_list ap;
2106
2107   if (check_drop_value()) {
2108     if (record_statistics) {
2109       pthread_mutex_lock(&statistics_lock);
2110       stats_values_dropped++;
2111       pthread_mutex_unlock(&statistics_lock);
2112     }
2113     return 0;
2114   }
2115
2116   assert(template->values_len == 1);
2117
2118   /* Calculate sum for Gauge to calculate percent if needed */
2119   if (DS_TYPE_GAUGE == store_type) {
2120     va_start(ap, store_type);
2121     while (42) {
2122       char const *name;
2123       gauge_t value;
2124
2125       name = va_arg(ap, char const *);
2126       if (name == NULL)
2127         break;
2128
2129       value = va_arg(ap, gauge_t);
2130       if (!isnan(value))
2131         sum += value;
2132     }
2133     va_end(ap);
2134   }
2135
2136   vl = plugin_value_list_clone(template);
2137   /* plugin_value_list_clone makes sure vl->time is set to non-zero. */
2138   if (store_percentage)
2139     sstrncpy(vl->type, "percent", sizeof(vl->type));
2140
2141   va_start(ap, store_type);
2142   while (42) {
2143     char const *name;
2144     int status;
2145
2146     /* Set the type instance. */
2147     name = va_arg(ap, char const *);
2148     if (name == NULL)
2149       break;
2150     sstrncpy(vl->type_instance, name, sizeof(vl->type_instance));
2151
2152     /* Set the value. */
2153     switch (store_type) {
2154     case DS_TYPE_GAUGE:
2155       vl->values[0].gauge = va_arg(ap, gauge_t);
2156       if (store_percentage)
2157         vl->values[0].gauge *= sum ? (100.0 / sum) : NAN;
2158       break;
2159     case DS_TYPE_ABSOLUTE:
2160       vl->values[0].absolute = va_arg(ap, absolute_t);
2161       break;
2162     case DS_TYPE_COUNTER:
2163       vl->values[0].counter = va_arg(ap, counter_t);
2164       break;
2165     case DS_TYPE_DERIVE:
2166       vl->values[0].derive = va_arg(ap, derive_t);
2167       break;
2168     default:
2169       ERROR("plugin_dispatch_multivalue: given store_type is incorrect.");
2170       failed++;
2171     }
2172
2173     status = plugin_write_enqueue(vl);
2174     if (status != 0)
2175       failed++;
2176   }
2177   va_end(ap);
2178
2179   plugin_value_list_free(vl);
2180   return failed;
2181 } /* }}} int plugin_dispatch_multivalue */
2182
2183 EXPORT int plugin_dispatch_notification(const notification_t *notif) {
2184   llentry_t *le;
2185   /* Possible TODO: Add flap detection here */
2186
2187   DEBUG("plugin_dispatch_notification: severity = %i; message = %s; "
2188         "time = %.3f; host = %s;",
2189         notif->severity, notif->message, CDTIME_T_TO_DOUBLE(notif->time),
2190         notif->host);
2191
2192   /* Nobody cares for notifications */
2193   if (list_notification == NULL)
2194     return -1;
2195
2196   le = llist_head(list_notification);
2197   while (le != NULL) {
2198     callback_func_t *cf;
2199     plugin_notification_cb callback;
2200     int status;
2201
2202     /* do not switch plugin context; rather keep the context
2203      * (interval) information of the calling plugin */
2204
2205     cf = le->value;
2206     callback = cf->cf_callback;
2207     status = (*callback)(notif, &cf->cf_udata);
2208     if (status != 0) {
2209       WARNING("plugin_dispatch_notification: Notification "
2210               "callback %s returned %i.",
2211               le->key, status);
2212     }
2213
2214     le = le->next;
2215   }
2216
2217   return 0;
2218 } /* int plugin_dispatch_notification */
2219
2220 EXPORT void plugin_log(int level, const char *format, ...) {
2221   char msg[1024];
2222   va_list ap;
2223   llentry_t *le;
2224
2225 #if !COLLECT_DEBUG
2226   if (level >= LOG_DEBUG)
2227     return;
2228 #endif
2229
2230   va_start(ap, format);
2231   vsnprintf(msg, sizeof(msg), format, ap);
2232   msg[sizeof(msg) - 1] = '\0';
2233   va_end(ap);
2234
2235   if (list_log == NULL) {
2236     fprintf(stderr, "%s\n", msg);
2237     return;
2238   }
2239
2240   le = llist_head(list_log);
2241   while (le != NULL) {
2242     callback_func_t *cf;
2243     plugin_log_cb callback;
2244
2245     cf = le->value;
2246     callback = cf->cf_callback;
2247
2248     /* do not switch plugin context; rather keep the context
2249      * (interval) information of the calling plugin */
2250
2251     (*callback)(level, msg, &cf->cf_udata);
2252
2253     le = le->next;
2254   }
2255 } /* void plugin_log */
2256
2257 void daemon_log(int level, const char *format, ...) {
2258   char msg[1024] = ""; // Size inherits from plugin_log()
2259
2260   char const *name = plugin_get_ctx().name;
2261   if (name == NULL)
2262     name = "UNKNOWN";
2263
2264   va_list ap;
2265   va_start(ap, format);
2266   vsnprintf(msg, sizeof(msg), format, ap);
2267   va_end(ap);
2268
2269   plugin_log(level, "%s plugin: %s", name, msg);
2270 } /* void daemon_log */
2271
2272 int parse_log_severity(const char *severity) {
2273   int log_level = -1;
2274
2275   if ((0 == strcasecmp(severity, "emerg")) ||
2276       (0 == strcasecmp(severity, "alert")) ||
2277       (0 == strcasecmp(severity, "crit")) || (0 == strcasecmp(severity, "err")))
2278     log_level = LOG_ERR;
2279   else if (0 == strcasecmp(severity, "warning"))
2280     log_level = LOG_WARNING;
2281   else if (0 == strcasecmp(severity, "notice"))
2282     log_level = LOG_NOTICE;
2283   else if (0 == strcasecmp(severity, "info"))
2284     log_level = LOG_INFO;
2285 #if COLLECT_DEBUG
2286   else if (0 == strcasecmp(severity, "debug"))
2287     log_level = LOG_DEBUG;
2288 #endif /* COLLECT_DEBUG */
2289
2290   return log_level;
2291 } /* int parse_log_severity */
2292
2293 EXPORT int parse_notif_severity(const char *severity) {
2294   int notif_severity = -1;
2295
2296   if (strcasecmp(severity, "FAILURE") == 0)
2297     notif_severity = NOTIF_FAILURE;
2298   else if (strcmp(severity, "OKAY") == 0)
2299     notif_severity = NOTIF_OKAY;
2300   else if ((strcmp(severity, "WARNING") == 0) ||
2301            (strcmp(severity, "WARN") == 0))
2302     notif_severity = NOTIF_WARNING;
2303
2304   return notif_severity;
2305 } /* int parse_notif_severity */
2306
2307 EXPORT const data_set_t *plugin_get_ds(const char *name) {
2308   data_set_t *ds;
2309
2310   if (data_sets == NULL) {
2311     P_ERROR("plugin_get_ds: No data sets are defined yet.");
2312     return NULL;
2313   }
2314
2315   if (c_avl_get(data_sets, name, (void *)&ds) != 0) {
2316     DEBUG("No such dataset registered: %s", name);
2317     return NULL;
2318   }
2319
2320   return ds;
2321 } /* data_set_t *plugin_get_ds */
2322
2323 static int plugin_notification_meta_add(notification_t *n, const char *name,
2324                                         enum notification_meta_type_e type,
2325                                         const void *value) {
2326   notification_meta_t *meta;
2327   notification_meta_t *tail;
2328
2329   if ((n == NULL) || (name == NULL) || (value == NULL)) {
2330     ERROR("plugin_notification_meta_add: A pointer is NULL!");
2331     return -1;
2332   }
2333
2334   meta = calloc(1, sizeof(*meta));
2335   if (meta == NULL) {
2336     ERROR("plugin_notification_meta_add: calloc failed.");
2337     return -1;
2338   }
2339
2340   sstrncpy(meta->name, name, sizeof(meta->name));
2341   meta->type = type;
2342
2343   switch (type) {
2344   case NM_TYPE_STRING: {
2345     meta->nm_value.nm_string = strdup((const char *)value);
2346     if (meta->nm_value.nm_string == NULL) {
2347       ERROR("plugin_notification_meta_add: strdup failed.");
2348       sfree(meta);
2349       return -1;
2350     }
2351     break;
2352   }
2353   case NM_TYPE_SIGNED_INT: {
2354     meta->nm_value.nm_signed_int = *((int64_t *)value);
2355     break;
2356   }
2357   case NM_TYPE_UNSIGNED_INT: {
2358     meta->nm_value.nm_unsigned_int = *((uint64_t *)value);
2359     break;
2360   }
2361   case NM_TYPE_DOUBLE: {
2362     meta->nm_value.nm_double = *((double *)value);
2363     break;
2364   }
2365   case NM_TYPE_BOOLEAN: {
2366     meta->nm_value.nm_boolean = *((bool *)value);
2367     break;
2368   }
2369   default: {
2370     ERROR("plugin_notification_meta_add: Unknown type: %i", type);
2371     sfree(meta);
2372     return -1;
2373   }
2374   } /* switch (type) */
2375
2376   meta->next = NULL;
2377   tail = n->meta;
2378   while ((tail != NULL) && (tail->next != NULL))
2379     tail = tail->next;
2380
2381   if (tail == NULL)
2382     n->meta = meta;
2383   else
2384     tail->next = meta;
2385
2386   return 0;
2387 } /* int plugin_notification_meta_add */
2388
2389 int plugin_notification_meta_add_string(notification_t *n, const char *name,
2390                                         const char *value) {
2391   return plugin_notification_meta_add(n, name, NM_TYPE_STRING, value);
2392 }
2393
2394 int plugin_notification_meta_add_signed_int(notification_t *n, const char *name,
2395                                             int64_t value) {
2396   return plugin_notification_meta_add(n, name, NM_TYPE_SIGNED_INT, &value);
2397 }
2398
2399 int plugin_notification_meta_add_unsigned_int(notification_t *n,
2400                                               const char *name,
2401                                               uint64_t value) {
2402   return plugin_notification_meta_add(n, name, NM_TYPE_UNSIGNED_INT, &value);
2403 }
2404
2405 int plugin_notification_meta_add_double(notification_t *n, const char *name,
2406                                         double value) {
2407   return plugin_notification_meta_add(n, name, NM_TYPE_DOUBLE, &value);
2408 }
2409
2410 int plugin_notification_meta_add_boolean(notification_t *n, const char *name,
2411                                          bool value) {
2412   return plugin_notification_meta_add(n, name, NM_TYPE_BOOLEAN, &value);
2413 }
2414
2415 int plugin_notification_meta_copy(notification_t *dst,
2416                                   const notification_t *src) {
2417   assert(dst != NULL);
2418   assert(src != NULL);
2419   assert(dst != src);
2420   assert((src->meta == NULL) || (src->meta != dst->meta));
2421
2422   for (notification_meta_t *meta = src->meta; meta != NULL; meta = meta->next) {
2423     if (meta->type == NM_TYPE_STRING)
2424       plugin_notification_meta_add_string(dst, meta->name,
2425                                           meta->nm_value.nm_string);
2426     else if (meta->type == NM_TYPE_SIGNED_INT)
2427       plugin_notification_meta_add_signed_int(dst, meta->name,
2428                                               meta->nm_value.nm_signed_int);
2429     else if (meta->type == NM_TYPE_UNSIGNED_INT)
2430       plugin_notification_meta_add_unsigned_int(dst, meta->name,
2431                                                 meta->nm_value.nm_unsigned_int);
2432     else if (meta->type == NM_TYPE_DOUBLE)
2433       plugin_notification_meta_add_double(dst, meta->name,
2434                                           meta->nm_value.nm_double);
2435     else if (meta->type == NM_TYPE_BOOLEAN)
2436       plugin_notification_meta_add_boolean(dst, meta->name,
2437                                            meta->nm_value.nm_boolean);
2438   }
2439
2440   return 0;
2441 } /* int plugin_notification_meta_copy */
2442
2443 int plugin_notification_meta_free(notification_meta_t *n) {
2444   notification_meta_t *this;
2445   notification_meta_t *next;
2446
2447   if (n == NULL) {
2448     ERROR("plugin_notification_meta_free: n == NULL!");
2449     return -1;
2450   }
2451
2452   this = n;
2453   while (this != NULL) {
2454     next = this->next;
2455
2456     if (this->type == NM_TYPE_STRING) {
2457       /* Assign to a temporary variable to work around nm_string's const
2458        * modifier. */
2459       void *tmp = (void *)this->nm_value.nm_string;
2460
2461       sfree(tmp);
2462       this->nm_value.nm_string = NULL;
2463     }
2464     sfree(this);
2465
2466     this = next;
2467   }
2468
2469   return 0;
2470 } /* int plugin_notification_meta_free */
2471
2472 static void plugin_ctx_destructor(void *ctx) {
2473   sfree(ctx);
2474 } /* void plugin_ctx_destructor */
2475
2476 static plugin_ctx_t ctx_init = {/* interval = */ 0};
2477
2478 static plugin_ctx_t *plugin_ctx_create(void) {
2479   plugin_ctx_t *ctx;
2480
2481   ctx = malloc(sizeof(*ctx));
2482   if (ctx == NULL) {
2483     ERROR("Failed to allocate plugin context: %s", STRERRNO);
2484     return NULL;
2485   }
2486
2487   *ctx = ctx_init;
2488   assert(plugin_ctx_key_initialized);
2489   pthread_setspecific(plugin_ctx_key, ctx);
2490   DEBUG("Created new plugin context.");
2491   return ctx;
2492 } /* int plugin_ctx_create */
2493
2494 EXPORT void plugin_init_ctx(void) {
2495   pthread_key_create(&plugin_ctx_key, plugin_ctx_destructor);
2496   plugin_ctx_key_initialized = true;
2497 } /* void plugin_init_ctx */
2498
2499 EXPORT plugin_ctx_t plugin_get_ctx(void) {
2500   plugin_ctx_t *ctx;
2501
2502   assert(plugin_ctx_key_initialized);
2503   ctx = pthread_getspecific(plugin_ctx_key);
2504
2505   if (ctx == NULL) {
2506     ctx = plugin_ctx_create();
2507     /* this must no happen -- exit() instead? */
2508     if (ctx == NULL)
2509       return ctx_init;
2510   }
2511
2512   return *ctx;
2513 } /* plugin_ctx_t plugin_get_ctx */
2514
2515 EXPORT plugin_ctx_t plugin_set_ctx(plugin_ctx_t ctx) {
2516   plugin_ctx_t *c;
2517   plugin_ctx_t old;
2518
2519   assert(plugin_ctx_key_initialized);
2520   c = pthread_getspecific(plugin_ctx_key);
2521
2522   if (c == NULL) {
2523     c = plugin_ctx_create();
2524     /* this must no happen -- exit() instead? */
2525     if (c == NULL)
2526       return ctx_init;
2527   }
2528
2529   old = *c;
2530   *c = ctx;
2531
2532   return old;
2533 } /* void plugin_set_ctx */
2534
2535 EXPORT cdtime_t plugin_get_interval(void) {
2536   cdtime_t interval;
2537
2538   interval = plugin_get_ctx().interval;
2539   if (interval > 0)
2540     return interval;
2541
2542   P_ERROR("plugin_get_interval: Unable to determine Interval from context.");
2543
2544   return cf_get_default_interval();
2545 } /* cdtime_t plugin_get_interval */
2546
2547 typedef struct {
2548   plugin_ctx_t ctx;
2549   void *(*start_routine)(void *);
2550   void *arg;
2551 } plugin_thread_t;
2552
2553 static void *plugin_thread_start(void *arg) {
2554   plugin_thread_t *plugin_thread = arg;
2555
2556   void *(*start_routine)(void *) = plugin_thread->start_routine;
2557   void *plugin_arg = plugin_thread->arg;
2558
2559   plugin_set_ctx(plugin_thread->ctx);
2560
2561   sfree(plugin_thread);
2562
2563   return start_routine(plugin_arg);
2564 } /* void *plugin_thread_start */
2565
2566 int plugin_thread_create(pthread_t *thread, const pthread_attr_t *attr,
2567                          void *(*start_routine)(void *), void *arg,
2568                          char const *name) {
2569   plugin_thread_t *plugin_thread;
2570
2571   plugin_thread = malloc(sizeof(*plugin_thread));
2572   if (plugin_thread == NULL)
2573     return ENOMEM;
2574
2575   plugin_thread->ctx = plugin_get_ctx();
2576   plugin_thread->start_routine = start_routine;
2577   plugin_thread->arg = arg;
2578
2579   int ret = pthread_create(thread, attr, plugin_thread_start, plugin_thread);
2580   if (ret != 0) {
2581     sfree(plugin_thread);
2582     return ret;
2583   }
2584
2585   if (name != NULL)
2586     set_thread_name(*thread, name);
2587
2588   return 0;
2589 } /* int plugin_thread_create */