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