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