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