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