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