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