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