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