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