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