ac9ce5bd16df5a40dc89a4543c3ccd89b344510d
[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 int             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 static void start_read_threads (int num)
655 {
656         if (read_threads != NULL)
657                 return;
658
659         read_threads = (pthread_t *) calloc (num, sizeof (pthread_t));
660         if (read_threads == NULL)
661         {
662                 ERROR ("plugin: start_read_threads: calloc failed.");
663                 return;
664         }
665
666         read_threads_num = 0;
667         for (int i = 0; i < num; i++)
668         {
669                 if (pthread_create (read_threads + read_threads_num, NULL,
670                                         plugin_read_thread, NULL) == 0)
671                 {
672 #if defined(HAVE_PTHREAD_SETNAME_NP) || defined(HAVE_PTHREAD_SET_NAME_NP)
673                         char thread_name[32];
674                         ssnprintf(thread_name, sizeof (thread_name),
675                                         "plugin reader#%d", i);
676 # if defined(HAVE_PTHREAD_SETNAME_NP)
677                         pthread_setname_np (*(read_threads + read_threads_num),
678                                 thread_name);
679 # elif defined(HAVE_PTHREAD_SET_NAME_NP)
680                         pthread_set_name_np (*(read_threads + read_threads_num),
681                                 thread_name);
682 # endif
683 #endif
684                         read_threads_num++;
685                 }
686                 else
687                 {
688                         ERROR ("plugin: start_read_threads: pthread_create failed.");
689                         return;
690                 }
691         } /* for (i) */
692 } /* void start_read_threads */
693
694 static void stop_read_threads (void)
695 {
696         if (read_threads == NULL)
697                 return;
698
699         INFO ("collectd: Stopping %i read threads.", read_threads_num);
700
701         pthread_mutex_lock (&read_lock);
702         read_loop = 0;
703         DEBUG ("plugin: stop_read_threads: Signalling `read_cond'");
704         pthread_cond_broadcast (&read_cond);
705         pthread_mutex_unlock (&read_lock);
706
707         for (int i = 0; i < read_threads_num; i++)
708         {
709                 if (pthread_join (read_threads[i], NULL) != 0)
710                 {
711                         ERROR ("plugin: stop_read_threads: pthread_join failed.");
712                 }
713                 read_threads[i] = (pthread_t) 0;
714         }
715         sfree (read_threads);
716         read_threads_num = 0;
717 } /* void stop_read_threads */
718
719 static void plugin_value_list_free (value_list_t *vl) /* {{{ */
720 {
721         if (vl == NULL)
722                 return;
723
724         meta_data_destroy (vl->meta);
725         sfree (vl->values);
726         sfree (vl);
727 } /* }}} void plugin_value_list_free */
728
729 static value_list_t *plugin_value_list_clone (value_list_t const *vl_orig) /* {{{ */
730 {
731         value_list_t *vl;
732
733         if (vl_orig == NULL)
734                 return (NULL);
735
736         vl = malloc (sizeof (*vl));
737         if (vl == NULL)
738                 return (NULL);
739         memcpy (vl, vl_orig, sizeof (*vl));
740
741         if (vl->host[0] == 0)
742                 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
743
744         vl->values = calloc (vl_orig->values_len, sizeof (*vl->values));
745         if (vl->values == NULL)
746         {
747                 plugin_value_list_free (vl);
748                 return (NULL);
749         }
750         memcpy (vl->values, vl_orig->values,
751                         vl_orig->values_len * sizeof (*vl->values));
752
753         vl->meta = meta_data_clone (vl->meta);
754         if ((vl_orig->meta != NULL) && (vl->meta == NULL))
755         {
756                 plugin_value_list_free (vl);
757                 return (NULL);
758         }
759
760         if (vl->time == 0)
761                 vl->time = cdtime ();
762
763         /* Fill in the interval from the thread context, if it is zero. */
764         if (vl->interval == 0)
765         {
766                 plugin_ctx_t ctx = plugin_get_ctx ();
767
768                 if (ctx.interval != 0)
769                         vl->interval = ctx.interval;
770                 else
771                 {
772                         char name[6 * DATA_MAX_NAME_LEN];
773                         FORMAT_VL (name, sizeof (name), vl);
774                         ERROR ("plugin_value_list_clone: Unable to determine "
775                                         "interval from context for "
776                                         "value list \"%s\". "
777                                         "This indicates a broken plugin. "
778                                         "Please report this problem to the "
779                                         "collectd mailing list or at "
780                                         "<http://collectd.org/bugs/>.", name);
781                         vl->interval = cf_get_default_interval ();
782                 }
783         }
784
785         return (vl);
786 } /* }}} value_list_t *plugin_value_list_clone */
787
788 static int plugin_write_enqueue (value_list_t const *vl) /* {{{ */
789 {
790         write_queue_t *q;
791
792         q = malloc (sizeof (*q));
793         if (q == NULL)
794                 return (ENOMEM);
795         q->next = NULL;
796
797         q->vl = plugin_value_list_clone (vl);
798         if (q->vl == NULL)
799         {
800                 sfree (q);
801                 return (ENOMEM);
802         }
803
804         /* Store context of caller (read plugin); otherwise, it would not be
805          * available to the write plugins when actually dispatching the
806          * value-list later on. */
807         q->ctx = plugin_get_ctx ();
808
809         pthread_mutex_lock (&write_lock);
810
811         if (write_queue_tail == NULL)
812         {
813                 write_queue_head = q;
814                 write_queue_tail = q;
815                 write_queue_length = 1;
816         }
817         else
818         {
819                 write_queue_tail->next = q;
820                 write_queue_tail = q;
821                 write_queue_length += 1;
822         }
823
824         pthread_cond_signal (&write_cond);
825         pthread_mutex_unlock (&write_lock);
826
827         return (0);
828 } /* }}} int plugin_write_enqueue */
829
830 static value_list_t *plugin_write_dequeue (void) /* {{{ */
831 {
832         write_queue_t *q;
833         value_list_t *vl;
834
835         pthread_mutex_lock (&write_lock);
836
837         while (write_loop && (write_queue_head == NULL))
838                 pthread_cond_wait (&write_cond, &write_lock);
839
840         if (write_queue_head == NULL)
841         {
842                 pthread_mutex_unlock (&write_lock);
843                 return (NULL);
844         }
845
846         q = write_queue_head;
847         write_queue_head = q->next;
848         write_queue_length -= 1;
849         if (write_queue_head == NULL) {
850                 write_queue_tail = NULL;
851                 assert(0 == write_queue_length);
852                 }
853
854         pthread_mutex_unlock (&write_lock);
855
856         (void) plugin_set_ctx (q->ctx);
857
858         vl = q->vl;
859         sfree (q);
860         return (vl);
861 } /* }}} value_list_t *plugin_write_dequeue */
862
863 static void *plugin_write_thread (void __attribute__((unused)) *args) /* {{{ */
864 {
865         while (write_loop)
866         {
867                 value_list_t *vl = plugin_write_dequeue ();
868                 if (vl == NULL)
869                         continue;
870
871                 plugin_dispatch_values_internal (vl);
872
873                 plugin_value_list_free (vl);
874         }
875
876         pthread_exit (NULL);
877         return ((void *) 0);
878 } /* }}} void *plugin_write_thread */
879
880 static void start_write_threads (size_t num) /* {{{ */
881 {
882         if (write_threads != NULL)
883                 return;
884
885         write_threads = (pthread_t *) calloc (num, sizeof (pthread_t));
886         if (write_threads == NULL)
887         {
888                 ERROR ("plugin: start_write_threads: calloc failed.");
889                 return;
890         }
891
892         write_threads_num = 0;
893         for (size_t i = 0; i < num; i++)
894         {
895                 int status;
896
897                 status = pthread_create (write_threads + write_threads_num,
898                                 /* attr = */ NULL,
899                                 plugin_write_thread,
900                                 /* arg = */ NULL);
901                 if (status != 0)
902                 {
903                         char errbuf[1024];
904                         ERROR ("plugin: start_write_threads: pthread_create failed "
905                                         "with status %i (%s).", status,
906                                         sstrerror (status, errbuf, sizeof (errbuf)));
907                         return;
908                 } else {
909 #if defined(HAVE_PTHREAD_SETNAME_NP) || defined(HAVE_PTHREAD_SET_NAME_NP)
910                         char thread_name[16];
911                         sstrncpy (thread_name, "plugin writer", sizeof(thread_name));
912 # if defined(HAVE_PTHREAD_SETNAME_NP)
913                         pthread_setname_np (*(write_threads + write_threads_num),
914                                 thread_name);
915 # elif defined(HAVE_PTHREAD_SET_NAME_NP)
916                         pthread_set_name_np (*(write_threads + write_threads_num),
917                                 thread_name);
918 # endif
919 #endif
920                         write_threads_num++;
921                 }
922         } /* for (i) */
923 } /* }}} void start_write_threads */
924
925 static void stop_write_threads (void) /* {{{ */
926 {
927         write_queue_t *q;
928         size_t i;
929
930         if (write_threads == NULL)
931                 return;
932
933         INFO ("collectd: Stopping %zu write threads.", write_threads_num);
934
935         pthread_mutex_lock (&write_lock);
936         write_loop = 0;
937         DEBUG ("plugin: stop_write_threads: Signalling `write_cond'");
938         pthread_cond_broadcast (&write_cond);
939         pthread_mutex_unlock (&write_lock);
940
941         for (i = 0; i < write_threads_num; i++)
942         {
943                 if (pthread_join (write_threads[i], NULL) != 0)
944                 {
945                         ERROR ("plugin: stop_write_threads: pthread_join failed.");
946                 }
947                 write_threads[i] = (pthread_t) 0;
948         }
949         sfree (write_threads);
950         write_threads_num = 0;
951
952         pthread_mutex_lock (&write_lock);
953         i = 0;
954         for (q = write_queue_head; q != NULL; )
955         {
956                 write_queue_t *q1 = q;
957                 plugin_value_list_free (q->vl);
958                 q = q->next;
959                 sfree (q1);
960                 i++;
961         }
962         write_queue_head = NULL;
963         write_queue_tail = NULL;
964         write_queue_length = 0;
965         pthread_mutex_unlock (&write_lock);
966
967         if (i > 0)
968         {
969                 WARNING ("plugin: %zu value list%s left after shutting down "
970                                 "the write threads.",
971                                 i, (i == 1) ? " was" : "s were");
972         }
973 } /* }}} void stop_write_threads */
974
975 /*
976  * Public functions
977  */
978 void plugin_set_dir (const char *dir)
979 {
980         sfree (plugindir);
981
982         if (dir == NULL)
983         {
984                 plugindir = NULL;
985                 return;
986         }
987
988         plugindir = strdup (dir);
989         if (plugindir == NULL)
990                 ERROR ("plugin_set_dir: strdup(\"%s\") failed", dir);
991 }
992
993 static _Bool plugin_is_loaded (char const *name)
994 {
995         int status;
996
997         if (plugins_loaded == NULL)
998                 plugins_loaded = c_avl_create ((int (*) (const void *, const void *)) strcasecmp);
999         assert (plugins_loaded != NULL);
1000
1001         status = c_avl_get (plugins_loaded, name, /* ret_value = */ NULL);
1002         return (status == 0);
1003 }
1004
1005 static int plugin_mark_loaded (char const *name)
1006 {
1007         char *name_copy;
1008         int status;
1009
1010         name_copy = strdup (name);
1011         if (name_copy == NULL)
1012                 return (ENOMEM);
1013
1014         status = c_avl_insert (plugins_loaded,
1015                         /* key = */ name_copy, /* value = */ NULL);
1016         return (status);
1017 }
1018
1019 static void plugin_free_loaded (void)
1020 {
1021         void *key;
1022         void *value;
1023
1024         if (plugins_loaded == NULL)
1025                 return;
1026
1027         while (c_avl_pick (plugins_loaded, &key, &value) == 0)
1028         {
1029                 sfree (key);
1030                 assert (value == NULL);
1031         }
1032
1033         c_avl_destroy (plugins_loaded);
1034         plugins_loaded = NULL;
1035 }
1036
1037 #define BUFSIZE 512
1038 int plugin_load (char const *plugin_name, uint32_t flags)
1039 {
1040         DIR  *dh;
1041         const char *dir;
1042         char  filename[BUFSIZE] = "";
1043         char  typename[BUFSIZE];
1044         int   ret;
1045         struct stat    statbuf;
1046         struct dirent *de;
1047         int status;
1048
1049         if (plugin_name == NULL)
1050                 return (EINVAL);
1051
1052         /* Check if plugin is already loaded and don't do anything in this
1053          * case. */
1054         if (plugin_is_loaded (plugin_name))
1055                 return (0);
1056
1057         dir = plugin_get_dir ();
1058         ret = 1;
1059
1060         /*
1061          * XXX: Magic at work:
1062          *
1063          * Some of the language bindings, for example the Python and Perl
1064          * plugins, need to be able to export symbols to the scripts they run.
1065          * For this to happen, the "Globals" flag needs to be set.
1066          * Unfortunately, this technical detail is hard to explain to the
1067          * average user and she shouldn't have to worry about this, ideally.
1068          * So in order to save everyone's sanity use a different default for a
1069          * handful of special plugins. --octo
1070          */
1071         if ((strcasecmp ("perl", plugin_name) == 0)
1072                         || (strcasecmp ("python", plugin_name) == 0))
1073                 flags |= PLUGIN_FLAGS_GLOBAL;
1074
1075         /* `cpu' should not match `cpufreq'. To solve this we add `.so' to the
1076          * type when matching the filename */
1077         status = ssnprintf (typename, sizeof (typename), "%s.so", plugin_name);
1078         if ((status < 0) || ((size_t) status >= sizeof (typename)))
1079         {
1080                 WARNING ("plugin_load: Filename too long: \"%s.so\"", plugin_name);
1081                 return (-1);
1082         }
1083
1084         if ((dh = opendir (dir)) == NULL)
1085         {
1086                 char errbuf[1024];
1087                 ERROR ("plugin_load: opendir (%s) failed: %s", dir,
1088                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1089                 return (-1);
1090         }
1091
1092         while ((de = readdir (dh)) != NULL)
1093         {
1094                 if (strcasecmp (de->d_name, typename))
1095                         continue;
1096
1097                 status = ssnprintf (filename, sizeof (filename),
1098                                 "%s/%s", dir, de->d_name);
1099                 if ((status < 0) || ((size_t) status >= sizeof (filename)))
1100                 {
1101                         WARNING ("plugin_load: Filename too long: \"%s/%s\"",
1102                                         dir, de->d_name);
1103                         continue;
1104                 }
1105
1106                 if (lstat (filename, &statbuf) == -1)
1107                 {
1108                         char errbuf[1024];
1109                         WARNING ("plugin_load: stat (\"%s\") failed: %s",
1110                                         filename,
1111                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1112                         continue;
1113                 }
1114                 else if (!S_ISREG (statbuf.st_mode))
1115                 {
1116                         /* don't follow symlinks */
1117                         WARNING ("plugin_load: %s is not a regular file.",
1118                                         filename);
1119                         continue;
1120                 }
1121
1122                 status = plugin_load_file (filename, flags);
1123                 if (status == 0)
1124                 {
1125                         /* success */
1126                         plugin_mark_loaded (plugin_name);
1127                         ret = 0;
1128                         INFO ("plugin_load: plugin \"%s\" successfully loaded.", plugin_name);
1129                         break;
1130                 }
1131                 else
1132                 {
1133                         ERROR ("plugin_load: Load plugin \"%s\" failed with "
1134                                         "status %i.", plugin_name, status);
1135                 }
1136         }
1137
1138         closedir (dh);
1139
1140         if (filename[0] == 0)
1141                 ERROR ("plugin_load: Could not find plugin \"%s\" in %s",
1142                                 plugin_name, dir);
1143
1144         return (ret);
1145 }
1146
1147 /*
1148  * The `register_*' functions follow
1149  */
1150 int plugin_register_config (const char *name,
1151                 int (*callback) (const char *key, const char *val),
1152                 const char **keys, int keys_num)
1153 {
1154         cf_register (name, callback, keys, keys_num);
1155         return (0);
1156 } /* int plugin_register_config */
1157
1158 int plugin_register_complex_config (const char *type,
1159                 int (*callback) (oconfig_item_t *))
1160 {
1161         return (cf_register_complex (type, callback));
1162 } /* int plugin_register_complex_config */
1163
1164 int plugin_register_init (const char *name,
1165                 int (*callback) (void))
1166 {
1167         return (create_register_callback (&list_init, name, (void *) callback,
1168                                 /* user_data = */ NULL));
1169 } /* plugin_register_init */
1170
1171 static int plugin_compare_read_func (const void *arg0, const void *arg1)
1172 {
1173         const read_func_t *rf0;
1174         const read_func_t *rf1;
1175
1176         rf0 = arg0;
1177         rf1 = arg1;
1178
1179         if (rf0->rf_next_read < rf1->rf_next_read)
1180                 return (-1);
1181         else if (rf0->rf_next_read > rf1->rf_next_read)
1182                 return (1);
1183         else
1184                 return (0);
1185 } /* int plugin_compare_read_func */
1186
1187 /* Add a read function to both, the heap and a linked list. The linked list if
1188  * used to look-up read functions, especially for the remove function. The heap
1189  * is used to determine which plugin to read next. */
1190 static int plugin_insert_read (read_func_t *rf)
1191 {
1192         int status;
1193         llentry_t *le;
1194
1195         rf->rf_next_read = cdtime ();
1196         rf->rf_effective_interval = rf->rf_interval;
1197
1198         pthread_mutex_lock (&read_lock);
1199
1200         if (read_list == NULL)
1201         {
1202                 read_list = llist_create ();
1203                 if (read_list == NULL)
1204                 {
1205                         pthread_mutex_unlock (&read_lock);
1206                         ERROR ("plugin_insert_read: read_list failed.");
1207                         return (-1);
1208                 }
1209         }
1210
1211         if (read_heap == NULL)
1212         {
1213                 read_heap = c_heap_create (plugin_compare_read_func);
1214                 if (read_heap == NULL)
1215                 {
1216                         pthread_mutex_unlock (&read_lock);
1217                         ERROR ("plugin_insert_read: c_heap_create failed.");
1218                         return (-1);
1219                 }
1220         }
1221
1222         le = llist_search (read_list, rf->rf_name);
1223         if (le != NULL)
1224         {
1225                 pthread_mutex_unlock (&read_lock);
1226                 WARNING ("The read function \"%s\" is already registered. "
1227                                 "Check for duplicate \"LoadPlugin\" lines "
1228                                 "in your configuration!",
1229                                 rf->rf_name);
1230                 return (EINVAL);
1231         }
1232
1233         le = llentry_create (rf->rf_name, rf);
1234         if (le == NULL)
1235         {
1236                 pthread_mutex_unlock (&read_lock);
1237                 ERROR ("plugin_insert_read: llentry_create failed.");
1238                 return (-1);
1239         }
1240
1241         status = c_heap_insert (read_heap, rf);
1242         if (status != 0)
1243         {
1244                 pthread_mutex_unlock (&read_lock);
1245                 ERROR ("plugin_insert_read: c_heap_insert failed.");
1246                 llentry_destroy (le);
1247                 return (-1);
1248         }
1249
1250         /* This does not fail. */
1251         llist_append (read_list, le);
1252
1253         /* Wake up all the read threads. */
1254         pthread_cond_broadcast (&read_cond);
1255         pthread_mutex_unlock (&read_lock);
1256         return (0);
1257 } /* int plugin_insert_read */
1258
1259 int plugin_register_read (const char *name,
1260                 int (*callback) (void))
1261 {
1262         read_func_t *rf;
1263         int status;
1264
1265         rf = calloc (1, sizeof (*rf));
1266         if (rf == NULL)
1267         {
1268                 ERROR ("plugin_register_read: calloc failed.");
1269                 return (ENOMEM);
1270         }
1271
1272         rf->rf_callback = (void *) callback;
1273         rf->rf_udata.data = NULL;
1274         rf->rf_udata.free_func = NULL;
1275         rf->rf_ctx = plugin_get_ctx ();
1276         rf->rf_group[0] = '\0';
1277         rf->rf_name = strdup (name);
1278         rf->rf_type = RF_SIMPLE;
1279         rf->rf_interval = plugin_get_interval ();
1280
1281         status = plugin_insert_read (rf);
1282         if (status != 0) {
1283                 sfree (rf->rf_name);
1284                 sfree (rf);
1285         }
1286
1287         return (status);
1288 } /* int plugin_register_read */
1289
1290 int plugin_register_complex_read (const char *group, const char *name,
1291                 plugin_read_cb callback,
1292                 cdtime_t interval,
1293                 user_data_t const *user_data)
1294 {
1295         read_func_t *rf;
1296         int status;
1297
1298         rf = calloc (1,sizeof (*rf));
1299         if (rf == NULL)
1300         {
1301                 ERROR ("plugin_register_complex_read: calloc failed.");
1302                 return (ENOMEM);
1303         }
1304
1305         rf->rf_callback = (void *) callback;
1306         if (group != NULL)
1307                 sstrncpy (rf->rf_group, group, sizeof (rf->rf_group));
1308         else
1309                 rf->rf_group[0] = '\0';
1310         rf->rf_name = strdup (name);
1311         rf->rf_type = RF_COMPLEX;
1312         rf->rf_interval = (interval != 0) ? interval : plugin_get_interval ();
1313
1314         /* Set user data */
1315         if (user_data == NULL)
1316         {
1317                 rf->rf_udata.data = NULL;
1318                 rf->rf_udata.free_func = NULL;
1319         }
1320         else
1321         {
1322                 rf->rf_udata = *user_data;
1323         }
1324
1325         rf->rf_ctx = plugin_get_ctx ();
1326
1327         status = plugin_insert_read (rf);
1328         if (status != 0) {
1329                 sfree (rf->rf_name);
1330                 sfree (rf);
1331         }
1332
1333         return (status);
1334 } /* int plugin_register_complex_read */
1335
1336 int plugin_register_write (const char *name,
1337                 plugin_write_cb callback, user_data_t const *ud)
1338 {
1339         return (create_register_callback (&list_write, name,
1340                                 (void *) callback, ud));
1341 } /* int plugin_register_write */
1342
1343 static int plugin_flush_timeout_callback (user_data_t *ud)
1344 {
1345         flush_callback_t *cb = ud->data;
1346
1347         return plugin_flush (cb->name, cb->timeout, /* identifier = */ NULL);
1348 } /* static int plugin_flush_callback */
1349
1350 static void plugin_flush_timeout_callback_free (void *data)
1351 {
1352         flush_callback_t *cb = data;
1353
1354         if (cb == NULL) return;
1355
1356         sfree (cb->name);
1357         sfree (cb);
1358 } /* static void plugin_flush_callback_free */
1359
1360 static char *plugin_flush_callback_name (const char *name)
1361 {
1362         const char *flush_prefix = "flush/";
1363         size_t prefix_size;
1364         char *flush_name;
1365         size_t name_size;
1366
1367         prefix_size = strlen(flush_prefix);
1368         name_size = strlen(name);
1369
1370         flush_name = malloc (name_size + prefix_size + 1);
1371         if (flush_name == NULL)
1372         {
1373                 ERROR ("plugin_flush_callback_name: malloc failed.");
1374                 return (NULL);
1375         }
1376
1377         sstrncpy (flush_name, flush_prefix, prefix_size + 1);
1378         sstrncpy (flush_name + prefix_size, name, name_size + 1);
1379
1380         return flush_name;
1381 } /* static char *plugin_flush_callback_name */
1382
1383 int plugin_register_flush (const char *name,
1384                 plugin_flush_cb callback, user_data_t const *ud)
1385 {
1386         int status;
1387         plugin_ctx_t ctx = plugin_get_ctx ();
1388
1389         status = create_register_callback (&list_flush, name,
1390                 (void *) callback, ud);
1391         if (status != 0)
1392                 return status;
1393
1394         if (ctx.flush_interval != 0)
1395         {
1396                 char *flush_name;
1397                 flush_callback_t *cb;
1398
1399                 flush_name = plugin_flush_callback_name (name);
1400                 if (flush_name == NULL)
1401                         return (-1);
1402
1403                 cb = malloc(sizeof (*cb));
1404                 if (cb == NULL)
1405                 {
1406                         ERROR ("plugin_register_flush: malloc failed.");
1407                         sfree (flush_name);
1408                         return (-1);
1409                 }
1410
1411                 cb->name = strdup (name);
1412                 if (cb->name == NULL)
1413                 {
1414                         ERROR ("plugin_register_flush: strdup failed.");
1415                         sfree (cb);
1416                         sfree (flush_name);
1417                         return (-1);
1418                 }
1419                 cb->timeout = ctx.flush_timeout;
1420
1421                 status = plugin_register_complex_read (
1422                         /* group     = */ "flush",
1423                         /* name      = */ flush_name,
1424                         /* callback  = */ plugin_flush_timeout_callback,
1425                         /* interval  = */ ctx.flush_interval,
1426                         /* user data = */ &(user_data_t) {
1427                                 .data = cb,
1428                                 .free_func = plugin_flush_timeout_callback_free,
1429                         });
1430
1431                 sfree (flush_name);
1432                 if (status != 0)
1433                 {
1434                         sfree (cb->name);
1435                         sfree (cb);
1436                         return status;
1437                 }
1438         }
1439
1440         return 0;
1441 } /* int plugin_register_flush */
1442
1443 int plugin_register_missing (const char *name,
1444                 plugin_missing_cb callback, user_data_t const *ud)
1445 {
1446         return (create_register_callback (&list_missing, name,
1447                                 (void *) callback, ud));
1448 } /* int plugin_register_missing */
1449
1450 int plugin_register_shutdown (const char *name,
1451                 int (*callback) (void))
1452 {
1453         return (create_register_callback (&list_shutdown, name,
1454                                 (void *) callback, /* user_data = */ NULL));
1455 } /* int plugin_register_shutdown */
1456
1457 static void plugin_free_data_sets (void)
1458 {
1459         void *key;
1460         void *value;
1461
1462         if (data_sets == NULL)
1463                 return;
1464
1465         while (c_avl_pick (data_sets, &key, &value) == 0)
1466         {
1467                 data_set_t *ds = value;
1468                 /* key is a pointer to ds->type */
1469
1470                 sfree (ds->ds);
1471                 sfree (ds);
1472         }
1473
1474         c_avl_destroy (data_sets);
1475         data_sets = NULL;
1476 } /* void plugin_free_data_sets */
1477
1478 int plugin_register_data_set (const data_set_t *ds)
1479 {
1480         data_set_t *ds_copy;
1481
1482         if ((data_sets != NULL)
1483                         && (c_avl_get (data_sets, ds->type, NULL) == 0))
1484         {
1485                 NOTICE ("Replacing DS `%s' with another version.", ds->type);
1486                 plugin_unregister_data_set (ds->type);
1487         }
1488         else if (data_sets == NULL)
1489         {
1490                 data_sets = c_avl_create ((int (*) (const void *, const void *)) strcmp);
1491                 if (data_sets == NULL)
1492                         return (-1);
1493         }
1494
1495         ds_copy = malloc (sizeof (*ds_copy));
1496         if (ds_copy == NULL)
1497                 return (-1);
1498         memcpy(ds_copy, ds, sizeof (data_set_t));
1499
1500         ds_copy->ds = malloc (sizeof (*ds_copy->ds)
1501                         * ds->ds_num);
1502         if (ds_copy->ds == NULL)
1503         {
1504                 sfree (ds_copy);
1505                 return (-1);
1506         }
1507
1508         for (size_t i = 0; i < ds->ds_num; i++)
1509                 memcpy (ds_copy->ds + i, ds->ds + i, sizeof (data_source_t));
1510
1511         return (c_avl_insert (data_sets, (void *) ds_copy->type, (void *) ds_copy));
1512 } /* int plugin_register_data_set */
1513
1514 int plugin_register_log (const char *name,
1515                 plugin_log_cb callback, user_data_t const *ud)
1516 {
1517         return (create_register_callback (&list_log, name,
1518                                 (void *) callback, ud));
1519 } /* int plugin_register_log */
1520
1521 int plugin_register_notification (const char *name,
1522                 plugin_notification_cb callback, user_data_t const *ud)
1523 {
1524         return (create_register_callback (&list_notification, name,
1525                                 (void *) callback, ud));
1526 } /* int plugin_register_log */
1527
1528 int plugin_unregister_config (const char *name)
1529 {
1530         cf_unregister (name);
1531         return (0);
1532 } /* int plugin_unregister_config */
1533
1534 int plugin_unregister_complex_config (const char *name)
1535 {
1536         cf_unregister_complex (name);
1537         return (0);
1538 } /* int plugin_unregister_complex_config */
1539
1540 int plugin_unregister_init (const char *name)
1541 {
1542         return (plugin_unregister (list_init, name));
1543 }
1544
1545 int plugin_unregister_read (const char *name) /* {{{ */
1546 {
1547         llentry_t *le;
1548         read_func_t *rf;
1549
1550         if (name == NULL)
1551                 return (-ENOENT);
1552
1553         pthread_mutex_lock (&read_lock);
1554
1555         if (read_list == NULL)
1556         {
1557                 pthread_mutex_unlock (&read_lock);
1558                 return (-ENOENT);
1559         }
1560
1561         le = llist_search (read_list, name);
1562         if (le == NULL)
1563         {
1564                 pthread_mutex_unlock (&read_lock);
1565                 WARNING ("plugin_unregister_read: No such read function: %s",
1566                                 name);
1567                 return (-ENOENT);
1568         }
1569
1570         llist_remove (read_list, le);
1571
1572         rf = le->value;
1573         assert (rf != NULL);
1574         rf->rf_type = RF_REMOVE;
1575
1576         pthread_mutex_unlock (&read_lock);
1577
1578         llentry_destroy (le);
1579
1580         DEBUG ("plugin_unregister_read: Marked `%s' for removal.", name);
1581
1582         return (0);
1583 } /* }}} int plugin_unregister_read */
1584
1585 void plugin_log_available_writers (void)
1586 {
1587         log_list_callbacks (&list_write, "Available write targets:");
1588 }
1589
1590 static int compare_read_func_group (llentry_t *e, void *ud) /* {{{ */
1591 {
1592         read_func_t *rf    = e->value;
1593         char        *group = ud;
1594
1595         return strcmp (rf->rf_group, (const char *)group);
1596 } /* }}} int compare_read_func_group */
1597
1598 int plugin_unregister_read_group (const char *group) /* {{{ */
1599 {
1600         llentry_t *le;
1601         read_func_t *rf;
1602
1603         int found = 0;
1604
1605         if (group == NULL)
1606                 return (-ENOENT);
1607
1608         pthread_mutex_lock (&read_lock);
1609
1610         if (read_list == NULL)
1611         {
1612                 pthread_mutex_unlock (&read_lock);
1613                 return (-ENOENT);
1614         }
1615
1616         while (42)
1617         {
1618                 le = llist_search_custom (read_list,
1619                                 compare_read_func_group, (void *)group);
1620
1621                 if (le == NULL)
1622                         break;
1623
1624                 ++found;
1625
1626                 llist_remove (read_list, le);
1627
1628                 rf = le->value;
1629                 assert (rf != NULL);
1630                 rf->rf_type = RF_REMOVE;
1631
1632                 llentry_destroy (le);
1633
1634                 DEBUG ("plugin_unregister_read_group: "
1635                                 "Marked `%s' (group `%s') for removal.",
1636                                 rf->rf_name, group);
1637         }
1638
1639         pthread_mutex_unlock (&read_lock);
1640
1641         if (found == 0)
1642         {
1643                 WARNING ("plugin_unregister_read_group: No such "
1644                                 "group of read function: %s", group);
1645                 return (-ENOENT);
1646         }
1647
1648         return (0);
1649 } /* }}} int plugin_unregister_read_group */
1650
1651 int plugin_unregister_write (const char *name)
1652 {
1653         return (plugin_unregister (list_write, name));
1654 }
1655
1656 int plugin_unregister_flush (const char *name)
1657 {
1658         plugin_ctx_t ctx = plugin_get_ctx ();
1659
1660         if (ctx.flush_interval != 0)
1661         {
1662                 char *flush_name;
1663
1664                 flush_name = plugin_flush_callback_name (name);
1665                 if (flush_name != NULL)
1666                 {
1667                         plugin_unregister_read(flush_name);
1668                         sfree (flush_name);
1669                 }
1670         }
1671
1672         return plugin_unregister (list_flush, name);
1673 }
1674
1675 int plugin_unregister_missing (const char *name)
1676 {
1677         return (plugin_unregister (list_missing, name));
1678 }
1679
1680 int plugin_unregister_shutdown (const char *name)
1681 {
1682         return (plugin_unregister (list_shutdown, name));
1683 }
1684
1685 int plugin_unregister_data_set (const char *name)
1686 {
1687         data_set_t *ds;
1688
1689         if (data_sets == NULL)
1690                 return (-1);
1691
1692         if (c_avl_remove (data_sets, name, NULL, (void *) &ds) != 0)
1693                 return (-1);
1694
1695         sfree (ds->ds);
1696         sfree (ds);
1697
1698         return (0);
1699 } /* int plugin_unregister_data_set */
1700
1701 int plugin_unregister_log (const char *name)
1702 {
1703         return (plugin_unregister (list_log, name));
1704 }
1705
1706 int plugin_unregister_notification (const char *name)
1707 {
1708         return (plugin_unregister (list_notification, name));
1709 }
1710
1711 int plugin_init_all (void)
1712 {
1713         char const *chain_name;
1714         llentry_t *le;
1715         int status;
1716         int ret = 0;
1717
1718         /* Init the value cache */
1719         uc_init ();
1720
1721         if (IS_TRUE (global_option_get ("CollectInternalStats")))
1722                 record_statistics = 1;
1723
1724         chain_name = global_option_get ("PreCacheChain");
1725         pre_cache_chain = fc_chain_get_by_name (chain_name);
1726
1727         chain_name = global_option_get ("PostCacheChain");
1728         post_cache_chain = fc_chain_get_by_name (chain_name);
1729
1730         write_limit_high = global_option_get_long ("WriteQueueLimitHigh",
1731                         /* default = */ 0);
1732         if (write_limit_high < 0)
1733         {
1734                 ERROR ("WriteQueueLimitHigh must be positive or zero.");
1735                 write_limit_high = 0;
1736         }
1737
1738         write_limit_low = global_option_get_long ("WriteQueueLimitLow",
1739                         /* default = */ write_limit_high / 2);
1740         if (write_limit_low < 0)
1741         {
1742                 ERROR ("WriteQueueLimitLow must be positive or zero.");
1743                 write_limit_low = write_limit_high / 2;
1744         }
1745         else if (write_limit_low > write_limit_high)
1746         {
1747                 ERROR ("WriteQueueLimitLow must not be larger than "
1748                                 "WriteQueueLimitHigh.");
1749                 write_limit_low = write_limit_high;
1750         }
1751
1752         write_threads_num = global_option_get_long ("WriteThreads",
1753                         /* default = */ 5);
1754         if (write_threads_num < 1)
1755         {
1756                 ERROR ("WriteThreads must be positive.");
1757                 write_threads_num = 5;
1758         }
1759
1760         if ((list_init == NULL) && (read_heap == NULL))
1761                 return ret;
1762
1763         /* Calling all init callbacks before checking if read callbacks
1764          * are available allows the init callbacks to register the read
1765          * callback. */
1766         le = llist_head (list_init);
1767         while (le != NULL)
1768         {
1769                 callback_func_t *cf;
1770                 plugin_init_cb callback;
1771                 plugin_ctx_t old_ctx;
1772
1773                 cf = le->value;
1774                 old_ctx = plugin_set_ctx (cf->cf_ctx);
1775                 callback = cf->cf_callback;
1776                 status = (*callback) ();
1777                 plugin_set_ctx (old_ctx);
1778
1779                 if (status != 0)
1780                 {
1781                         ERROR ("Initialization of plugin `%s' "
1782                                         "failed with status %i. "
1783                                         "Plugin will be unloaded.",
1784                                         le->key, status);
1785                         /* Plugins that register read callbacks from the init
1786                          * callback should take care of appropriate error
1787                          * handling themselves. */
1788                         /* FIXME: Unload _all_ functions */
1789                         plugin_unregister_read (le->key);
1790                         ret = -1;
1791                 }
1792
1793                 le = le->next;
1794         }
1795
1796         start_write_threads ((size_t) write_threads_num);
1797
1798         max_read_interval = global_option_get_time ("MaxReadInterval",
1799                         DEFAULT_MAX_READ_INTERVAL);
1800
1801         /* Start read-threads */
1802         if (read_heap != NULL)
1803         {
1804                 const char *rt;
1805                 int num;
1806
1807                 rt = global_option_get ("ReadThreads");
1808                 num = atoi (rt);
1809                 if (num != -1)
1810                         start_read_threads ((num > 0) ? num : 5);
1811         }
1812         return ret;
1813 } /* void plugin_init_all */
1814
1815 /* TODO: Rename this function. */
1816 void plugin_read_all (void)
1817 {
1818         if(record_statistics) {
1819                 plugin_update_internal_statistics ();
1820         }
1821         uc_check_timeout ();
1822
1823         return;
1824 } /* void plugin_read_all */
1825
1826 /* Read function called when the `-T' command line argument is given. */
1827 int plugin_read_all_once (void)
1828 {
1829         int status;
1830         int return_status = 0;
1831
1832         if (read_heap == NULL)
1833         {
1834                 NOTICE ("No read-functions are registered.");
1835                 return (0);
1836         }
1837
1838         while (42)
1839         {
1840                 read_func_t *rf;
1841                 plugin_ctx_t old_ctx;
1842
1843                 rf = c_heap_get_root (read_heap);
1844                 if (rf == NULL)
1845                         break;
1846
1847                 old_ctx = plugin_set_ctx (rf->rf_ctx);
1848
1849                 if (rf->rf_type == RF_SIMPLE)
1850                 {
1851                         int (*callback) (void);
1852
1853                         callback = rf->rf_callback;
1854                         status = (*callback) ();
1855                 }
1856                 else
1857                 {
1858                         plugin_read_cb callback;
1859
1860                         callback = rf->rf_callback;
1861                         status = (*callback) (&rf->rf_udata);
1862                 }
1863
1864                 plugin_set_ctx (old_ctx);
1865
1866                 if (status != 0)
1867                 {
1868                         NOTICE ("read-function of plugin `%s' failed.",
1869                                         rf->rf_name);
1870                         return_status = -1;
1871                 }
1872
1873                 sfree (rf->rf_name);
1874                 destroy_callback ((void *) rf);
1875         }
1876
1877         return (return_status);
1878 } /* int plugin_read_all_once */
1879
1880 int plugin_write (const char *plugin, /* {{{ */
1881                 const data_set_t *ds, const value_list_t *vl)
1882 {
1883   llentry_t *le;
1884   int status;
1885
1886   if (vl == NULL)
1887     return (EINVAL);
1888
1889   if (list_write == NULL)
1890     return (ENOENT);
1891
1892   if (ds == NULL)
1893   {
1894     ds = plugin_get_ds (vl->type);
1895     if (ds == NULL)
1896     {
1897       ERROR ("plugin_write: Unable to lookup type `%s'.", vl->type);
1898       return (ENOENT);
1899     }
1900   }
1901
1902   if (plugin == NULL)
1903   {
1904     int success = 0;
1905     int failure = 0;
1906
1907     le = llist_head (list_write);
1908     while (le != NULL)
1909     {
1910       callback_func_t *cf = le->value;
1911       plugin_write_cb callback;
1912
1913       /* do not switch plugin context; rather keep the context (interval)
1914        * information of the calling read plugin */
1915
1916       DEBUG ("plugin: plugin_write: Writing values via %s.", le->key);
1917       callback = cf->cf_callback;
1918       status = (*callback) (ds, vl, &cf->cf_udata);
1919       if (status != 0)
1920         failure++;
1921       else
1922         success++;
1923
1924       le = le->next;
1925     }
1926
1927     if ((success == 0) && (failure != 0))
1928       status = -1;
1929     else
1930       status = 0;
1931   }
1932   else /* plugin != NULL */
1933   {
1934     callback_func_t *cf;
1935     plugin_write_cb callback;
1936
1937     le = llist_head (list_write);
1938     while (le != NULL)
1939     {
1940       if (strcasecmp (plugin, le->key) == 0)
1941         break;
1942
1943       le = le->next;
1944     }
1945
1946     if (le == NULL)
1947       return (ENOENT);
1948
1949     cf = le->value;
1950
1951     /* do not switch plugin context; rather keep the context (interval)
1952      * information of the calling read plugin */
1953
1954     DEBUG ("plugin: plugin_write: Writing values via %s.", le->key);
1955     callback = cf->cf_callback;
1956     status = (*callback) (ds, vl, &cf->cf_udata);
1957   }
1958
1959   return (status);
1960 } /* }}} int plugin_write */
1961
1962 int plugin_flush (const char *plugin, cdtime_t timeout, const char *identifier)
1963 {
1964   llentry_t *le;
1965
1966   if (list_flush == NULL)
1967     return (0);
1968
1969   le = llist_head (list_flush);
1970   while (le != NULL)
1971   {
1972     callback_func_t *cf;
1973     plugin_flush_cb callback;
1974     plugin_ctx_t old_ctx;
1975
1976     if ((plugin != NULL)
1977         && (strcmp (plugin, le->key) != 0))
1978     {
1979       le = le->next;
1980       continue;
1981     }
1982
1983     cf = le->value;
1984     old_ctx = plugin_set_ctx (cf->cf_ctx);
1985     callback = cf->cf_callback;
1986
1987     (*callback) (timeout, identifier, &cf->cf_udata);
1988
1989     plugin_set_ctx (old_ctx);
1990
1991     le = le->next;
1992   }
1993   return (0);
1994 } /* int plugin_flush */
1995
1996 int plugin_shutdown_all (void)
1997 {
1998         llentry_t *le;
1999         int ret = 0;  // Assume success.
2000
2001         destroy_all_callbacks (&list_init);
2002
2003         stop_read_threads ();
2004
2005         pthread_mutex_lock (&read_lock);
2006         llist_destroy (read_list);
2007         read_list = NULL;
2008         pthread_mutex_unlock (&read_lock);
2009
2010         destroy_read_heap ();
2011
2012         /* blocks until all write threads have shut down. */
2013         stop_write_threads ();
2014
2015         /* ask all plugins to write out the state they kept. */
2016         plugin_flush (/* plugin = */ NULL,
2017                         /* timeout = */ 0,
2018                         /* identifier = */ NULL);
2019
2020         le = NULL;
2021         if (list_shutdown != NULL)
2022                 le = llist_head (list_shutdown);
2023
2024         while (le != NULL)
2025         {
2026                 callback_func_t *cf;
2027                 plugin_shutdown_cb callback;
2028                 plugin_ctx_t old_ctx;
2029
2030                 cf = le->value;
2031                 old_ctx = plugin_set_ctx (cf->cf_ctx);
2032                 callback = cf->cf_callback;
2033
2034                 /* Advance the pointer before calling the callback allows
2035                  * shutdown functions to unregister themselves. If done the
2036                  * other way around the memory `le' points to will be freed
2037                  * after callback returns. */
2038                 le = le->next;
2039
2040                 if ((*callback) () != 0)
2041                         ret = -1;
2042
2043                 plugin_set_ctx (old_ctx);
2044         }
2045
2046         /* Write plugins which use the `user_data' pointer usually need the
2047          * same data available to the flush callback. If this is the case, set
2048          * the free_function to NULL when registering the flush callback and to
2049          * the real free function when registering the write callback. This way
2050          * the data isn't freed twice. */
2051         destroy_all_callbacks (&list_flush);
2052         destroy_all_callbacks (&list_missing);
2053         destroy_all_callbacks (&list_write);
2054
2055         destroy_all_callbacks (&list_notification);
2056         destroy_all_callbacks (&list_shutdown);
2057         destroy_all_callbacks (&list_log);
2058
2059         plugin_free_loaded ();
2060         plugin_free_data_sets ();
2061         return (ret);
2062 } /* void plugin_shutdown_all */
2063
2064 int plugin_dispatch_missing (const value_list_t *vl) /* {{{ */
2065 {
2066   llentry_t *le;
2067
2068   if (list_missing == NULL)
2069     return (0);
2070
2071   le = llist_head (list_missing);
2072   while (le != NULL)
2073   {
2074     callback_func_t *cf;
2075     plugin_missing_cb callback;
2076     plugin_ctx_t old_ctx;
2077     int status;
2078
2079     cf = le->value;
2080     old_ctx = plugin_set_ctx (cf->cf_ctx);
2081     callback = cf->cf_callback;
2082
2083     status = (*callback) (vl, &cf->cf_udata);
2084     plugin_set_ctx (old_ctx);
2085     if (status != 0)
2086     {
2087       if (status < 0)
2088       {
2089         ERROR ("plugin_dispatch_missing: Callback function \"%s\" "
2090             "failed with status %i.",
2091             le->key, status);
2092         return (status);
2093       }
2094       else
2095       {
2096         return (0);
2097       }
2098     }
2099
2100     le = le->next;
2101   }
2102   return (0);
2103 } /* int }}} plugin_dispatch_missing */
2104
2105 static int plugin_dispatch_values_internal (value_list_t *vl)
2106 {
2107         int status;
2108         static c_complain_t no_write_complaint = C_COMPLAIN_INIT_STATIC;
2109
2110         data_set_t *ds;
2111
2112         _Bool free_meta_data = 0;
2113
2114         assert (vl != NULL);
2115
2116         /* These fields are initialized by plugin_value_list_clone() if needed: */
2117         assert (vl->host[0] != 0);
2118         assert (vl->time != 0); /* The time is determined at _enqueue_ time. */
2119         assert (vl->interval != 0);
2120
2121         if (vl->type[0] == 0 || vl->values == NULL || vl->values_len < 1)
2122         {
2123                 ERROR ("plugin_dispatch_values: Invalid value list "
2124                                 "from plugin %s.", vl->plugin);
2125                 return (-1);
2126         }
2127
2128         /* Free meta data only if the calling function didn't specify any. In
2129          * this case matches and targets may add some and the calling function
2130          * may not expect (and therefore free) that data. */
2131         if (vl->meta == NULL)
2132                 free_meta_data = 1;
2133
2134         if (list_write == NULL)
2135                 c_complain_once (LOG_WARNING, &no_write_complaint,
2136                                 "plugin_dispatch_values: No write callback has been "
2137                                 "registered. Please load at least one output plugin, "
2138                                 "if you want the collected data to be stored.");
2139
2140         if (data_sets == NULL)
2141         {
2142                 ERROR ("plugin_dispatch_values: No data sets registered. "
2143                                 "Could the types database be read? Check "
2144                                 "your `TypesDB' setting!");
2145                 return (-1);
2146         }
2147
2148         if (c_avl_get (data_sets, vl->type, (void *) &ds) != 0)
2149         {
2150                 char ident[6 * DATA_MAX_NAME_LEN];
2151
2152                 FORMAT_VL (ident, sizeof (ident), vl);
2153                 INFO ("plugin_dispatch_values: Dataset not found: %s "
2154                                 "(from \"%s\"), check your types.db!",
2155                                 vl->type, ident);
2156                 return (-1);
2157         }
2158
2159         DEBUG ("plugin_dispatch_values: time = %.3f; interval = %.3f; "
2160                         "host = %s; "
2161                         "plugin = %s; plugin_instance = %s; "
2162                         "type = %s; type_instance = %s;",
2163                         CDTIME_T_TO_DOUBLE (vl->time),
2164                         CDTIME_T_TO_DOUBLE (vl->interval),
2165                         vl->host,
2166                         vl->plugin, vl->plugin_instance,
2167                         vl->type, vl->type_instance);
2168
2169 #if COLLECT_DEBUG
2170         assert (0 == strcmp (ds->type, vl->type));
2171 #else
2172         if (0 != strcmp (ds->type, vl->type))
2173                 WARNING ("plugin_dispatch_values: (ds->type = %s) != (vl->type = %s)",
2174                                 ds->type, vl->type);
2175 #endif
2176
2177 #if COLLECT_DEBUG
2178         assert (ds->ds_num == vl->values_len);
2179 #else
2180         if (ds->ds_num != vl->values_len)
2181         {
2182                 ERROR ("plugin_dispatch_values: ds->type = %s: "
2183                                 "(ds->ds_num = %zu) != "
2184                                 "(vl->values_len = %zu)",
2185                                 ds->type, ds->ds_num, vl->values_len);
2186                 return (-1);
2187         }
2188 #endif
2189
2190         escape_slashes (vl->host, sizeof (vl->host));
2191         escape_slashes (vl->plugin, sizeof (vl->plugin));
2192         escape_slashes (vl->plugin_instance, sizeof (vl->plugin_instance));
2193         escape_slashes (vl->type, sizeof (vl->type));
2194         escape_slashes (vl->type_instance, sizeof (vl->type_instance));
2195
2196         if (pre_cache_chain != NULL)
2197         {
2198                 status = fc_process_chain (ds, vl, pre_cache_chain);
2199                 if (status < 0)
2200                 {
2201                         WARNING ("plugin_dispatch_values: Running the "
2202                                         "pre-cache chain failed with "
2203                                         "status %i (%#x).",
2204                                         status, status);
2205                 }
2206                 else if (status == FC_TARGET_STOP)
2207                         return (0);
2208         }
2209
2210         /* Update the value cache */
2211         uc_update (ds, vl);
2212
2213         if (post_cache_chain != NULL)
2214         {
2215                 status = fc_process_chain (ds, vl, post_cache_chain);
2216                 if (status < 0)
2217                 {
2218                         WARNING ("plugin_dispatch_values: Running the "
2219                                         "post-cache chain failed with "
2220                                         "status %i (%#x).",
2221                                         status, status);
2222                 }
2223         }
2224         else
2225                 fc_default_action (ds, vl);
2226
2227         if ((free_meta_data != 0) && (vl->meta != NULL))
2228         {
2229                 meta_data_destroy (vl->meta);
2230                 vl->meta = NULL;
2231         }
2232
2233         return (0);
2234 } /* int plugin_dispatch_values_internal */
2235
2236 static double get_drop_probability (void) /* {{{ */
2237 {
2238         long pos;
2239         long size;
2240         long wql;
2241
2242         pthread_mutex_lock (&write_lock);
2243         wql = write_queue_length;
2244         pthread_mutex_unlock (&write_lock);
2245
2246         if (wql < write_limit_low)
2247                 return (0.0);
2248         if (wql >= write_limit_high)
2249                 return (1.0);
2250
2251         pos = 1 + wql - write_limit_low;
2252         size = 1 + write_limit_high - write_limit_low;
2253
2254         return (((double) pos) / ((double) size));
2255 } /* }}} double get_drop_probability */
2256
2257 static _Bool check_drop_value (void) /* {{{ */
2258 {
2259         static cdtime_t last_message_time = 0;
2260         static pthread_mutex_t last_message_lock = PTHREAD_MUTEX_INITIALIZER;
2261
2262         double p;
2263         double q;
2264         int status;
2265
2266         if (write_limit_high == 0)
2267                 return (0);
2268
2269         p = get_drop_probability ();
2270         if (p == 0.0)
2271                 return (0);
2272
2273         status = pthread_mutex_trylock (&last_message_lock);
2274         if (status == 0)
2275         {
2276                 cdtime_t now;
2277
2278                 now = cdtime ();
2279                 if ((now - last_message_time) > TIME_T_TO_CDTIME_T (1))
2280                 {
2281                         last_message_time = now;
2282                         ERROR ("plugin_dispatch_values: Low water mark "
2283                                         "reached. Dropping %.0f%% of metrics.",
2284                                         100.0 * p);
2285                 }
2286                 pthread_mutex_unlock (&last_message_lock);
2287         }
2288
2289         if (p == 1.0)
2290                 return (1);
2291
2292         q = cdrand_d ();
2293         if (q > p)
2294                 return (1);
2295         else
2296                 return (0);
2297 } /* }}} _Bool check_drop_value */
2298
2299 int plugin_dispatch_values (value_list_t const *vl)
2300 {
2301         int status;
2302         static pthread_mutex_t statistics_lock = PTHREAD_MUTEX_INITIALIZER;
2303
2304         if (check_drop_value ()) {
2305                 if(record_statistics) {
2306                         pthread_mutex_lock(&statistics_lock);
2307                         stats_values_dropped++;
2308                         pthread_mutex_unlock(&statistics_lock);
2309                 }
2310                 return (0);
2311         }
2312
2313         status = plugin_write_enqueue (vl);
2314         if (status != 0)
2315         {
2316                 char errbuf[1024];
2317                 ERROR ("plugin_dispatch_values: plugin_write_enqueue failed "
2318                                 "with status %i (%s).", status,
2319                                 sstrerror (status, errbuf, sizeof (errbuf)));
2320                 return (status);
2321         }
2322
2323         return (0);
2324 }
2325
2326 __attribute__((sentinel))
2327 int plugin_dispatch_multivalue (value_list_t const *template, /* {{{ */
2328                 _Bool store_percentage, int store_type, ...)
2329 {
2330         value_list_t *vl;
2331         int failed = 0;
2332         gauge_t sum = 0.0;
2333         va_list ap;
2334
2335         assert (template->values_len == 1);
2336
2337         /* Calculate sum for Gauge to calculate percent if needed */
2338         if (DS_TYPE_GAUGE == store_type)        {
2339                 va_start (ap, store_type);
2340                 while (42)
2341                 {
2342                         char const *name;
2343                         gauge_t value;
2344
2345                         name = va_arg (ap, char const *);
2346                         if (name == NULL)
2347                                 break;
2348
2349                         value = va_arg (ap, gauge_t);
2350                         if (!isnan (value))
2351                                 sum += value;
2352                 }
2353                 va_end (ap);
2354         }
2355
2356
2357         vl = plugin_value_list_clone (template);
2358         /* plugin_value_list_clone makes sure vl->time is set to non-zero. */
2359         if (store_percentage)
2360                 sstrncpy (vl->type, "percent", sizeof (vl->type));
2361
2362         va_start (ap, store_type);
2363         while (42)
2364         {
2365                 char const *name;
2366                 int status;
2367
2368                 /* Set the type instance. */
2369                 name = va_arg (ap, char const *);
2370                 if (name == NULL)
2371                         break;
2372                 sstrncpy (vl->type_instance, name, sizeof (vl->type_instance));
2373
2374                 /* Set the value. */
2375                 switch (store_type)
2376                 {
2377                 case DS_TYPE_GAUGE:
2378                         vl->values[0].gauge = va_arg (ap, gauge_t);
2379                         if (store_percentage)
2380                                 vl->values[0].gauge *= sum ? (100.0 / sum) : NAN;
2381                         break;
2382                 case DS_TYPE_ABSOLUTE:
2383                         vl->values[0].absolute = va_arg (ap, absolute_t);
2384                         break;
2385                 case DS_TYPE_COUNTER:
2386                         vl->values[0].counter  = va_arg (ap, counter_t);
2387                         break;
2388                 case DS_TYPE_DERIVE:
2389                         vl->values[0].derive   = va_arg (ap, derive_t);
2390                         break;
2391                 default:
2392                         ERROR ("plugin_dispatch_multivalue: given store_type is incorrect.");
2393                         failed++;
2394                 }
2395
2396
2397                 status = plugin_write_enqueue (vl);
2398                 if (status != 0)
2399                         failed++;
2400         }
2401         va_end (ap);
2402
2403         plugin_value_list_free (vl);
2404         return (failed);
2405 } /* }}} int plugin_dispatch_multivalue */
2406
2407 int plugin_dispatch_notification (const notification_t *notif)
2408 {
2409         llentry_t *le;
2410         /* Possible TODO: Add flap detection here */
2411
2412         DEBUG ("plugin_dispatch_notification: severity = %i; message = %s; "
2413                         "time = %.3f; host = %s;",
2414                         notif->severity, notif->message,
2415                         CDTIME_T_TO_DOUBLE (notif->time), notif->host);
2416
2417         /* Nobody cares for notifications */
2418         if (list_notification == NULL)
2419                 return (-1);
2420
2421         le = llist_head (list_notification);
2422         while (le != NULL)
2423         {
2424                 callback_func_t *cf;
2425                 plugin_notification_cb callback;
2426                 int status;
2427
2428                 /* do not switch plugin context; rather keep the context
2429                  * (interval) information of the calling plugin */
2430
2431                 cf = le->value;
2432                 callback = cf->cf_callback;
2433                 status = (*callback) (notif, &cf->cf_udata);
2434                 if (status != 0)
2435                 {
2436                         WARNING ("plugin_dispatch_notification: Notification "
2437                                         "callback %s returned %i.",
2438                                         le->key, status);
2439                 }
2440
2441                 le = le->next;
2442         }
2443
2444         return (0);
2445 } /* int plugin_dispatch_notification */
2446
2447 void plugin_log (int level, const char *format, ...)
2448 {
2449         char msg[1024];
2450         va_list ap;
2451         llentry_t *le;
2452
2453 #if !COLLECT_DEBUG
2454         if (level >= LOG_DEBUG)
2455                 return;
2456 #endif
2457
2458         va_start (ap, format);
2459         vsnprintf (msg, sizeof (msg), format, ap);
2460         msg[sizeof (msg) - 1] = '\0';
2461         va_end (ap);
2462
2463         if (list_log == NULL)
2464         {
2465                 fprintf (stderr, "%s\n", msg);
2466                 return;
2467         }
2468
2469         le = llist_head (list_log);
2470         while (le != NULL)
2471         {
2472                 callback_func_t *cf;
2473                 plugin_log_cb callback;
2474
2475                 cf = le->value;
2476                 callback = cf->cf_callback;
2477
2478                 /* do not switch plugin context; rather keep the context
2479                  * (interval) information of the calling plugin */
2480
2481                 (*callback) (level, msg, &cf->cf_udata);
2482
2483                 le = le->next;
2484         }
2485 } /* void plugin_log */
2486
2487 int parse_log_severity (const char *severity)
2488 {
2489         int log_level = -1;
2490
2491         if ((0 == strcasecmp (severity, "emerg"))
2492                         || (0 == strcasecmp (severity, "alert"))
2493                         || (0 == strcasecmp (severity, "crit"))
2494                         || (0 == strcasecmp (severity, "err")))
2495                 log_level = LOG_ERR;
2496         else if (0 == strcasecmp (severity, "warning"))
2497                 log_level = LOG_WARNING;
2498         else if (0 == strcasecmp (severity, "notice"))
2499                 log_level = LOG_NOTICE;
2500         else if (0 == strcasecmp (severity, "info"))
2501                 log_level = LOG_INFO;
2502 #if COLLECT_DEBUG
2503         else if (0 == strcasecmp (severity, "debug"))
2504                 log_level = LOG_DEBUG;
2505 #endif /* COLLECT_DEBUG */
2506
2507         return (log_level);
2508 } /* int parse_log_severity */
2509
2510 int parse_notif_severity (const char *severity)
2511 {
2512         int notif_severity = -1;
2513
2514         if (strcasecmp (severity, "FAILURE") == 0)
2515                 notif_severity = NOTIF_FAILURE;
2516         else if (strcmp (severity, "OKAY") == 0)
2517                 notif_severity = NOTIF_OKAY;
2518         else if ((strcmp (severity, "WARNING") == 0)
2519                         || (strcmp (severity, "WARN") == 0))
2520                 notif_severity = NOTIF_WARNING;
2521
2522         return (notif_severity);
2523 } /* int parse_notif_severity */
2524
2525 const data_set_t *plugin_get_ds (const char *name)
2526 {
2527         data_set_t *ds;
2528
2529         if (data_sets == NULL)
2530         {
2531                 ERROR ("plugin_get_ds: No data sets are defined yet.");
2532                 return (NULL);
2533         }
2534
2535         if (c_avl_get (data_sets, name, (void *) &ds) != 0)
2536         {
2537                 DEBUG ("No such dataset registered: %s", name);
2538                 return (NULL);
2539         }
2540
2541         return (ds);
2542 } /* data_set_t *plugin_get_ds */
2543
2544 static int plugin_notification_meta_add (notification_t *n,
2545     const char *name,
2546     enum notification_meta_type_e type,
2547     const void *value)
2548 {
2549   notification_meta_t *meta;
2550   notification_meta_t *tail;
2551
2552   if ((n == NULL) || (name == NULL) || (value == NULL))
2553   {
2554     ERROR ("plugin_notification_meta_add: A pointer is NULL!");
2555     return (-1);
2556   }
2557
2558   meta = calloc (1, sizeof (*meta));
2559   if (meta == NULL)
2560   {
2561     ERROR ("plugin_notification_meta_add: calloc failed.");
2562     return (-1);
2563   }
2564
2565   sstrncpy (meta->name, name, sizeof (meta->name));
2566   meta->type = type;
2567
2568   switch (type)
2569   {
2570     case NM_TYPE_STRING:
2571     {
2572       meta->nm_value.nm_string = strdup ((const char *) value);
2573       if (meta->nm_value.nm_string == NULL)
2574       {
2575         ERROR ("plugin_notification_meta_add: strdup failed.");
2576         sfree (meta);
2577         return (-1);
2578       }
2579       break;
2580     }
2581     case NM_TYPE_SIGNED_INT:
2582     {
2583       meta->nm_value.nm_signed_int = *((int64_t *) value);
2584       break;
2585     }
2586     case NM_TYPE_UNSIGNED_INT:
2587     {
2588       meta->nm_value.nm_unsigned_int = *((uint64_t *) value);
2589       break;
2590     }
2591     case NM_TYPE_DOUBLE:
2592     {
2593       meta->nm_value.nm_double = *((double *) value);
2594       break;
2595     }
2596     case NM_TYPE_BOOLEAN:
2597     {
2598       meta->nm_value.nm_boolean = *((_Bool *) value);
2599       break;
2600     }
2601     default:
2602     {
2603       ERROR ("plugin_notification_meta_add: Unknown type: %i", type);
2604       sfree (meta);
2605       return (-1);
2606     }
2607   } /* switch (type) */
2608
2609   meta->next = NULL;
2610   tail = n->meta;
2611   while ((tail != NULL) && (tail->next != NULL))
2612     tail = tail->next;
2613
2614   if (tail == NULL)
2615     n->meta = meta;
2616   else
2617     tail->next = meta;
2618
2619   return (0);
2620 } /* int plugin_notification_meta_add */
2621
2622 int plugin_notification_meta_add_string (notification_t *n,
2623     const char *name,
2624     const char *value)
2625 {
2626   return (plugin_notification_meta_add (n, name, NM_TYPE_STRING, value));
2627 }
2628
2629 int plugin_notification_meta_add_signed_int (notification_t *n,
2630     const char *name,
2631     int64_t value)
2632 {
2633   return (plugin_notification_meta_add (n, name, NM_TYPE_SIGNED_INT, &value));
2634 }
2635
2636 int plugin_notification_meta_add_unsigned_int (notification_t *n,
2637     const char *name,
2638     uint64_t value)
2639 {
2640   return (plugin_notification_meta_add (n, name, NM_TYPE_UNSIGNED_INT, &value));
2641 }
2642
2643 int plugin_notification_meta_add_double (notification_t *n,
2644     const char *name,
2645     double value)
2646 {
2647   return (plugin_notification_meta_add (n, name, NM_TYPE_DOUBLE, &value));
2648 }
2649
2650 int plugin_notification_meta_add_boolean (notification_t *n,
2651     const char *name,
2652     _Bool value)
2653 {
2654   return (plugin_notification_meta_add (n, name, NM_TYPE_BOOLEAN, &value));
2655 }
2656
2657 int plugin_notification_meta_copy (notification_t *dst,
2658     const notification_t *src)
2659 {
2660   assert (dst != NULL);
2661   assert (src != NULL);
2662   assert (dst != src);
2663   assert ((src->meta == NULL) || (src->meta != dst->meta));
2664
2665   for (notification_meta_t *meta = src->meta; meta != NULL; meta = meta->next)
2666   {
2667     if (meta->type == NM_TYPE_STRING)
2668       plugin_notification_meta_add_string (dst, meta->name,
2669           meta->nm_value.nm_string);
2670     else if (meta->type == NM_TYPE_SIGNED_INT)
2671       plugin_notification_meta_add_signed_int (dst, meta->name,
2672           meta->nm_value.nm_signed_int);
2673     else if (meta->type == NM_TYPE_UNSIGNED_INT)
2674       plugin_notification_meta_add_unsigned_int (dst, meta->name,
2675           meta->nm_value.nm_unsigned_int);
2676     else if (meta->type == NM_TYPE_DOUBLE)
2677       plugin_notification_meta_add_double (dst, meta->name,
2678           meta->nm_value.nm_double);
2679     else if (meta->type == NM_TYPE_BOOLEAN)
2680       plugin_notification_meta_add_boolean (dst, meta->name,
2681           meta->nm_value.nm_boolean);
2682   }
2683
2684   return (0);
2685 } /* int plugin_notification_meta_copy */
2686
2687 int plugin_notification_meta_free (notification_meta_t *n)
2688 {
2689   notification_meta_t *this;
2690   notification_meta_t *next;
2691
2692   if (n == NULL)
2693   {
2694     ERROR ("plugin_notification_meta_free: n == NULL!");
2695     return (-1);
2696   }
2697
2698   this = n;
2699   while (this != NULL)
2700   {
2701     next = this->next;
2702
2703     if (this->type == NM_TYPE_STRING)
2704     {
2705       /* Assign to a temporary variable to work around nm_string's const
2706        * modifier. */
2707       void *tmp = (void *) this->nm_value.nm_string;
2708
2709       sfree (tmp);
2710       this->nm_value.nm_string = NULL;
2711     }
2712     sfree (this);
2713
2714     this = next;
2715   }
2716
2717   return (0);
2718 } /* int plugin_notification_meta_free */
2719
2720 static void plugin_ctx_destructor (void *ctx)
2721 {
2722         sfree (ctx);
2723 } /* void plugin_ctx_destructor */
2724
2725 static plugin_ctx_t ctx_init = { /* interval = */ 0 };
2726
2727 static plugin_ctx_t *plugin_ctx_create (void)
2728 {
2729         plugin_ctx_t *ctx;
2730
2731         ctx = malloc (sizeof (*ctx));
2732         if (ctx == NULL) {
2733                 char errbuf[1024];
2734                 ERROR ("Failed to allocate plugin context: %s",
2735                                 sstrerror (errno, errbuf, sizeof (errbuf)));
2736                 return NULL;
2737         }
2738
2739         *ctx = ctx_init;
2740         assert (plugin_ctx_key_initialized);
2741         pthread_setspecific (plugin_ctx_key, ctx);
2742         DEBUG("Created new plugin context.");
2743         return (ctx);
2744 } /* int plugin_ctx_create */
2745
2746 void plugin_init_ctx (void)
2747 {
2748         pthread_key_create (&plugin_ctx_key, plugin_ctx_destructor);
2749         plugin_ctx_key_initialized = 1;
2750 } /* void plugin_init_ctx */
2751
2752 plugin_ctx_t plugin_get_ctx (void)
2753 {
2754         plugin_ctx_t *ctx;
2755
2756         assert (plugin_ctx_key_initialized);
2757         ctx = pthread_getspecific (plugin_ctx_key);
2758
2759         if (ctx == NULL) {
2760                 ctx = plugin_ctx_create ();
2761                 /* this must no happen -- exit() instead? */
2762                 if (ctx == NULL)
2763                         return ctx_init;
2764         }
2765
2766         return (*ctx);
2767 } /* plugin_ctx_t plugin_get_ctx */
2768
2769 plugin_ctx_t plugin_set_ctx (plugin_ctx_t ctx)
2770 {
2771         plugin_ctx_t *c;
2772         plugin_ctx_t old;
2773
2774         assert (plugin_ctx_key_initialized);
2775         c = pthread_getspecific (plugin_ctx_key);
2776
2777         if (c == NULL) {
2778                 c = plugin_ctx_create ();
2779                 /* this must no happen -- exit() instead? */
2780                 if (c == NULL)
2781                         return ctx_init;
2782         }
2783
2784         old = *c;
2785         *c = ctx;
2786
2787         return (old);
2788 } /* void plugin_set_ctx */
2789
2790 cdtime_t plugin_get_interval (void)
2791 {
2792         cdtime_t interval;
2793
2794         interval = plugin_get_ctx().interval;
2795         if (interval > 0)
2796                 return interval;
2797
2798         return cf_get_default_interval ();
2799 } /* cdtime_t plugin_get_interval */
2800
2801 typedef struct {
2802         plugin_ctx_t ctx;
2803         void *(*start_routine) (void *);
2804         void *arg;
2805 } plugin_thread_t;
2806
2807 static void *plugin_thread_start (void *arg)
2808 {
2809         plugin_thread_t *plugin_thread = arg;
2810
2811         void *(*start_routine) (void *) = plugin_thread->start_routine;
2812         void *plugin_arg = plugin_thread->arg;
2813
2814         plugin_set_ctx (plugin_thread->ctx);
2815
2816         sfree (plugin_thread);
2817
2818         return start_routine (plugin_arg);
2819 } /* void *plugin_thread_start */
2820
2821 int plugin_thread_create (pthread_t *thread, const pthread_attr_t *attr,
2822                 void *(*start_routine) (void *), void *arg, char *name)
2823 {
2824         plugin_thread_t *plugin_thread;
2825         int ret;
2826
2827         plugin_thread = malloc (sizeof (*plugin_thread));
2828         if (plugin_thread == NULL)
2829                 return -1;
2830
2831         plugin_thread->ctx           = plugin_get_ctx ();
2832         plugin_thread->start_routine = start_routine;
2833         plugin_thread->arg           = arg;
2834
2835         ret = pthread_create (thread, attr,
2836                         plugin_thread_start, plugin_thread);
2837
2838         if (ret == 0 && name != NULL) {
2839 #if defined(HAVE_PTHREAD_SETNAME_NP) || defined(HAVE_PTHREAD_SET_NAME_NP)
2840                 char thread_name[16];
2841                 sstrncpy (thread_name, name, sizeof(thread_name));
2842 # if defined(HAVE_PTHREAD_SETNAME_NP)
2843                 pthread_setname_np (*thread, thread_name);
2844 # elif defined(HAVE_PTHREAD_SET_NAME_NP)
2845                 pthread_set_name_np (*thread, thread_name);
2846 # endif
2847 #endif
2848         }
2849
2850         return ret;
2851 } /* int plugin_thread_create */
2852
2853 /* vim: set sw=8 ts=8 noet fdm=marker : */