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