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