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