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