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