Code

Merge branch 'collectd-5.3'
[collectd.git] / src / plugin.c
1 /**
2  * collectd - src/plugin.c
3  * Copyright (C) 2005-2013  Florian octo Forster
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Authors:
19  *   Florian octo Forster <octo at collectd.org>
20  *   Sebastian Harl <sh at tokkee.org>
21  **/
23 #include "collectd.h"
24 #include "common.h"
25 #include "plugin.h"
26 #include "configfile.h"
27 #include "filter_chain.h"
28 #include "utils_avltree.h"
29 #include "utils_cache.h"
30 #include "utils_complain.h"
31 #include "utils_llist.h"
32 #include "utils_heap.h"
33 #include "utils_time.h"
35 #if HAVE_PTHREAD_H
36 # include <pthread.h>
37 #endif
39 #include <ltdl.h>
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;
52 #define RF_SIMPLE  0
53 #define RF_COMPLEX 1
54 #define RF_REMOVE  65535
55 struct read_func_s
56 {
57         /* `read_func_t' "inherits" from `callback_func_t'.
58          * The `rf_super' member MUST be the first one in this structure! */
59 #define rf_callback rf_super.cf_callback
60 #define rf_udata rf_super.cf_udata
61 #define rf_ctx rf_super.cf_ctx
62         callback_func_t rf_super;
63         char rf_group[DATA_MAX_NAME_LEN];
64         char *rf_name;
65         int rf_type;
66         cdtime_t rf_interval;
67         cdtime_t rf_effective_interval;
68         cdtime_t rf_next_read;
69 };
70 typedef struct read_func_s read_func_t;
72 struct write_queue_s;
73 typedef struct write_queue_s write_queue_t;
74 struct write_queue_s
75 {
76         value_list_t *vl;
77         plugin_ctx_t ctx;
78         write_queue_t *next;
79 };
81 /*
82  * Private variables
83  */
84 static c_avl_tree_t *plugins_loaded = NULL;
86 static llist_t *list_init;
87 static llist_t *list_write;
88 static llist_t *list_flush;
89 static llist_t *list_missing;
90 static llist_t *list_shutdown;
91 static llist_t *list_log;
92 static llist_t *list_notification;
94 static fc_chain_t *pre_cache_chain = NULL;
95 static fc_chain_t *post_cache_chain = NULL;
97 static c_avl_tree_t *data_sets;
99 static char *plugindir = NULL;
101 static c_heap_t       *read_heap = NULL;
102 static llist_t        *read_list;
103 static int             read_loop = 1;
104 static pthread_mutex_t read_lock = PTHREAD_MUTEX_INITIALIZER;
105 static pthread_cond_t  read_cond = PTHREAD_COND_INITIALIZER;
106 static pthread_t      *read_threads = NULL;
107 static int             read_threads_num = 0;
109 static write_queue_t  *write_queue_head;
110 static write_queue_t  *write_queue_tail;
111 static _Bool           write_loop = 1;
112 static pthread_mutex_t write_lock = PTHREAD_MUTEX_INITIALIZER;
113 static pthread_cond_t  write_cond = PTHREAD_COND_INITIALIZER;
114 static pthread_t      *write_threads = NULL;
115 static size_t          write_threads_num = 0;
117 static pthread_key_t   plugin_ctx_key;
118 static _Bool           plugin_ctx_key_initialized = 0;
120 /*
121  * Static functions
122  */
123 static int plugin_dispatch_values_internal (value_list_t *vl);
125 static const char *plugin_get_dir (void)
127         if (plugindir == NULL)
128                 return (PLUGINDIR);
129         else
130                 return (plugindir);
133 static void destroy_callback (callback_func_t *cf) /* {{{ */
135         if (cf == NULL)
136                 return;
138         if ((cf->cf_udata.data != NULL) && (cf->cf_udata.free_func != NULL))
139         {
140                 cf->cf_udata.free_func (cf->cf_udata.data);
141                 cf->cf_udata.data = NULL;
142                 cf->cf_udata.free_func = NULL;
143         }
144         sfree (cf);
145 } /* }}} void destroy_callback */
147 static void destroy_all_callbacks (llist_t **list) /* {{{ */
149         llentry_t *le;
151         if (*list == NULL)
152                 return;
154         le = llist_head (*list);
155         while (le != NULL)
156         {
157                 llentry_t *le_next;
159                 le_next = le->next;
161                 sfree (le->key);
162                 destroy_callback (le->value);
163                 le->value = NULL;
165                 le = le_next;
166         }
168         llist_destroy (*list);
169         *list = NULL;
170 } /* }}} void destroy_all_callbacks */
172 static void destroy_read_heap (void) /* {{{ */
174         if (read_heap == NULL)
175                 return;
177         while (42)
178         {
179                 callback_func_t *cf;
181                 cf = c_heap_get_root (read_heap);
182                 if (cf == NULL)
183                         break;
185                 destroy_callback (cf);
186         }
188         c_heap_destroy (read_heap);
189         read_heap = NULL;
190 } /* }}} void destroy_read_heap */
192 static int register_callback (llist_t **list, /* {{{ */
193                 const char *name, callback_func_t *cf)
195         llentry_t *le;
196         char *key;
198         if (*list == NULL)
199         {
200                 *list = llist_create ();
201                 if (*list == NULL)
202                 {
203                         ERROR ("plugin: register_callback: "
204                                         "llist_create failed.");
205                         destroy_callback (cf);
206                         return (-1);
207                 }
208         }
210         key = strdup (name);
211         if (key == NULL)
212         {
213                 ERROR ("plugin: register_callback: strdup failed.");
214                 destroy_callback (cf);
215                 return (-1);
216         }
218         le = llist_search (*list, name);
219         if (le == NULL)
220         {
221                 le = llentry_create (key, cf);
222                 if (le == NULL)
223                 {
224                         ERROR ("plugin: register_callback: "
225                                         "llentry_create failed.");
226                         free (key);
227                         destroy_callback (cf);
228                         return (-1);
229                 }
231                 llist_append (*list, le);
232         }
233         else
234         {
235                 callback_func_t *old_cf;
237                 old_cf = le->value;
238                 le->value = cf;
240                 WARNING ("plugin: register_callback: "
241                                 "a callback named `%s' already exists - "
242                                 "overwriting the old entry!", name);
244                 destroy_callback (old_cf);
245                 sfree (key);
246         }
248         return (0);
249 } /* }}} int register_callback */
251 static int create_register_callback (llist_t **list, /* {{{ */
252                 const char *name, void *callback, user_data_t *ud)
254         callback_func_t *cf;
256         cf = (callback_func_t *) malloc (sizeof (*cf));
257         if (cf == NULL)
258         {
259                 ERROR ("plugin: create_register_callback: malloc failed.");
260                 return (-1);
261         }
262         memset (cf, 0, sizeof (*cf));
264         cf->cf_callback = callback;
265         if (ud == NULL)
266         {
267                 cf->cf_udata.data = NULL;
268                 cf->cf_udata.free_func = NULL;
269         }
270         else
271         {
272                 cf->cf_udata = *ud;
273         }
275         cf->cf_ctx = plugin_get_ctx ();
277         return (register_callback (list, name, cf));
278 } /* }}} int create_register_callback */
280 static int plugin_unregister (llist_t *list, const char *name) /* {{{ */
282         llentry_t *e;
284         if (list == NULL)
285                 return (-1);
287         e = llist_search (list, name);
288         if (e == NULL)
289                 return (-1);
291         llist_remove (list, e);
293         sfree (e->key);
294         destroy_callback (e->value);
296         llentry_destroy (e);
298         return (0);
299 } /* }}} int plugin_unregister */
301 /*
302  * (Try to) load the shared object `file'. Won't complain if it isn't a shared
303  * object, but it will bitch about a shared object not having a
304  * ``module_register'' symbol..
305  */
306 static int plugin_load_file (char *file, uint32_t flags)
308         lt_dlhandle dlh;
309         void (*reg_handle) (void);
311         lt_dlinit ();
312         lt_dlerror (); /* clear errors */
314 #if LIBTOOL_VERSION == 2
315         if (flags & PLUGIN_FLAGS_GLOBAL) {
316                 lt_dladvise advise;
317                 lt_dladvise_init(&advise);
318                 lt_dladvise_global(&advise);
319                 dlh = lt_dlopenadvise(file, advise);
320                 lt_dladvise_destroy(&advise);
321         } else {
322                 dlh = lt_dlopen (file);
323         }
324 #else /* if LIBTOOL_VERSION == 1 */
325         if (flags & PLUGIN_FLAGS_GLOBAL)
326                 WARNING ("plugin_load_file: The global flag is not supported, "
327                                 "libtool 2 is required for this.");
328         dlh = lt_dlopen (file);
329 #endif
331         if (dlh == NULL)
332         {
333                 char errbuf[1024] = "";
335                 ssnprintf (errbuf, sizeof (errbuf),
336                                 "lt_dlopen (\"%s\") failed: %s. "
337                                 "The most common cause for this problem are "
338                                 "missing dependencies. Use ldd(1) to check "
339                                 "the dependencies of the plugin "
340                                 "/ shared object.",
341                                 file, lt_dlerror ());
343                 ERROR ("%s", errbuf);
344                 /* Make sure this is printed to STDERR in any case, but also
345                  * make sure it's printed only once. */
346                 if (list_log != NULL)
347                         fprintf (stderr, "ERROR: %s\n", errbuf);
349                 return (1);
350         }
352         if ((reg_handle = (void (*) (void)) lt_dlsym (dlh, "module_register")) == NULL)
353         {
354                 WARNING ("Couldn't find symbol \"module_register\" in \"%s\": %s\n",
355                                 file, lt_dlerror ());
356                 lt_dlclose (dlh);
357                 return (-1);
358         }
360         (*reg_handle) ();
362         return (0);
365 static void *plugin_read_thread (void __attribute__((unused)) *args)
367         while (read_loop != 0)
368         {
369                 read_func_t *rf;
370                 plugin_ctx_t old_ctx;
371                 cdtime_t now;
372                 int status;
373                 int rf_type;
374                 int rc;
376                 /* Get the read function that needs to be read next.
377                  * We don't need to hold "read_lock" for the heap, but we need
378                  * to call c_heap_get_root() and pthread_cond_wait() in the
379                  * same protected block. */
380                 pthread_mutex_lock (&read_lock);
381                 rf = c_heap_get_root (read_heap);
382                 if (rf == NULL)
383                 {
384                         pthread_cond_wait (&read_cond, &read_lock);
385                         pthread_mutex_unlock (&read_lock);
386                         continue;
387                 }
388                 pthread_mutex_unlock (&read_lock);
390                 if (rf->rf_interval == 0)
391                 {
392                         /* this should not happen, because the interval is set
393                          * for each plugin when loading it
394                          * XXX: issue a warning? */
395                         rf->rf_interval = plugin_get_interval ();
396                         rf->rf_effective_interval = rf->rf_interval;
398                         rf->rf_next_read = cdtime ();
399                 }
401                 /* sleep until this entry is due,
402                  * using pthread_cond_timedwait */
403                 pthread_mutex_lock (&read_lock);
404                 /* In pthread_cond_timedwait, spurious wakeups are possible
405                  * (and really happen, at least on NetBSD with > 1 CPU), thus
406                  * we need to re-evaluate the condition every time
407                  * pthread_cond_timedwait returns. */
408                 rc = 0;
409                 while ((read_loop != 0)
410                                 && (cdtime () < rf->rf_next_read)
411                                 && rc == 0)
412                 {
413                         struct timespec ts = { 0 };
415                         CDTIME_T_TO_TIMESPEC (rf->rf_next_read, &ts);
417                         rc = pthread_cond_timedwait (&read_cond, &read_lock,
418                                 &ts);
419                 }
421                 /* Must hold `read_lock' when accessing `rf->rf_type'. */
422                 rf_type = rf->rf_type;
423                 pthread_mutex_unlock (&read_lock);
425                 /* Check if we're supposed to stop.. This may have interrupted
426                  * the sleep, too. */
427                 if (read_loop == 0)
428                 {
429                         /* Insert `rf' again, so it can be free'd correctly */
430                         c_heap_insert (read_heap, rf);
431                         break;
432                 }
434                 /* The entry has been marked for deletion. The linked list
435                  * entry has already been removed by `plugin_unregister_read'.
436                  * All we have to do here is free the `read_func_t' and
437                  * continue. */
438                 if (rf_type == RF_REMOVE)
439                 {
440                         DEBUG ("plugin_read_thread: Destroying the `%s' "
441                                         "callback.", rf->rf_name);
442                         sfree (rf->rf_name);
443                         destroy_callback ((callback_func_t *) rf);
444                         rf = NULL;
445                         continue;
446                 }
448                 DEBUG ("plugin_read_thread: Handling `%s'.", rf->rf_name);
450                 old_ctx = plugin_set_ctx (rf->rf_ctx);
452                 if (rf_type == RF_SIMPLE)
453                 {
454                         int (*callback) (void);
456                         callback = rf->rf_callback;
457                         status = (*callback) ();
458                 }
459                 else
460                 {
461                         plugin_read_cb callback;
463                         assert (rf_type == RF_COMPLEX);
465                         callback = rf->rf_callback;
466                         status = (*callback) (&rf->rf_udata);
467                 }
469                 plugin_set_ctx (old_ctx);
471                 /* If the function signals failure, we will increase the
472                  * intervals in which it will be called. */
473                 if (status != 0)
474                 {
475                         rf->rf_effective_interval *= 2;
476                         if (rf->rf_effective_interval > TIME_T_TO_CDTIME_T (86400))
477                                 rf->rf_effective_interval = TIME_T_TO_CDTIME_T (86400);
479                         NOTICE ("read-function of plugin `%s' failed. "
480                                         "Will suspend it for %.3f seconds.",
481                                         rf->rf_name,
482                                         CDTIME_T_TO_DOUBLE (rf->rf_effective_interval));
483                 }
484                 else
485                 {
486                         /* Success: Restore the interval, if it was changed. */
487                         rf->rf_effective_interval = rf->rf_interval;
488                 }
490                 /* update the ``next read due'' field */
491                 now = cdtime ();
493                 DEBUG ("plugin_read_thread: Effective interval of the "
494                                 "%s plugin is %.3f seconds.",
495                                 rf->rf_name,
496                                 CDTIME_T_TO_DOUBLE (rf->rf_effective_interval));
498                 /* Calculate the next (absolute) time at which this function
499                  * should be called. */
500                 rf->rf_next_read += rf->rf_effective_interval;
502                 /* Check, if `rf_next_read' is in the past. */
503                 if (rf->rf_next_read < now)
504                 {
505                         /* `rf_next_read' is in the past. Insert `now'
506                          * so this value doesn't trail off into the
507                          * past too much. */
508                         rf->rf_next_read = now;
509                 }
511                 DEBUG ("plugin_read_thread: Next read of the %s plugin at %.3f.",
512                                 rf->rf_name,
513                                 CDTIME_T_TO_DOUBLE (rf->rf_next_read));
515                 /* Re-insert this read function into the heap again. */
516                 c_heap_insert (read_heap, rf);
517         } /* while (read_loop) */
519         pthread_exit (NULL);
520         return ((void *) 0);
521 } /* void *plugin_read_thread */
523 static void start_read_threads (int num)
525         int i;
527         if (read_threads != NULL)
528                 return;
530         read_threads = (pthread_t *) calloc (num, sizeof (pthread_t));
531         if (read_threads == NULL)
532         {
533                 ERROR ("plugin: start_read_threads: calloc failed.");
534                 return;
535         }
537         read_threads_num = 0;
538         for (i = 0; i < num; i++)
539         {
540                 if (pthread_create (read_threads + read_threads_num, NULL,
541                                         plugin_read_thread, NULL) == 0)
542                 {
543                         read_threads_num++;
544                 }
545                 else
546                 {
547                         ERROR ("plugin: start_read_threads: pthread_create failed.");
548                         return;
549                 }
550         } /* for (i) */
551 } /* void start_read_threads */
553 static void stop_read_threads (void)
555         int i;
557         if (read_threads == NULL)
558                 return;
560         INFO ("collectd: Stopping %i read threads.", read_threads_num);
562         pthread_mutex_lock (&read_lock);
563         read_loop = 0;
564         DEBUG ("plugin: stop_read_threads: Signalling `read_cond'");
565         pthread_cond_broadcast (&read_cond);
566         pthread_mutex_unlock (&read_lock);
568         for (i = 0; i < read_threads_num; i++)
569         {
570                 if (pthread_join (read_threads[i], NULL) != 0)
571                 {
572                         ERROR ("plugin: stop_read_threads: pthread_join failed.");
573                 }
574                 read_threads[i] = (pthread_t) 0;
575         }
576         sfree (read_threads);
577         read_threads_num = 0;
578 } /* void stop_read_threads */
580 static void plugin_value_list_free (value_list_t *vl) /* {{{ */
582         if (vl == NULL)
583                 return;
585         meta_data_destroy (vl->meta);
586         sfree (vl->values);
587         sfree (vl);
588 } /* }}} void plugin_value_list_free */
590 static value_list_t *plugin_value_list_clone (value_list_t const *vl_orig) /* {{{ */
592         value_list_t *vl;
594         if (vl_orig == NULL)
595                 return (NULL);
597         vl = malloc (sizeof (*vl));
598         if (vl == NULL)
599                 return (NULL);
600         memcpy (vl, vl_orig, sizeof (*vl));
602         vl->values = calloc (vl_orig->values_len, sizeof (*vl->values));
603         if (vl->values == NULL)
604         {
605                 plugin_value_list_free (vl);
606                 return (NULL);
607         }
608         memcpy (vl->values, vl_orig->values,
609                         vl_orig->values_len * sizeof (*vl->values));
611         vl->meta = meta_data_clone (vl->meta);
612         if ((vl_orig->meta != NULL) && (vl->meta == NULL))
613         {
614                 plugin_value_list_free (vl);
615                 return (NULL);
616         }
618         if (vl->time == 0)
619                 vl->time = cdtime ();
621         /* Fill in the interval from the thread context, if it is zero. */
622         if (vl->interval == 0)
623         {
624                 plugin_ctx_t ctx = plugin_get_ctx ();
626                 if (ctx.interval != 0)
627                         vl->interval = ctx.interval;
628                 else
629                 {
630                         char name[6 * DATA_MAX_NAME_LEN];
631                         FORMAT_VL (name, sizeof (name), vl);
632                         ERROR ("plugin_value_list_clone: Unable to determine "
633                                         "interval from context for "
634                                         "value list \"%s\". "
635                                         "This indicates a broken plugin. "
636                                         "Please report this problem to the "
637                                         "collectd mailing list or at "
638                                         "<http://collectd.org/bugs/>.", name);
639                         vl->interval = cf_get_default_interval ();
640                 }
641         }
643         return (vl);
644 } /* }}} value_list_t *plugin_value_list_clone */
646 static int plugin_write_enqueue (value_list_t const *vl) /* {{{ */
648         write_queue_t *q;
650         q = malloc (sizeof (*q));
651         if (q == NULL)
652                 return (ENOMEM);
653         q->next = NULL;
655         q->vl = plugin_value_list_clone (vl);
656         if (q->vl == NULL)
657         {
658                 sfree (q);
659                 return (ENOMEM);
660         }
662         /* Store context of caller (read plugin); otherwise, it would not be
663          * available to the write plugins when actually dispatching the
664          * value-list later on. */
665         q->ctx = plugin_get_ctx ();
667         pthread_mutex_lock (&write_lock);
669         if (write_queue_tail == NULL)
670         {
671                 write_queue_head = q;
672                 write_queue_tail = q;
673         }
674         else
675         {
676                 write_queue_tail->next = q;
677                 write_queue_tail = q;
678         }
680         pthread_cond_signal (&write_cond);
681         pthread_mutex_unlock (&write_lock);
683         return (0);
684 } /* }}} int plugin_write_enqueue */
686 static value_list_t *plugin_write_dequeue (void) /* {{{ */
688         write_queue_t *q;
689         value_list_t *vl;
691         pthread_mutex_lock (&write_lock);
693         while (write_loop && (write_queue_head == NULL))
694                 pthread_cond_wait (&write_cond, &write_lock);
696         if (write_queue_head == NULL)
697         {
698                 pthread_mutex_unlock (&write_lock);
699                 return (NULL);
700         }
702         q = write_queue_head;
703         write_queue_head = q->next;
704         if (write_queue_head == NULL)
705                 write_queue_tail = NULL;
707         pthread_mutex_unlock (&write_lock);
709         (void) plugin_set_ctx (q->ctx);
711         vl = q->vl;
712         sfree (q);
713         return (vl);
714 } /* }}} value_list_t *plugin_write_dequeue */
716 static void *plugin_write_thread (void __attribute__((unused)) *args) /* {{{ */
718         while (write_loop)
719         {
720                 value_list_t *vl = plugin_write_dequeue ();
721                 if (vl == NULL)
722                         continue;
724                 plugin_dispatch_values_internal (vl);
726                 plugin_value_list_free (vl);
727         }
729         pthread_exit (NULL);
730         return ((void *) 0);
731 } /* }}} void *plugin_write_thread */
733 static void start_write_threads (size_t num) /* {{{ */
735         size_t i;
737         if (write_threads != NULL)
738                 return;
740         write_threads = (pthread_t *) calloc (num, sizeof (pthread_t));
741         if (write_threads == NULL)
742         {
743                 ERROR ("plugin: start_write_threads: calloc failed.");
744                 return;
745         }
747         write_threads_num = 0;
748         for (i = 0; i < num; i++)
749         {
750                 int status;
752                 status = pthread_create (write_threads + write_threads_num,
753                                 /* attr = */ NULL,
754                                 plugin_write_thread,
755                                 /* arg = */ NULL);
756                 if (status != 0)
757                 {
758                         char errbuf[1024];
759                         ERROR ("plugin: start_write_threads: pthread_create failed "
760                                         "with status %i (%s).", status,
761                                         sstrerror (status, errbuf, sizeof (errbuf)));
762                         return;
763                 }
765                 write_threads_num++;
766         } /* for (i) */
767 } /* }}} void start_write_threads */
769 static void stop_write_threads (void) /* {{{ */
771         write_queue_t *q;
772         int i;
774         if (write_threads == NULL)
775                 return;
777         INFO ("collectd: Stopping %zu write threads.", write_threads_num);
779         pthread_mutex_lock (&write_lock);
780         write_loop = 0;
781         DEBUG ("plugin: stop_write_threads: Signalling `write_cond'");
782         pthread_cond_broadcast (&write_cond);
783         pthread_mutex_unlock (&write_lock);
785         for (i = 0; i < write_threads_num; i++)
786         {
787                 if (pthread_join (write_threads[i], NULL) != 0)
788                 {
789                         ERROR ("plugin: stop_write_threads: pthread_join failed.");
790                 }
791                 write_threads[i] = (pthread_t) 0;
792         }
793         sfree (write_threads);
794         write_threads_num = 0;
796         pthread_mutex_lock (&write_lock);
797         i = 0;
798         for (q = write_queue_head; q != NULL; )
799         {
800                 write_queue_t *q1 = q;
801                 plugin_value_list_free (q->vl);
802                 q = q->next;
803                 sfree (q1);
804                 i++;
805         }
806         write_queue_head = NULL;
807         write_queue_tail = NULL;
808         pthread_mutex_unlock (&write_lock);
810         if (i > 0)
811         {
812                 WARNING ("plugin: %i value list%s left after shutting down "
813                                 "the write threads.",
814                                 i, (i == 1) ? " was" : "s were");
815         }
816 } /* }}} void stop_write_threads */
818 /*
819  * Public functions
820  */
821 void plugin_set_dir (const char *dir)
823         if (plugindir != NULL)
824                 free (plugindir);
826         if (dir == NULL)
827                 plugindir = NULL;
828         else if ((plugindir = strdup (dir)) == NULL)
829         {
830                 char errbuf[1024];
831                 ERROR ("strdup failed: %s",
832                                 sstrerror (errno, errbuf, sizeof (errbuf)));
833         }
836 static _Bool plugin_is_loaded (char const *name)
838         int status;
840         if (plugins_loaded == NULL)
841                 plugins_loaded = c_avl_create ((void *) strcasecmp);
842         assert (plugins_loaded != NULL);
844         status = c_avl_get (plugins_loaded, name, /* ret_value = */ NULL);
845         return (status == 0);
848 static int plugin_mark_loaded (char const *name)
850         char *name_copy;
851         int status;
853         name_copy = strdup (name);
854         if (name_copy == NULL)
855                 return (ENOMEM);
857         status = c_avl_insert (plugins_loaded,
858                         /* key = */ name_copy, /* value = */ NULL);
859         return (status);
862 static void plugin_free_loaded ()
864         void *key;
865         void *value;
867         if (plugins_loaded == NULL)
868                 return;
870         while (c_avl_pick (plugins_loaded, &key, &value) == 0)
871         {
872                 sfree (key);
873                 assert (value == NULL);
874         }
876         c_avl_destroy (plugins_loaded);
877         plugins_loaded = NULL;
880 #define BUFSIZE 512
881 int plugin_load (char const *plugin_name, uint32_t flags)
883         DIR  *dh;
884         const char *dir;
885         char  filename[BUFSIZE] = "";
886         char  typename[BUFSIZE];
887         int   typename_len;
888         int   ret;
889         struct stat    statbuf;
890         struct dirent *de;
891         int status;
893         if (plugin_name == NULL)
894                 return (EINVAL);
896         /* Check if plugin is already loaded and don't do anything in this
897          * case. */
898         if (plugin_is_loaded (plugin_name))
899                 return (0);
901         dir = plugin_get_dir ();
902         ret = 1;
904         /*
905          * XXX: Magic at work:
906          *
907          * Some of the language bindings, for example the Python and Perl
908          * plugins, need to be able to export symbols to the scripts they run.
909          * For this to happen, the "Globals" flag needs to be set.
910          * Unfortunately, this technical detail is hard to explain to the
911          * average user and she shouldn't have to worry about this, ideally.
912          * So in order to save everyone's sanity use a different default for a
913          * handful of special plugins. --octo
914          */
915         if ((strcasecmp ("perl", plugin_name) == 0)
916                         || (strcasecmp ("python", plugin_name) == 0))
917                 flags |= PLUGIN_FLAGS_GLOBAL;
919         /* `cpu' should not match `cpufreq'. To solve this we add `.so' to the
920          * type when matching the filename */
921         status = ssnprintf (typename, sizeof (typename), "%s.so", plugin_name);
922         if ((status < 0) || ((size_t) status >= sizeof (typename)))
923         {
924                 WARNING ("plugin_load: Filename too long: \"%s.so\"", plugin_name);
925                 return (-1);
926         }
927         typename_len = strlen (typename);
929         if ((dh = opendir (dir)) == NULL)
930         {
931                 char errbuf[1024];
932                 ERROR ("plugin_load: opendir (%s) failed: %s", dir,
933                                 sstrerror (errno, errbuf, sizeof (errbuf)));
934                 return (-1);
935         }
937         while ((de = readdir (dh)) != NULL)
938         {
939                 if (strncasecmp (de->d_name, typename, typename_len))
940                         continue;
942                 status = ssnprintf (filename, sizeof (filename),
943                                 "%s/%s", dir, de->d_name);
944                 if ((status < 0) || ((size_t) status >= sizeof (filename)))
945                 {
946                         WARNING ("plugin_load: Filename too long: \"%s/%s\"",
947                                         dir, de->d_name);
948                         continue;
949                 }
951                 if (lstat (filename, &statbuf) == -1)
952                 {
953                         char errbuf[1024];
954                         WARNING ("plugin_load: stat (\"%s\") failed: %s",
955                                         filename,
956                                         sstrerror (errno, errbuf, sizeof (errbuf)));
957                         continue;
958                 }
959                 else if (!S_ISREG (statbuf.st_mode))
960                 {
961                         /* don't follow symlinks */
962                         WARNING ("plugin_load: %s is not a regular file.",
963                                         filename);
964                         continue;
965                 }
967                 status = plugin_load_file (filename, flags);
968                 if (status == 0)
969                 {
970                         /* success */
971                         plugin_mark_loaded (plugin_name);
972                         ret = 0;
973                         break;
974                 }
975                 else
976                 {
977                         ERROR ("plugin_load: Load plugin \"%s\" failed with "
978                                         "status %i.", plugin_name, status);
979                 }
980         }
982         closedir (dh);
984         if (filename[0] == 0)
985                 ERROR ("plugin_load: Could not find plugin \"%s\" in %s",
986                                 plugin_name, dir);
988         return (ret);
991 /*
992  * The `register_*' functions follow
993  */
994 int plugin_register_config (const char *name,
995                 int (*callback) (const char *key, const char *val),
996                 const char **keys, int keys_num)
998         cf_register (name, callback, keys, keys_num);
999         return (0);
1000 } /* int plugin_register_config */
1002 int plugin_register_complex_config (const char *type,
1003                 int (*callback) (oconfig_item_t *))
1005         return (cf_register_complex (type, callback));
1006 } /* int plugin_register_complex_config */
1008 int plugin_register_init (const char *name,
1009                 int (*callback) (void))
1011         return (create_register_callback (&list_init, name, (void *) callback,
1012                                 /* user_data = */ NULL));
1013 } /* plugin_register_init */
1015 static int plugin_compare_read_func (const void *arg0, const void *arg1)
1017         const read_func_t *rf0;
1018         const read_func_t *rf1;
1020         rf0 = arg0;
1021         rf1 = arg1;
1023         if (rf0->rf_next_read < rf1->rf_next_read)
1024                 return (-1);
1025         else if (rf0->rf_next_read > rf1->rf_next_read)
1026                 return (1);
1027         else
1028                 return (0);
1029 } /* int plugin_compare_read_func */
1031 /* Add a read function to both, the heap and a linked list. The linked list if
1032  * used to look-up read functions, especially for the remove function. The heap
1033  * is used to determine which plugin to read next. */
1034 static int plugin_insert_read (read_func_t *rf)
1036         int status;
1037         llentry_t *le;
1039         rf->rf_next_read = cdtime ();
1040         rf->rf_effective_interval = rf->rf_interval;
1042         pthread_mutex_lock (&read_lock);
1044         if (read_list == NULL)
1045         {
1046                 read_list = llist_create ();
1047                 if (read_list == NULL)
1048                 {
1049                         pthread_mutex_unlock (&read_lock);
1050                         ERROR ("plugin_insert_read: read_list failed.");
1051                         return (-1);
1052                 }
1053         }
1055         if (read_heap == NULL)
1056         {
1057                 read_heap = c_heap_create (plugin_compare_read_func);
1058                 if (read_heap == NULL)
1059                 {
1060                         pthread_mutex_unlock (&read_lock);
1061                         ERROR ("plugin_insert_read: c_heap_create failed.");
1062                         return (-1);
1063                 }
1064         }
1066         le = llist_search (read_list, rf->rf_name);
1067         if (le != NULL)
1068         {
1069                 pthread_mutex_unlock (&read_lock);
1070                 WARNING ("The read function \"%s\" is already registered. "
1071                                 "Check for duplicate \"LoadPlugin\" lines "
1072                                 "in your configuration!",
1073                                 rf->rf_name);
1074                 return (EINVAL);
1075         }
1077         le = llentry_create (rf->rf_name, rf);
1078         if (le == NULL)
1079         {
1080                 pthread_mutex_unlock (&read_lock);
1081                 ERROR ("plugin_insert_read: llentry_create failed.");
1082                 return (-1);
1083         }
1085         status = c_heap_insert (read_heap, rf);
1086         if (status != 0)
1087         {
1088                 pthread_mutex_unlock (&read_lock);
1089                 ERROR ("plugin_insert_read: c_heap_insert failed.");
1090                 llentry_destroy (le);
1091                 return (-1);
1092         }
1094         /* This does not fail. */
1095         llist_append (read_list, le);
1097         /* Wake up all the read threads. */
1098         pthread_cond_broadcast (&read_cond);
1099         pthread_mutex_unlock (&read_lock);
1100         return (0);
1101 } /* int plugin_insert_read */
1103 int plugin_register_read (const char *name,
1104                 int (*callback) (void))
1106         read_func_t *rf;
1107         int status;
1109         rf = malloc (sizeof (*rf));
1110         if (rf == NULL)
1111         {
1112                 ERROR ("plugin_register_read: malloc failed.");
1113                 return (ENOMEM);
1114         }
1116         memset (rf, 0, sizeof (read_func_t));
1117         rf->rf_callback = (void *) callback;
1118         rf->rf_udata.data = NULL;
1119         rf->rf_udata.free_func = NULL;
1120         rf->rf_ctx = plugin_get_ctx ();
1121         rf->rf_group[0] = '\0';
1122         rf->rf_name = strdup (name);
1123         rf->rf_type = RF_SIMPLE;
1124         rf->rf_interval = plugin_get_interval ();
1126         status = plugin_insert_read (rf);
1127         if (status != 0)
1128                 sfree (rf);
1130         return (status);
1131 } /* int plugin_register_read */
1133 int plugin_register_complex_read (const char *group, const char *name,
1134                 plugin_read_cb callback,
1135                 const struct timespec *interval,
1136                 user_data_t *user_data)
1138         read_func_t *rf;
1139         int status;
1141         rf = malloc (sizeof (*rf));
1142         if (rf == NULL)
1143         {
1144                 ERROR ("plugin_register_complex_read: malloc failed.");
1145                 return (ENOMEM);
1146         }
1148         memset (rf, 0, sizeof (read_func_t));
1149         rf->rf_callback = (void *) callback;
1150         if (group != NULL)
1151                 sstrncpy (rf->rf_group, group, sizeof (rf->rf_group));
1152         else
1153                 rf->rf_group[0] = '\0';
1154         rf->rf_name = strdup (name);
1155         rf->rf_type = RF_COMPLEX;
1156         if (interval != NULL)
1157                 rf->rf_interval = TIMESPEC_TO_CDTIME_T (interval);
1158         else
1159                 rf->rf_interval = plugin_get_interval ();
1161         /* Set user data */
1162         if (user_data == NULL)
1163         {
1164                 rf->rf_udata.data = NULL;
1165                 rf->rf_udata.free_func = NULL;
1166         }
1167         else
1168         {
1169                 rf->rf_udata = *user_data;
1170         }
1172         rf->rf_ctx = plugin_get_ctx ();
1174         status = plugin_insert_read (rf);
1175         if (status != 0)
1176                 sfree (rf);
1178         return (status);
1179 } /* int plugin_register_complex_read */
1181 int plugin_register_write (const char *name,
1182                 plugin_write_cb callback, user_data_t *ud)
1184         return (create_register_callback (&list_write, name,
1185                                 (void *) callback, ud));
1186 } /* int plugin_register_write */
1188 int plugin_register_flush (const char *name,
1189                 plugin_flush_cb callback, user_data_t *ud)
1191         return (create_register_callback (&list_flush, name,
1192                                 (void *) callback, ud));
1193 } /* int plugin_register_flush */
1195 int plugin_register_missing (const char *name,
1196                 plugin_missing_cb callback, user_data_t *ud)
1198         return (create_register_callback (&list_missing, name,
1199                                 (void *) callback, ud));
1200 } /* int plugin_register_missing */
1202 int plugin_register_shutdown (const char *name,
1203                 int (*callback) (void))
1205         return (create_register_callback (&list_shutdown, name,
1206                                 (void *) callback, /* user_data = */ NULL));
1207 } /* int plugin_register_shutdown */
1209 static void plugin_free_data_sets (void)
1211         void *key;
1212         void *value;
1214         if (data_sets == NULL)
1215                 return;
1217         while (c_avl_pick (data_sets, &key, &value) == 0)
1218         {
1219                 data_set_t *ds = value;
1220                 /* key is a pointer to ds->type */
1222                 sfree (ds->ds);
1223                 sfree (ds);
1224         }
1226         c_avl_destroy (data_sets);
1227         data_sets = NULL;
1228 } /* void plugin_free_data_sets */
1230 int plugin_register_data_set (const data_set_t *ds)
1232         data_set_t *ds_copy;
1233         int i;
1235         if ((data_sets != NULL)
1236                         && (c_avl_get (data_sets, ds->type, NULL) == 0))
1237         {
1238                 NOTICE ("Replacing DS `%s' with another version.", ds->type);
1239                 plugin_unregister_data_set (ds->type);
1240         }
1241         else if (data_sets == NULL)
1242         {
1243                 data_sets = c_avl_create ((int (*) (const void *, const void *)) strcmp);
1244                 if (data_sets == NULL)
1245                         return (-1);
1246         }
1248         ds_copy = (data_set_t *) malloc (sizeof (data_set_t));
1249         if (ds_copy == NULL)
1250                 return (-1);
1251         memcpy(ds_copy, ds, sizeof (data_set_t));
1253         ds_copy->ds = (data_source_t *) malloc (sizeof (data_source_t)
1254                         * ds->ds_num);
1255         if (ds_copy->ds == NULL)
1256         {
1257                 free (ds_copy);
1258                 return (-1);
1259         }
1261         for (i = 0; i < ds->ds_num; i++)
1262                 memcpy (ds_copy->ds + i, ds->ds + i, sizeof (data_source_t));
1264         return (c_avl_insert (data_sets, (void *) ds_copy->type, (void *) ds_copy));
1265 } /* int plugin_register_data_set */
1267 int plugin_register_log (const char *name,
1268                 plugin_log_cb callback, user_data_t *ud)
1270         return (create_register_callback (&list_log, name,
1271                                 (void *) callback, ud));
1272 } /* int plugin_register_log */
1274 int plugin_register_notification (const char *name,
1275                 plugin_notification_cb callback, user_data_t *ud)
1277         return (create_register_callback (&list_notification, name,
1278                                 (void *) callback, ud));
1279 } /* int plugin_register_log */
1281 int plugin_unregister_config (const char *name)
1283         cf_unregister (name);
1284         return (0);
1285 } /* int plugin_unregister_config */
1287 int plugin_unregister_complex_config (const char *name)
1289         cf_unregister_complex (name);
1290         return (0);
1291 } /* int plugin_unregister_complex_config */
1293 int plugin_unregister_init (const char *name)
1295         return (plugin_unregister (list_init, name));
1298 int plugin_unregister_read (const char *name) /* {{{ */
1300         llentry_t *le;
1301         read_func_t *rf;
1303         if (name == NULL)
1304                 return (-ENOENT);
1306         pthread_mutex_lock (&read_lock);
1308         if (read_list == NULL)
1309         {
1310                 pthread_mutex_unlock (&read_lock);
1311                 return (-ENOENT);
1312         }
1314         le = llist_search (read_list, name);
1315         if (le == NULL)
1316         {
1317                 pthread_mutex_unlock (&read_lock);
1318                 WARNING ("plugin_unregister_read: No such read function: %s",
1319                                 name);
1320                 return (-ENOENT);
1321         }
1323         llist_remove (read_list, le);
1325         rf = le->value;
1326         assert (rf != NULL);
1327         rf->rf_type = RF_REMOVE;
1329         pthread_mutex_unlock (&read_lock);
1331         llentry_destroy (le);
1333         DEBUG ("plugin_unregister_read: Marked `%s' for removal.", name);
1335         return (0);
1336 } /* }}} int plugin_unregister_read */
1338 static int compare_read_func_group (llentry_t *e, void *ud) /* {{{ */
1340         read_func_t *rf    = e->value;
1341         char        *group = ud;
1343         return strcmp (rf->rf_group, (const char *)group);
1344 } /* }}} int compare_read_func_group */
1346 int plugin_unregister_read_group (const char *group) /* {{{ */
1348         llentry_t *le;
1349         read_func_t *rf;
1351         int found = 0;
1353         if (group == NULL)
1354                 return (-ENOENT);
1356         pthread_mutex_lock (&read_lock);
1358         if (read_list == NULL)
1359         {
1360                 pthread_mutex_unlock (&read_lock);
1361                 return (-ENOENT);
1362         }
1364         while (42)
1365         {
1366                 le = llist_search_custom (read_list,
1367                                 compare_read_func_group, (void *)group);
1369                 if (le == NULL)
1370                         break;
1372                 ++found;
1374                 llist_remove (read_list, le);
1376                 rf = le->value;
1377                 assert (rf != NULL);
1378                 rf->rf_type = RF_REMOVE;
1380                 llentry_destroy (le);
1382                 DEBUG ("plugin_unregister_read_group: "
1383                                 "Marked `%s' (group `%s') for removal.",
1384                                 rf->rf_name, group);
1385         }
1387         pthread_mutex_unlock (&read_lock);
1389         if (found == 0)
1390         {
1391                 WARNING ("plugin_unregister_read_group: No such "
1392                                 "group of read function: %s", group);
1393                 return (-ENOENT);
1394         }
1396         return (0);
1397 } /* }}} int plugin_unregister_read_group */
1399 int plugin_unregister_write (const char *name)
1401         return (plugin_unregister (list_write, name));
1404 int plugin_unregister_flush (const char *name)
1406         return (plugin_unregister (list_flush, name));
1409 int plugin_unregister_missing (const char *name)
1411         return (plugin_unregister (list_missing, name));
1414 int plugin_unregister_shutdown (const char *name)
1416         return (plugin_unregister (list_shutdown, name));
1419 int plugin_unregister_data_set (const char *name)
1421         data_set_t *ds;
1423         if (data_sets == NULL)
1424                 return (-1);
1426         if (c_avl_remove (data_sets, name, NULL, (void *) &ds) != 0)
1427                 return (-1);
1429         sfree (ds->ds);
1430         sfree (ds);
1432         return (0);
1433 } /* int plugin_unregister_data_set */
1435 int plugin_unregister_log (const char *name)
1437         return (plugin_unregister (list_log, name));
1440 int plugin_unregister_notification (const char *name)
1442         return (plugin_unregister (list_notification, name));
1445 void plugin_init_all (void)
1447         const char *chain_name;
1448         llentry_t *le;
1449         int status;
1451         /* Init the value cache */
1452         uc_init ();
1454         chain_name = global_option_get ("PreCacheChain");
1455         pre_cache_chain = fc_chain_get_by_name (chain_name);
1457         chain_name = global_option_get ("PostCacheChain");
1458         post_cache_chain = fc_chain_get_by_name (chain_name);
1460         {
1461                 char const *tmp = global_option_get ("WriteThreads");
1462                 int num = atoi (tmp);
1464                 if (num < 1)
1465                         num = 5;
1467                 start_write_threads ((size_t) num);
1468         }
1470         if ((list_init == NULL) && (read_heap == NULL))
1471                 return;
1473         /* Calling all init callbacks before checking if read callbacks
1474          * are available allows the init callbacks to register the read
1475          * callback. */
1476         le = llist_head (list_init);
1477         while (le != NULL)
1478         {
1479                 callback_func_t *cf;
1480                 plugin_init_cb callback;
1481                 plugin_ctx_t old_ctx;
1483                 cf = le->value;
1484                 old_ctx = plugin_set_ctx (cf->cf_ctx);
1485                 callback = cf->cf_callback;
1486                 status = (*callback) ();
1487                 plugin_set_ctx (old_ctx);
1489                 if (status != 0)
1490                 {
1491                         ERROR ("Initialization of plugin `%s' "
1492                                         "failed with status %i. "
1493                                         "Plugin will be unloaded.",
1494                                         le->key, status);
1495                         /* Plugins that register read callbacks from the init
1496                          * callback should take care of appropriate error
1497                          * handling themselves. */
1498                         /* FIXME: Unload _all_ functions */
1499                         plugin_unregister_read (le->key);
1500                 }
1502                 le = le->next;
1503         }
1505         /* Start read-threads */
1506         if (read_heap != NULL)
1507         {
1508                 const char *rt;
1509                 int num;
1510                 rt = global_option_get ("ReadThreads");
1511                 num = atoi (rt);
1512                 if (num != -1)
1513                         start_read_threads ((num > 0) ? num : 5);
1514         }
1515 } /* void plugin_init_all */
1517 /* TODO: Rename this function. */
1518 void plugin_read_all (void)
1520         uc_check_timeout ();
1522         return;
1523 } /* void plugin_read_all */
1525 /* Read function called when the `-T' command line argument is given. */
1526 int plugin_read_all_once (void)
1528         int status;
1529         int return_status = 0;
1531         if (read_heap == NULL)
1532         {
1533                 NOTICE ("No read-functions are registered.");
1534                 return (0);
1535         }
1537         while (42)
1538         {
1539                 read_func_t *rf;
1540                 plugin_ctx_t old_ctx;
1542                 rf = c_heap_get_root (read_heap);
1543                 if (rf == NULL)
1544                         break;
1546                 old_ctx = plugin_set_ctx (rf->rf_ctx);
1548                 if (rf->rf_type == RF_SIMPLE)
1549                 {
1550                         int (*callback) (void);
1552                         callback = rf->rf_callback;
1553                         status = (*callback) ();
1554                 }
1555                 else
1556                 {
1557                         plugin_read_cb callback;
1559                         callback = rf->rf_callback;
1560                         status = (*callback) (&rf->rf_udata);
1561                 }
1563                 plugin_set_ctx (old_ctx);
1565                 if (status != 0)
1566                 {
1567                         NOTICE ("read-function of plugin `%s' failed.",
1568                                         rf->rf_name);
1569                         return_status = -1;
1570                 }
1572                 destroy_callback ((void *) rf);
1573         }
1575         return (return_status);
1576 } /* int plugin_read_all_once */
1578 int plugin_write (const char *plugin, /* {{{ */
1579                 const data_set_t *ds, const value_list_t *vl)
1581   llentry_t *le;
1582   int status;
1584   if (vl == NULL)
1585     return (EINVAL);
1587   if (list_write == NULL)
1588     return (ENOENT);
1590   if (ds == NULL)
1591   {
1592     ds = plugin_get_ds (vl->type);
1593     if (ds == NULL)
1594     {
1595       ERROR ("plugin_write: Unable to lookup type `%s'.", vl->type);
1596       return (ENOENT);
1597     }
1598   }
1600   if (plugin == NULL)
1601   {
1602     int success = 0;
1603     int failure = 0;
1605     le = llist_head (list_write);
1606     while (le != NULL)
1607     {
1608       callback_func_t *cf = le->value;
1609       plugin_write_cb callback;
1611       /* do not switch plugin context; rather keep the context (interval)
1612        * information of the calling read plugin */
1614       DEBUG ("plugin: plugin_write: Writing values via %s.", le->key);
1615       callback = cf->cf_callback;
1616       status = (*callback) (ds, vl, &cf->cf_udata);
1617       if (status != 0)
1618         failure++;
1619       else
1620         success++;
1622       le = le->next;
1623     }
1625     if ((success == 0) && (failure != 0))
1626       status = -1;
1627     else
1628       status = 0;
1629   }
1630   else /* plugin != NULL */
1631   {
1632     callback_func_t *cf;
1633     plugin_write_cb callback;
1635     le = llist_head (list_write);
1636     while (le != NULL)
1637     {
1638       if (strcasecmp (plugin, le->key) == 0)
1639         break;
1641       le = le->next;
1642     }
1644     if (le == NULL)
1645       return (ENOENT);
1647     cf = le->value;
1649     /* do not switch plugin context; rather keep the context (interval)
1650      * information of the calling read plugin */
1652     DEBUG ("plugin: plugin_write: Writing values via %s.", le->key);
1653     callback = cf->cf_callback;
1654     status = (*callback) (ds, vl, &cf->cf_udata);
1655   }
1657   return (status);
1658 } /* }}} int plugin_write */
1660 int plugin_flush (const char *plugin, cdtime_t timeout, const char *identifier)
1662   llentry_t *le;
1664   if (list_flush == NULL)
1665     return (0);
1667   le = llist_head (list_flush);
1668   while (le != NULL)
1669   {
1670     callback_func_t *cf;
1671     plugin_flush_cb callback;
1672     plugin_ctx_t old_ctx;
1674     if ((plugin != NULL)
1675         && (strcmp (plugin, le->key) != 0))
1676     {
1677       le = le->next;
1678       continue;
1679     }
1681     cf = le->value;
1682     old_ctx = plugin_set_ctx (cf->cf_ctx);
1683     callback = cf->cf_callback;
1685     (*callback) (timeout, identifier, &cf->cf_udata);
1687     plugin_set_ctx (old_ctx);
1689     le = le->next;
1690   }
1691   return (0);
1692 } /* int plugin_flush */
1694 void plugin_shutdown_all (void)
1696         llentry_t *le;
1698         stop_read_threads ();
1700         destroy_all_callbacks (&list_init);
1702         pthread_mutex_lock (&read_lock);
1703         llist_destroy (read_list);
1704         read_list = NULL;
1705         pthread_mutex_unlock (&read_lock);
1707         destroy_read_heap ();
1709         plugin_flush (/* plugin = */ NULL,
1710                         /* timeout = */ 0,
1711                         /* identifier = */ NULL);
1713         le = NULL;
1714         if (list_shutdown != NULL)
1715                 le = llist_head (list_shutdown);
1717         while (le != NULL)
1718         {
1719                 callback_func_t *cf;
1720                 plugin_shutdown_cb callback;
1721                 plugin_ctx_t old_ctx;
1723                 cf = le->value;
1724                 old_ctx = plugin_set_ctx (cf->cf_ctx);
1725                 callback = cf->cf_callback;
1727                 /* Advance the pointer before calling the callback allows
1728                  * shutdown functions to unregister themselves. If done the
1729                  * other way around the memory `le' points to will be freed
1730                  * after callback returns. */
1731                 le = le->next;
1733                 (*callback) ();
1735                 plugin_set_ctx (old_ctx);
1736         }
1738         stop_write_threads ();
1740         /* Write plugins which use the `user_data' pointer usually need the
1741          * same data available to the flush callback. If this is the case, set
1742          * the free_function to NULL when registering the flush callback and to
1743          * the real free function when registering the write callback. This way
1744          * the data isn't freed twice. */
1745         destroy_all_callbacks (&list_flush);
1746         destroy_all_callbacks (&list_missing);
1747         destroy_all_callbacks (&list_write);
1749         destroy_all_callbacks (&list_notification);
1750         destroy_all_callbacks (&list_shutdown);
1751         destroy_all_callbacks (&list_log);
1753         plugin_free_loaded ();
1754         plugin_free_data_sets ();
1755 } /* void plugin_shutdown_all */
1757 int plugin_dispatch_missing (const value_list_t *vl) /* {{{ */
1759   llentry_t *le;
1761   if (list_missing == NULL)
1762     return (0);
1764   le = llist_head (list_missing);
1765   while (le != NULL)
1766   {
1767     callback_func_t *cf;
1768     plugin_missing_cb callback;
1769     plugin_ctx_t old_ctx;
1770     int status;
1772     cf = le->value;
1773     old_ctx = plugin_set_ctx (cf->cf_ctx);
1774     callback = cf->cf_callback;
1776     status = (*callback) (vl, &cf->cf_udata);
1777     plugin_set_ctx (old_ctx);
1778     if (status != 0)
1779     {
1780       if (status < 0)
1781       {
1782         ERROR ("plugin_dispatch_missing: Callback function \"%s\" "
1783             "failed with status %i.",
1784             le->key, status);
1785         return (status);
1786       }
1787       else
1788       {
1789         return (0);
1790       }
1791     }
1793     le = le->next;
1794   }
1795   return (0);
1796 } /* int }}} plugin_dispatch_missing */
1798 static int plugin_dispatch_values_internal (value_list_t *vl)
1800         int status;
1801         static c_complain_t no_write_complaint = C_COMPLAIN_INIT_STATIC;
1803         value_t *saved_values;
1804         int      saved_values_len;
1806         data_set_t *ds;
1808         int free_meta_data = 0;
1810         if ((vl == NULL) || (vl->type[0] == 0)
1811                         || (vl->values == NULL) || (vl->values_len < 1))
1812         {
1813                 ERROR ("plugin_dispatch_values: Invalid value list "
1814                                 "from plugin %s.", vl->plugin);
1815                 return (-1);
1816         }
1818         /* Free meta data only if the calling function didn't specify any. In
1819          * this case matches and targets may add some and the calling function
1820          * may not expect (and therefore free) that data. */
1821         if (vl->meta == NULL)
1822                 free_meta_data = 1;
1824         if (list_write == NULL)
1825                 c_complain_once (LOG_WARNING, &no_write_complaint,
1826                                 "plugin_dispatch_values: No write callback has been "
1827                                 "registered. Please load at least one output plugin, "
1828                                 "if you want the collected data to be stored.");
1830         if (data_sets == NULL)
1831         {
1832                 ERROR ("plugin_dispatch_values: No data sets registered. "
1833                                 "Could the types database be read? Check "
1834                                 "your `TypesDB' setting!");
1835                 return (-1);
1836         }
1838         if (c_avl_get (data_sets, vl->type, (void *) &ds) != 0)
1839         {
1840                 char ident[6 * DATA_MAX_NAME_LEN];
1842                 FORMAT_VL (ident, sizeof (ident), vl);
1843                 INFO ("plugin_dispatch_values: Dataset not found: %s "
1844                                 "(from \"%s\"), check your types.db!",
1845                                 vl->type, ident);
1846                 return (-1);
1847         }
1849         /* Assured by plugin_value_list_clone(). The time is determined at
1850          * _enqueue_ time. */
1851         assert (vl->time != 0);
1852         assert (vl->interval != 0);
1854         DEBUG ("plugin_dispatch_values: time = %.3f; interval = %.3f; "
1855                         "host = %s; "
1856                         "plugin = %s; plugin_instance = %s; "
1857                         "type = %s; type_instance = %s;",
1858                         CDTIME_T_TO_DOUBLE (vl->time),
1859                         CDTIME_T_TO_DOUBLE (vl->interval),
1860                         vl->host,
1861                         vl->plugin, vl->plugin_instance,
1862                         vl->type, vl->type_instance);
1864 #if COLLECT_DEBUG
1865         assert (0 == strcmp (ds->type, vl->type));
1866 #else
1867         if (0 != strcmp (ds->type, vl->type))
1868                 WARNING ("plugin_dispatch_values: (ds->type = %s) != (vl->type = %s)",
1869                                 ds->type, vl->type);
1870 #endif
1872 #if COLLECT_DEBUG
1873         assert (ds->ds_num == vl->values_len);
1874 #else
1875         if (ds->ds_num != vl->values_len)
1876         {
1877                 ERROR ("plugin_dispatch_values: ds->type = %s: "
1878                                 "(ds->ds_num = %i) != "
1879                                 "(vl->values_len = %i)",
1880                                 ds->type, ds->ds_num, vl->values_len);
1881                 return (-1);
1882         }
1883 #endif
1885         escape_slashes (vl->host, sizeof (vl->host));
1886         escape_slashes (vl->plugin, sizeof (vl->plugin));
1887         escape_slashes (vl->plugin_instance, sizeof (vl->plugin_instance));
1888         escape_slashes (vl->type, sizeof (vl->type));
1889         escape_slashes (vl->type_instance, sizeof (vl->type_instance));
1891         /* Copy the values. This way, we can assure `targets' that they get
1892          * dynamically allocated values, which they can free and replace if
1893          * they like. */
1894         if ((pre_cache_chain != NULL) || (post_cache_chain != NULL))
1895         {
1896                 saved_values     = vl->values;
1897                 saved_values_len = vl->values_len;
1899                 vl->values = (value_t *) calloc (vl->values_len,
1900                                 sizeof (*vl->values));
1901                 if (vl->values == NULL)
1902                 {
1903                         ERROR ("plugin_dispatch_values: calloc failed.");
1904                         vl->values = saved_values;
1905                         return (-1);
1906                 }
1907                 memcpy (vl->values, saved_values,
1908                                 vl->values_len * sizeof (*vl->values));
1909         }
1910         else /* if ((pre == NULL) && (post == NULL)) */
1911         {
1912                 saved_values     = NULL;
1913                 saved_values_len = 0;
1914         }
1916         if (pre_cache_chain != NULL)
1917         {
1918                 status = fc_process_chain (ds, vl, pre_cache_chain);
1919                 if (status < 0)
1920                 {
1921                         WARNING ("plugin_dispatch_values: Running the "
1922                                         "pre-cache chain failed with "
1923                                         "status %i (%#x).",
1924                                         status, status);
1925                 }
1926                 else if (status == FC_TARGET_STOP)
1927                 {
1928                         /* Restore the state of the value_list so that plugins
1929                          * don't get confused.. */
1930                         if (saved_values != NULL)
1931                         {
1932                                 free (vl->values);
1933                                 vl->values     = saved_values;
1934                                 vl->values_len = saved_values_len;
1935                         }
1936                         return (0);
1937                 }
1938         }
1940         /* Update the value cache */
1941         uc_update (ds, vl);
1943         if (post_cache_chain != NULL)
1944         {
1945                 status = fc_process_chain (ds, vl, post_cache_chain);
1946                 if (status < 0)
1947                 {
1948                         WARNING ("plugin_dispatch_values: Running the "
1949                                         "post-cache chain failed with "
1950                                         "status %i (%#x).",
1951                                         status, status);
1952                 }
1953         }
1954         else
1955                 fc_default_action (ds, vl);
1957         /* Restore the state of the value_list so that plugins don't get
1958          * confused.. */
1959         if (saved_values != NULL)
1960         {
1961                 free (vl->values);
1962                 vl->values     = saved_values;
1963                 vl->values_len = saved_values_len;
1964         }
1966         if ((free_meta_data != 0) && (vl->meta != NULL))
1967         {
1968                 meta_data_destroy (vl->meta);
1969                 vl->meta = NULL;
1970         }
1972         return (0);
1973 } /* int plugin_dispatch_values_internal */
1975 int plugin_dispatch_values (value_list_t const *vl)
1977         int status;
1979         status = plugin_write_enqueue (vl);
1980         if (status != 0)
1981         {
1982                 char errbuf[1024];
1983                 ERROR ("plugin_dispatch_values: plugin_write_enqueue failed "
1984                                 "with status %i (%s).", status,
1985                                 sstrerror (status, errbuf, sizeof (errbuf)));
1986                 return (status);
1987         }
1989         return (0);
1992 int plugin_dispatch_notification (const notification_t *notif)
1994         llentry_t *le;
1995         /* Possible TODO: Add flap detection here */
1997         DEBUG ("plugin_dispatch_notification: severity = %i; message = %s; "
1998                         "time = %.3f; host = %s;",
1999                         notif->severity, notif->message,
2000                         CDTIME_T_TO_DOUBLE (notif->time), notif->host);
2002         /* Nobody cares for notifications */
2003         if (list_notification == NULL)
2004                 return (-1);
2006         le = llist_head (list_notification);
2007         while (le != NULL)
2008         {
2009                 callback_func_t *cf;
2010                 plugin_notification_cb callback;
2011                 int status;
2013                 /* do not switch plugin context; rather keep the context
2014                  * (interval) information of the calling plugin */
2016                 cf = le->value;
2017                 callback = cf->cf_callback;
2018                 status = (*callback) (notif, &cf->cf_udata);
2019                 if (status != 0)
2020                 {
2021                         WARNING ("plugin_dispatch_notification: Notification "
2022                                         "callback %s returned %i.",
2023                                         le->key, status);
2024                 }
2026                 le = le->next;
2027         }
2029         return (0);
2030 } /* int plugin_dispatch_notification */
2032 void plugin_log (int level, const char *format, ...)
2034         char msg[1024];
2035         va_list ap;
2036         llentry_t *le;
2038 #if !COLLECT_DEBUG
2039         if (level >= LOG_DEBUG)
2040                 return;
2041 #endif
2043         va_start (ap, format);
2044         vsnprintf (msg, sizeof (msg), format, ap);
2045         msg[sizeof (msg) - 1] = '\0';
2046         va_end (ap);
2048         if (list_log == NULL)
2049         {
2050                 fprintf (stderr, "%s\n", msg);
2051                 return;
2052         }
2054         le = llist_head (list_log);
2055         while (le != NULL)
2056         {
2057                 callback_func_t *cf;
2058                 plugin_log_cb callback;
2060                 cf = le->value;
2061                 callback = cf->cf_callback;
2063                 /* do not switch plugin context; rather keep the context
2064                  * (interval) information of the calling plugin */
2066                 (*callback) (level, msg, &cf->cf_udata);
2068                 le = le->next;
2069         }
2070 } /* void plugin_log */
2072 int parse_log_severity (const char *severity)
2074         int log_level = -1;
2076         if ((0 == strcasecmp (severity, "emerg"))
2077                         || (0 == strcasecmp (severity, "alert"))
2078                         || (0 == strcasecmp (severity, "crit"))
2079                         || (0 == strcasecmp (severity, "err")))
2080                 log_level = LOG_ERR;
2081         else if (0 == strcasecmp (severity, "warning"))
2082                 log_level = LOG_WARNING;
2083         else if (0 == strcasecmp (severity, "notice"))
2084                 log_level = LOG_NOTICE;
2085         else if (0 == strcasecmp (severity, "info"))
2086                 log_level = LOG_INFO;
2087 #if COLLECT_DEBUG
2088         else if (0 == strcasecmp (severity, "debug"))
2089                 log_level = LOG_DEBUG;
2090 #endif /* COLLECT_DEBUG */
2092         return (log_level);
2093 } /* int parse_log_severity */
2095 int parse_notif_severity (const char *severity)
2097         int notif_severity = -1;
2099         if (strcasecmp (severity, "FAILURE") == 0)
2100                 notif_severity = NOTIF_FAILURE;
2101         else if (strcmp (severity, "OKAY") == 0)
2102                 notif_severity = NOTIF_OKAY;
2103         else if ((strcmp (severity, "WARNING") == 0)
2104                         || (strcmp (severity, "WARN") == 0))
2105                 notif_severity = NOTIF_WARNING;
2107         return (notif_severity);
2108 } /* int parse_notif_severity */
2110 const data_set_t *plugin_get_ds (const char *name)
2112         data_set_t *ds;
2114         if (data_sets == NULL)
2115         {
2116                 ERROR ("plugin_get_ds: No data sets are defined yet.");
2117                 return (NULL);
2118         }
2120         if (c_avl_get (data_sets, name, (void *) &ds) != 0)
2121         {
2122                 DEBUG ("No such dataset registered: %s", name);
2123                 return (NULL);
2124         }
2126         return (ds);
2127 } /* data_set_t *plugin_get_ds */
2129 static int plugin_notification_meta_add (notification_t *n,
2130     const char *name,
2131     enum notification_meta_type_e type,
2132     const void *value)
2134   notification_meta_t *meta;
2135   notification_meta_t *tail;
2137   if ((n == NULL) || (name == NULL) || (value == NULL))
2138   {
2139     ERROR ("plugin_notification_meta_add: A pointer is NULL!");
2140     return (-1);
2141   }
2143   meta = (notification_meta_t *) malloc (sizeof (notification_meta_t));
2144   if (meta == NULL)
2145   {
2146     ERROR ("plugin_notification_meta_add: malloc failed.");
2147     return (-1);
2148   }
2149   memset (meta, 0, sizeof (notification_meta_t));
2151   sstrncpy (meta->name, name, sizeof (meta->name));
2152   meta->type = type;
2154   switch (type)
2155   {
2156     case NM_TYPE_STRING:
2157     {
2158       meta->nm_value.nm_string = strdup ((const char *) value);
2159       if (meta->nm_value.nm_string == NULL)
2160       {
2161         ERROR ("plugin_notification_meta_add: strdup failed.");
2162         sfree (meta);
2163         return (-1);
2164       }
2165       break;
2166     }
2167     case NM_TYPE_SIGNED_INT:
2168     {
2169       meta->nm_value.nm_signed_int = *((int64_t *) value);
2170       break;
2171     }
2172     case NM_TYPE_UNSIGNED_INT:
2173     {
2174       meta->nm_value.nm_unsigned_int = *((uint64_t *) value);
2175       break;
2176     }
2177     case NM_TYPE_DOUBLE:
2178     {
2179       meta->nm_value.nm_double = *((double *) value);
2180       break;
2181     }
2182     case NM_TYPE_BOOLEAN:
2183     {
2184       meta->nm_value.nm_boolean = *((_Bool *) value);
2185       break;
2186     }
2187     default:
2188     {
2189       ERROR ("plugin_notification_meta_add: Unknown type: %i", type);
2190       sfree (meta);
2191       return (-1);
2192     }
2193   } /* switch (type) */
2195   meta->next = NULL;
2196   tail = n->meta;
2197   while ((tail != NULL) && (tail->next != NULL))
2198     tail = tail->next;
2200   if (tail == NULL)
2201     n->meta = meta;
2202   else
2203     tail->next = meta;
2205   return (0);
2206 } /* int plugin_notification_meta_add */
2208 int plugin_notification_meta_add_string (notification_t *n,
2209     const char *name,
2210     const char *value)
2212   return (plugin_notification_meta_add (n, name, NM_TYPE_STRING, value));
2215 int plugin_notification_meta_add_signed_int (notification_t *n,
2216     const char *name,
2217     int64_t value)
2219   return (plugin_notification_meta_add (n, name, NM_TYPE_SIGNED_INT, &value));
2222 int plugin_notification_meta_add_unsigned_int (notification_t *n,
2223     const char *name,
2224     uint64_t value)
2226   return (plugin_notification_meta_add (n, name, NM_TYPE_UNSIGNED_INT, &value));
2229 int plugin_notification_meta_add_double (notification_t *n,
2230     const char *name,
2231     double value)
2233   return (plugin_notification_meta_add (n, name, NM_TYPE_DOUBLE, &value));
2236 int plugin_notification_meta_add_boolean (notification_t *n,
2237     const char *name,
2238     _Bool value)
2240   return (plugin_notification_meta_add (n, name, NM_TYPE_BOOLEAN, &value));
2243 int plugin_notification_meta_copy (notification_t *dst,
2244     const notification_t *src)
2246   notification_meta_t *meta;
2248   assert (dst != NULL);
2249   assert (src != NULL);
2250   assert (dst != src);
2251   assert ((src->meta == NULL) || (src->meta != dst->meta));
2253   for (meta = src->meta; meta != NULL; meta = meta->next)
2254   {
2255     if (meta->type == NM_TYPE_STRING)
2256       plugin_notification_meta_add_string (dst, meta->name,
2257           meta->nm_value.nm_string);
2258     else if (meta->type == NM_TYPE_SIGNED_INT)
2259       plugin_notification_meta_add_signed_int (dst, meta->name,
2260           meta->nm_value.nm_signed_int);
2261     else if (meta->type == NM_TYPE_UNSIGNED_INT)
2262       plugin_notification_meta_add_unsigned_int (dst, meta->name,
2263           meta->nm_value.nm_unsigned_int);
2264     else if (meta->type == NM_TYPE_DOUBLE)
2265       plugin_notification_meta_add_double (dst, meta->name,
2266           meta->nm_value.nm_double);
2267     else if (meta->type == NM_TYPE_BOOLEAN)
2268       plugin_notification_meta_add_boolean (dst, meta->name,
2269           meta->nm_value.nm_boolean);
2270   }
2272   return (0);
2273 } /* int plugin_notification_meta_copy */
2275 int plugin_notification_meta_free (notification_meta_t *n)
2277   notification_meta_t *this;
2278   notification_meta_t *next;
2280   if (n == NULL)
2281   {
2282     ERROR ("plugin_notification_meta_free: n == NULL!");
2283     return (-1);
2284   }
2286   this = n;
2287   while (this != NULL)
2288   {
2289     next = this->next;
2291     if (this->type == NM_TYPE_STRING)
2292     {
2293       free ((char *)this->nm_value.nm_string);
2294       this->nm_value.nm_string = NULL;
2295     }
2296     sfree (this);
2298     this = next;
2299   }
2301   return (0);
2302 } /* int plugin_notification_meta_free */
2304 static void plugin_ctx_destructor (void *ctx)
2306         sfree (ctx);
2307 } /* void plugin_ctx_destructor */
2309 static plugin_ctx_t ctx_init = { /* interval = */ 0 };
2311 static plugin_ctx_t *plugin_ctx_create (void)
2313         plugin_ctx_t *ctx;
2315         ctx = malloc (sizeof (*ctx));
2316         if (ctx == NULL) {
2317                 char errbuf[1024];
2318                 ERROR ("Failed to allocate plugin context: %s",
2319                                 sstrerror (errno, errbuf, sizeof (errbuf)));
2320                 return NULL;
2321         }
2323         *ctx = ctx_init;
2324         assert (plugin_ctx_key_initialized);
2325         pthread_setspecific (plugin_ctx_key, ctx);
2326         DEBUG("Created new plugin context.");
2327         return (ctx);
2328 } /* int plugin_ctx_create */
2330 void plugin_init_ctx (void)
2332         pthread_key_create (&plugin_ctx_key, plugin_ctx_destructor);
2333         plugin_ctx_key_initialized = 1;
2334 } /* void plugin_init_ctx */
2336 plugin_ctx_t plugin_get_ctx (void)
2338         plugin_ctx_t *ctx;
2340         assert (plugin_ctx_key_initialized);
2341         ctx = pthread_getspecific (plugin_ctx_key);
2343         if (ctx == NULL) {
2344                 ctx = plugin_ctx_create ();
2345                 /* this must no happen -- exit() instead? */
2346                 if (ctx == NULL)
2347                         return ctx_init;
2348         }
2350         return (*ctx);
2351 } /* plugin_ctx_t plugin_get_ctx */
2353 plugin_ctx_t plugin_set_ctx (plugin_ctx_t ctx)
2355         plugin_ctx_t *c;
2356         plugin_ctx_t old;
2358         assert (plugin_ctx_key_initialized);
2359         c = pthread_getspecific (plugin_ctx_key);
2361         if (c == NULL) {
2362                 c = plugin_ctx_create ();
2363                 /* this must no happen -- exit() instead? */
2364                 if (c == NULL)
2365                         return ctx_init;
2366         }
2368         old = *c;
2369         *c = ctx;
2371         return (old);
2372 } /* void plugin_set_ctx */
2374 cdtime_t plugin_get_interval (void)
2376         cdtime_t interval;
2378         interval = plugin_get_ctx().interval;
2379         if (interval > 0)
2380                 return interval;
2382         return cf_get_default_interval ();
2383 } /* cdtime_t plugin_get_interval */
2385 typedef struct {
2386         plugin_ctx_t ctx;
2387         void *(*start_routine) (void *);
2388         void *arg;
2389 } plugin_thread_t;
2391 static void *plugin_thread_start (void *arg)
2393         plugin_thread_t *plugin_thread = arg;
2395         void *(*start_routine) (void *) = plugin_thread->start_routine;
2396         void *plugin_arg = plugin_thread->arg;
2398         plugin_set_ctx (plugin_thread->ctx);
2400         free (plugin_thread);
2402         return start_routine (plugin_arg);
2403 } /* void *plugin_thread_start */
2405 int plugin_thread_create (pthread_t *thread, const pthread_attr_t *attr,
2406                 void *(*start_routine) (void *), void *arg)
2408         plugin_thread_t *plugin_thread;
2410         plugin_thread = malloc (sizeof (*plugin_thread));
2411         if (plugin_thread == NULL)
2412                 return -1;
2414         plugin_thread->ctx           = plugin_get_ctx ();
2415         plugin_thread->start_routine = start_routine;
2416         plugin_thread->arg           = arg;
2418         return pthread_create (thread, attr,
2419                         plugin_thread_start, plugin_thread);
2420 } /* int plugin_thread_create */
2422 /* vim: set sw=8 ts=8 noet fdm=marker : */