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