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