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