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