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