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