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