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