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