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