Code

Merge remote-tracking branch 'github/pr/2006'
[collectd.git] / src / daemon / plugin.c
1 /**
2  * collectd - src/plugin.c
3  * Copyright (C) 2005-2014  Florian octo Forster
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Florian octo Forster <octo at collectd.org>
25  *   Sebastian Harl <sh at tokkee.org>
26  **/
28 #include "collectd.h"
30 #include "common.h"
31 #include "plugin.h"
32 #include "configfile.h"
33 #include "filter_chain.h"
34 #include "utils_avltree.h"
35 #include "utils_cache.h"
36 #include "utils_complain.h"
37 #include "utils_llist.h"
38 #include "utils_heap.h"
39 #include "utils_time.h"
40 #include "utils_random.h"
42 #include <ltdl.h>
44 /*
45  * Private structures
46  */
47 struct callback_func_s
48 {
49         void *cf_callback;
50         user_data_t cf_udata;
51         plugin_ctx_t cf_ctx;
52 };
53 typedef struct callback_func_s callback_func_t;
55 #define RF_SIMPLE  0
56 #define RF_COMPLEX 1
57 #define RF_REMOVE  65535
58 struct read_func_s
59 {
60         /* `read_func_t' "inherits" from `callback_func_t'.
61          * The `rf_super' member MUST be the first one in this structure! */
62 #define rf_callback rf_super.cf_callback
63 #define rf_udata rf_super.cf_udata
64 #define rf_ctx rf_super.cf_ctx
65         callback_func_t rf_super;
66         char rf_group[DATA_MAX_NAME_LEN];
67         char *rf_name;
68         int rf_type;
69         cdtime_t rf_interval;
70         cdtime_t rf_effective_interval;
71         cdtime_t rf_next_read;
72 };
73 typedef struct read_func_s read_func_t;
75 struct write_queue_s;
76 typedef struct write_queue_s write_queue_t;
77 struct write_queue_s
78 {
79         value_list_t *vl;
80         plugin_ctx_t ctx;
81         write_queue_t *next;
82 };
84 struct flush_callback_s {
85         char *name;
86         cdtime_t timeout;
87 };
88 typedef struct flush_callback_s flush_callback_t;
90 /*
91  * Private variables
92  */
93 static c_avl_tree_t *plugins_loaded = NULL;
95 static llist_t *list_init;
96 static llist_t *list_write;
97 static llist_t *list_flush;
98 static llist_t *list_missing;
99 static llist_t *list_shutdown;
100 static llist_t *list_log;
101 static llist_t *list_notification;
103 static fc_chain_t *pre_cache_chain = NULL;
104 static fc_chain_t *post_cache_chain = NULL;
106 static c_avl_tree_t *data_sets;
108 static char *plugindir = NULL;
110 #ifndef DEFAULT_MAX_READ_INTERVAL
111 # define DEFAULT_MAX_READ_INTERVAL TIME_T_TO_CDTIME_T_STATIC (86400)
112 #endif
113 static c_heap_t       *read_heap = NULL;
114 static llist_t        *read_list;
115 static int             read_loop = 1;
116 static pthread_mutex_t read_lock = PTHREAD_MUTEX_INITIALIZER;
117 static pthread_cond_t  read_cond = PTHREAD_COND_INITIALIZER;
118 static pthread_t      *read_threads = NULL;
119 static int             read_threads_num = 0;
120 static cdtime_t        max_read_interval = DEFAULT_MAX_READ_INTERVAL;
122 static write_queue_t  *write_queue_head;
123 static write_queue_t  *write_queue_tail;
124 static long            write_queue_length = 0;
125 static _Bool           write_loop = 1;
126 static pthread_mutex_t write_lock = PTHREAD_MUTEX_INITIALIZER;
127 static pthread_cond_t  write_cond = PTHREAD_COND_INITIALIZER;
128 static pthread_t      *write_threads = NULL;
129 static size_t          write_threads_num = 0;
131 static pthread_key_t   plugin_ctx_key;
132 static _Bool           plugin_ctx_key_initialized = 0;
134 static long            write_limit_high = 0;
135 static long            write_limit_low = 0;
137 static derive_t        stats_values_dropped = 0;
138 static _Bool           record_statistics = 0;
140 /*
141  * Static functions
142  */
143 static int plugin_dispatch_values_internal (value_list_t *vl);
145 static const char *plugin_get_dir (void)
147         if (plugindir == NULL)
148                 return (PLUGINDIR);
149         else
150                 return (plugindir);
153 static void plugin_update_internal_statistics (void) { /* {{{ */
155         gauge_t copy_write_queue_length = (gauge_t) write_queue_length;
157         /* Initialize `vl' */
158         value_list_t vl = VALUE_LIST_INIT;
159         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
160         sstrncpy (vl.plugin, "collectd", sizeof (vl.plugin));
162         /* Write queue */
163         sstrncpy (vl.plugin_instance, "write_queue",
164                         sizeof (vl.plugin_instance));
166         /* Write queue : queue length */
167         vl.values = &(value_t) { .gauge = copy_write_queue_length };
168         vl.values_len = 1;
169         sstrncpy (vl.type, "queue_length", sizeof (vl.type));
170         vl.type_instance[0] = 0;
171         plugin_dispatch_values (&vl);
173         /* Write queue : Values dropped (queue length > low limit) */
174         vl.values = &(value_t) { .gauge = (gauge_t) stats_values_dropped };
175         vl.values_len = 1;
176         sstrncpy (vl.type, "derive", sizeof (vl.type));
177         sstrncpy (vl.type_instance, "dropped", sizeof (vl.type_instance));
178         plugin_dispatch_values (&vl);
180         /* Cache */
181         sstrncpy (vl.plugin_instance, "cache",
182                         sizeof (vl.plugin_instance));
184         /* Cache : Nb entry in cache tree */
185         vl.values = &(value_t) { .gauge = (gauge_t) uc_get_size() };
186         vl.values_len = 1;
187         sstrncpy (vl.type, "cache_size", sizeof (vl.type));
188         vl.type_instance[0] = 0;
189         plugin_dispatch_values (&vl);
191         return;
192 } /* }}} void plugin_update_internal_statistics */
194 static void destroy_callback (callback_func_t *cf) /* {{{ */
196         if (cf == NULL)
197                 return;
199         if ((cf->cf_udata.data != NULL) && (cf->cf_udata.free_func != NULL))
200         {
201                 cf->cf_udata.free_func (cf->cf_udata.data);
202                 cf->cf_udata.data = NULL;
203                 cf->cf_udata.free_func = NULL;
204         }
205         sfree (cf);
206 } /* }}} void destroy_callback */
208 static void destroy_all_callbacks (llist_t **list) /* {{{ */
210         llentry_t *le;
212         if (*list == NULL)
213                 return;
215         le = llist_head (*list);
216         while (le != NULL)
217         {
218                 llentry_t *le_next;
220                 le_next = le->next;
222                 sfree (le->key);
223                 destroy_callback (le->value);
224                 le->value = NULL;
226                 le = le_next;
227         }
229         llist_destroy (*list);
230         *list = NULL;
231 } /* }}} void destroy_all_callbacks */
233 static void destroy_read_heap (void) /* {{{ */
235         if (read_heap == NULL)
236                 return;
238         while (42)
239         {
240                 read_func_t *rf;
242                 rf = c_heap_get_root (read_heap);
243                 if (rf == NULL)
244                         break;
245                 sfree (rf->rf_name);
246                 destroy_callback ((callback_func_t *) rf);
247         }
249         c_heap_destroy (read_heap);
250         read_heap = NULL;
251 } /* }}} void destroy_read_heap */
253 static int register_callback (llist_t **list, /* {{{ */
254                 const char *name, callback_func_t *cf)
256         llentry_t *le;
257         char *key;
259         if (*list == NULL)
260         {
261                 *list = llist_create ();
262                 if (*list == NULL)
263                 {
264                         ERROR ("plugin: register_callback: "
265                                         "llist_create failed.");
266                         destroy_callback (cf);
267                         return (-1);
268                 }
269         }
271         key = strdup (name);
272         if (key == NULL)
273         {
274                 ERROR ("plugin: register_callback: strdup failed.");
275                 destroy_callback (cf);
276                 return (-1);
277         }
279         le = llist_search (*list, name);
280         if (le == NULL)
281         {
282                 le = llentry_create (key, cf);
283                 if (le == NULL)
284                 {
285                         ERROR ("plugin: register_callback: "
286                                         "llentry_create failed.");
287                         sfree (key);
288                         destroy_callback (cf);
289                         return (-1);
290                 }
292                 llist_append (*list, le);
293         }
294         else
295         {
296                 callback_func_t *old_cf;
298                 old_cf = le->value;
299                 le->value = cf;
301                 WARNING ("plugin: register_callback: "
302                                 "a callback named `%s' already exists - "
303                                 "overwriting the old entry!", name);
305                 destroy_callback (old_cf);
306                 sfree (key);
307         }
309         return (0);
310 } /* }}} int register_callback */
312 static void log_list_callbacks (llist_t **list, /* {{{ */
313                                 const char *comment)
315         char *str;
316         int len;
317         int i;
318         llentry_t *le;
319         int n;
320         char **keys;
322         n = llist_size(*list);
323         if (n == 0)
324         {
325                 INFO("%s [none]", comment);
326                 return;
327         }
329         keys = calloc(n, sizeof(char*));
331         if (keys == NULL)
332         {
333                 ERROR("%s: failed to allocate memory for list of callbacks",
334                       comment);
336                 return;
337         }
339         for (le = llist_head (*list), i = 0, len = 0;
340              le != NULL;
341              le = le->next, i++)
342         {
343                 keys[i] = le->key;
344                 len += strlen(le->key) + 6;
345         }
346         str = malloc(len + 10);
347         if (str == NULL)
348         {
349                 ERROR("%s: failed to allocate memory for list of callbacks",
350                       comment);
351         }
352         else
353         {
354                 *str = '\0';
355                 strjoin(str, len, keys, n, "', '");
356                 INFO("%s ['%s']", comment, str);
357                 sfree (str);
358         }
359         sfree (keys);
360 } /* }}} void log_list_callbacks */
362 static int create_register_callback (llist_t **list, /* {{{ */
363                 const char *name, void *callback, user_data_t const *ud)
365         callback_func_t *cf;
367         cf = calloc (1, sizeof (*cf));
368         if (cf == NULL)
369         {
370                 ERROR ("plugin: create_register_callback: calloc failed.");
371                 return (-1);
372         }
374         cf->cf_callback = callback;
375         if (ud == NULL)
376         {
377                 cf->cf_udata.data = NULL;
378                 cf->cf_udata.free_func = NULL;
379         }
380         else
381         {
382                 cf->cf_udata = *ud;
383         }
385         cf->cf_ctx = plugin_get_ctx ();
387         return (register_callback (list, name, cf));
388 } /* }}} int create_register_callback */
390 static int plugin_unregister (llist_t *list, const char *name) /* {{{ */
392         llentry_t *e;
394         if (list == NULL)
395                 return (-1);
397         e = llist_search (list, name);
398         if (e == NULL)
399                 return (-1);
401         llist_remove (list, e);
403         sfree (e->key);
404         destroy_callback (e->value);
406         llentry_destroy (e);
408         return (0);
409 } /* }}} int plugin_unregister */
411 /*
412  * (Try to) load the shared object `file'. Won't complain if it isn't a shared
413  * object, but it will bitch about a shared object not having a
414  * ``module_register'' symbol..
415  */
416 static int plugin_load_file (char *file, uint32_t flags)
418         lt_dlhandle dlh;
419         void (*reg_handle) (void);
421         lt_dlinit ();
422         lt_dlerror (); /* clear errors */
424 #if LIBTOOL_VERSION == 2
425         if (flags & PLUGIN_FLAGS_GLOBAL) {
426                 lt_dladvise advise;
427                 lt_dladvise_init(&advise);
428                 lt_dladvise_global(&advise);
429                 dlh = lt_dlopenadvise(file, advise);
430                 lt_dladvise_destroy(&advise);
431         } else {
432                 dlh = lt_dlopen (file);
433         }
434 #else /* if LIBTOOL_VERSION == 1 */
435         if (flags & PLUGIN_FLAGS_GLOBAL)
436                 WARNING ("plugin_load_file: The global flag is not supported, "
437                                 "libtool 2 is required for this.");
438         dlh = lt_dlopen (file);
439 #endif
441         if (dlh == NULL)
442         {
443                 char errbuf[1024] = "";
445                 ssnprintf (errbuf, sizeof (errbuf),
446                                 "lt_dlopen (\"%s\") failed: %s. "
447                                 "The most common cause for this problem is "
448                                 "missing dependencies. Use ldd(1) to check "
449                                 "the dependencies of the plugin "
450                                 "/ shared object.",
451                                 file, lt_dlerror ());
453                 ERROR ("%s", errbuf);
454                 /* Make sure this is printed to STDERR in any case, but also
455                  * make sure it's printed only once. */
456                 if (list_log != NULL)
457                         fprintf (stderr, "ERROR: %s\n", errbuf);
459                 return (1);
460         }
462         if ((reg_handle = (void (*) (void)) lt_dlsym (dlh, "module_register")) == NULL)
463         {
464                 WARNING ("Couldn't find symbol \"module_register\" in \"%s\": %s\n",
465                                 file, lt_dlerror ());
466                 lt_dlclose (dlh);
467                 return (-1);
468         }
470         (*reg_handle) ();
472         return (0);
475 static void *plugin_read_thread (void __attribute__((unused)) *args)
477         while (read_loop != 0)
478         {
479                 read_func_t *rf;
480                 plugin_ctx_t old_ctx;
481                 cdtime_t start;
482                 cdtime_t now;
483                 cdtime_t elapsed;
484                 int status;
485                 int rf_type;
486                 int rc;
488                 /* Get the read function that needs to be read next.
489                  * We don't need to hold "read_lock" for the heap, but we need
490                  * to call c_heap_get_root() and pthread_cond_wait() in the
491                  * same protected block. */
492                 pthread_mutex_lock (&read_lock);
493                 rf = c_heap_get_root (read_heap);
494                 if (rf == NULL)
495                 {
496                         pthread_cond_wait (&read_cond, &read_lock);
497                         pthread_mutex_unlock (&read_lock);
498                         continue;
499                 }
500                 pthread_mutex_unlock (&read_lock);
502                 if (rf->rf_interval == 0)
503                 {
504                         /* this should not happen, because the interval is set
505                          * for each plugin when loading it
506                          * XXX: issue a warning? */
507                         rf->rf_interval = plugin_get_interval ();
508                         rf->rf_effective_interval = rf->rf_interval;
510                         rf->rf_next_read = cdtime ();
511                 }
513                 /* sleep until this entry is due,
514                  * using pthread_cond_timedwait */
515                 pthread_mutex_lock (&read_lock);
516                 /* In pthread_cond_timedwait, spurious wakeups are possible
517                  * (and really happen, at least on NetBSD with > 1 CPU), thus
518                  * we need to re-evaluate the condition every time
519                  * pthread_cond_timedwait returns. */
520                 rc = 0;
521                 while ((read_loop != 0)
522                                 && (cdtime () < rf->rf_next_read)
523                                 && rc == 0)
524                 {
525                         rc = pthread_cond_timedwait (&read_cond, &read_lock,
526                                 &CDTIME_T_TO_TIMESPEC (rf->rf_next_read));
527                 }
529                 /* Must hold `read_lock' when accessing `rf->rf_type'. */
530                 rf_type = rf->rf_type;
531                 pthread_mutex_unlock (&read_lock);
533                 /* Check if we're supposed to stop.. This may have interrupted
534                  * the sleep, too. */
535                 if (read_loop == 0)
536                 {
537                         /* Insert `rf' again, so it can be free'd correctly */
538                         c_heap_insert (read_heap, rf);
539                         break;
540                 }
542                 /* The entry has been marked for deletion. The linked list
543                  * entry has already been removed by `plugin_unregister_read'.
544                  * All we have to do here is free the `read_func_t' and
545                  * continue. */
546                 if (rf_type == RF_REMOVE)
547                 {
548                         DEBUG ("plugin_read_thread: Destroying the `%s' "
549                                         "callback.", rf->rf_name);
550                         sfree (rf->rf_name);
551                         destroy_callback ((callback_func_t *) rf);
552                         rf = NULL;
553                         continue;
554                 }
556                 DEBUG ("plugin_read_thread: Handling `%s'.", rf->rf_name);
558                 start = cdtime ();
560                 old_ctx = plugin_set_ctx (rf->rf_ctx);
562                 if (rf_type == RF_SIMPLE)
563                 {
564                         int (*callback) (void);
566                         callback = rf->rf_callback;
567                         status = (*callback) ();
568                 }
569                 else
570                 {
571                         plugin_read_cb callback;
573                         assert (rf_type == RF_COMPLEX);
575                         callback = rf->rf_callback;
576                         status = (*callback) (&rf->rf_udata);
577                 }
579                 plugin_set_ctx (old_ctx);
581                 /* If the function signals failure, we will increase the
582                  * intervals in which it will be called. */
583                 if (status != 0)
584                 {
585                         rf->rf_effective_interval *= 2;
586                         if (rf->rf_effective_interval > max_read_interval)
587                                 rf->rf_effective_interval = max_read_interval;
589                         NOTICE ("read-function of plugin `%s' failed. "
590                                         "Will suspend it for %.3f seconds.",
591                                         rf->rf_name,
592                                         CDTIME_T_TO_DOUBLE (rf->rf_effective_interval));
593                 }
594                 else
595                 {
596                         /* Success: Restore the interval, if it was changed. */
597                         rf->rf_effective_interval = rf->rf_interval;
598                 }
600                 /* update the ``next read due'' field */
601                 now = cdtime ();
603                 /* calculate the time spent in the read function */
604                 elapsed = (now - start);
606                 if (elapsed > rf->rf_effective_interval)
607                         WARNING ("plugin_read_thread: read-function of the `%s' plugin took %.3f "
608                                 "seconds, which is above its read interval (%.3f seconds). You might "
609                                 "want to adjust the `Interval' or `ReadThreads' settings.",
610                                 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed),
611                                 CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
613                 DEBUG ("plugin_read_thread: read-function of the `%s' plugin took "
614                                 "%.6f seconds.",
615                                 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed));
617                 DEBUG ("plugin_read_thread: Effective interval of the "
618                                 "`%s' plugin is %.3f seconds.",
619                                 rf->rf_name,
620                                 CDTIME_T_TO_DOUBLE (rf->rf_effective_interval));
622                 /* Calculate the next (absolute) time at which this function
623                  * should be called. */
624                 rf->rf_next_read += rf->rf_effective_interval;
626                 /* Check, if `rf_next_read' is in the past. */
627                 if (rf->rf_next_read < now)
628                 {
629                         /* `rf_next_read' is in the past. Insert `now'
630                          * so this value doesn't trail off into the
631                          * past too much. */
632                         rf->rf_next_read = now;
633                 }
635                 DEBUG ("plugin_read_thread: Next read of the `%s' plugin at %.3f.",
636                                 rf->rf_name,
637                                 CDTIME_T_TO_DOUBLE (rf->rf_next_read));
639                 /* Re-insert this read function into the heap again. */
640                 c_heap_insert (read_heap, rf);
641         } /* while (read_loop) */
643         pthread_exit (NULL);
644         return ((void *) 0);
645 } /* void *plugin_read_thread */
647 static void start_read_threads (int num)
649         if (read_threads != NULL)
650                 return;
652         read_threads = (pthread_t *) calloc (num, sizeof (pthread_t));
653         if (read_threads == NULL)
654         {
655                 ERROR ("plugin: start_read_threads: calloc failed.");
656                 return;
657         }
659         read_threads_num = 0;
660         for (int i = 0; i < num; i++)
661         {
662                 if (pthread_create (read_threads + read_threads_num, NULL,
663                                         plugin_read_thread, NULL) == 0)
664                 {
665                         read_threads_num++;
666                 }
667                 else
668                 {
669                         ERROR ("plugin: start_read_threads: pthread_create failed.");
670                         return;
671                 }
672         } /* for (i) */
673 } /* void start_read_threads */
675 static void stop_read_threads (void)
677         if (read_threads == NULL)
678                 return;
680         INFO ("collectd: Stopping %i read threads.", read_threads_num);
682         pthread_mutex_lock (&read_lock);
683         read_loop = 0;
684         DEBUG ("plugin: stop_read_threads: Signalling `read_cond'");
685         pthread_cond_broadcast (&read_cond);
686         pthread_mutex_unlock (&read_lock);
688         for (int i = 0; i < read_threads_num; i++)
689         {
690                 if (pthread_join (read_threads[i], NULL) != 0)
691                 {
692                         ERROR ("plugin: stop_read_threads: pthread_join failed.");
693                 }
694                 read_threads[i] = (pthread_t) 0;
695         }
696         sfree (read_threads);
697         read_threads_num = 0;
698 } /* void stop_read_threads */
700 static void plugin_value_list_free (value_list_t *vl) /* {{{ */
702         if (vl == NULL)
703                 return;
705         meta_data_destroy (vl->meta);
706         sfree (vl->values);
707         sfree (vl);
708 } /* }}} void plugin_value_list_free */
710 static value_list_t *plugin_value_list_clone (value_list_t const *vl_orig) /* {{{ */
712         value_list_t *vl;
714         if (vl_orig == NULL)
715                 return (NULL);
717         vl = malloc (sizeof (*vl));
718         if (vl == NULL)
719                 return (NULL);
720         memcpy (vl, vl_orig, sizeof (*vl));
722         if (vl->host[0] == 0)
723                 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
725         vl->values = calloc (vl_orig->values_len, sizeof (*vl->values));
726         if (vl->values == NULL)
727         {
728                 plugin_value_list_free (vl);
729                 return (NULL);
730         }
731         memcpy (vl->values, vl_orig->values,
732                         vl_orig->values_len * sizeof (*vl->values));
734         vl->meta = meta_data_clone (vl->meta);
735         if ((vl_orig->meta != NULL) && (vl->meta == NULL))
736         {
737                 plugin_value_list_free (vl);
738                 return (NULL);
739         }
741         if (vl->time == 0)
742                 vl->time = cdtime ();
744         /* Fill in the interval from the thread context, if it is zero. */
745         if (vl->interval == 0)
746         {
747                 plugin_ctx_t ctx = plugin_get_ctx ();
749                 if (ctx.interval != 0)
750                         vl->interval = ctx.interval;
751                 else
752                 {
753                         char name[6 * DATA_MAX_NAME_LEN];
754                         FORMAT_VL (name, sizeof (name), vl);
755                         ERROR ("plugin_value_list_clone: Unable to determine "
756                                         "interval from context for "
757                                         "value list \"%s\". "
758                                         "This indicates a broken plugin. "
759                                         "Please report this problem to the "
760                                         "collectd mailing list or at "
761                                         "<http://collectd.org/bugs/>.", name);
762                         vl->interval = cf_get_default_interval ();
763                 }
764         }
766         return (vl);
767 } /* }}} value_list_t *plugin_value_list_clone */
769 static int plugin_write_enqueue (value_list_t const *vl) /* {{{ */
771         write_queue_t *q;
773         q = malloc (sizeof (*q));
774         if (q == NULL)
775                 return (ENOMEM);
776         q->next = NULL;
778         q->vl = plugin_value_list_clone (vl);
779         if (q->vl == NULL)
780         {
781                 sfree (q);
782                 return (ENOMEM);
783         }
785         /* Store context of caller (read plugin); otherwise, it would not be
786          * available to the write plugins when actually dispatching the
787          * value-list later on. */
788         q->ctx = plugin_get_ctx ();
790         pthread_mutex_lock (&write_lock);
792         if (write_queue_tail == NULL)
793         {
794                 write_queue_head = q;
795                 write_queue_tail = q;
796                 write_queue_length = 1;
797         }
798         else
799         {
800                 write_queue_tail->next = q;
801                 write_queue_tail = q;
802                 write_queue_length += 1;
803         }
805         pthread_cond_signal (&write_cond);
806         pthread_mutex_unlock (&write_lock);
808         return (0);
809 } /* }}} int plugin_write_enqueue */
811 static value_list_t *plugin_write_dequeue (void) /* {{{ */
813         write_queue_t *q;
814         value_list_t *vl;
816         pthread_mutex_lock (&write_lock);
818         while (write_loop && (write_queue_head == NULL))
819                 pthread_cond_wait (&write_cond, &write_lock);
821         if (write_queue_head == NULL)
822         {
823                 pthread_mutex_unlock (&write_lock);
824                 return (NULL);
825         }
827         q = write_queue_head;
828         write_queue_head = q->next;
829         write_queue_length -= 1;
830         if (write_queue_head == NULL) {
831                 write_queue_tail = NULL;
832                 assert(0 == write_queue_length);
833                 }
835         pthread_mutex_unlock (&write_lock);
837         (void) plugin_set_ctx (q->ctx);
839         vl = q->vl;
840         sfree (q);
841         return (vl);
842 } /* }}} value_list_t *plugin_write_dequeue */
844 static void *plugin_write_thread (void __attribute__((unused)) *args) /* {{{ */
846         while (write_loop)
847         {
848                 value_list_t *vl = plugin_write_dequeue ();
849                 if (vl == NULL)
850                         continue;
852                 plugin_dispatch_values_internal (vl);
854                 plugin_value_list_free (vl);
855         }
857         pthread_exit (NULL);
858         return ((void *) 0);
859 } /* }}} void *plugin_write_thread */
861 static void start_write_threads (size_t num) /* {{{ */
863         if (write_threads != NULL)
864                 return;
866         write_threads = (pthread_t *) calloc (num, sizeof (pthread_t));
867         if (write_threads == NULL)
868         {
869                 ERROR ("plugin: start_write_threads: calloc failed.");
870                 return;
871         }
873         write_threads_num = 0;
874         for (size_t i = 0; i < num; i++)
875         {
876                 int status;
878                 status = pthread_create (write_threads + write_threads_num,
879                                 /* attr = */ NULL,
880                                 plugin_write_thread,
881                                 /* arg = */ NULL);
882                 if (status != 0)
883                 {
884                         char errbuf[1024];
885                         ERROR ("plugin: start_write_threads: pthread_create failed "
886                                         "with status %i (%s).", status,
887                                         sstrerror (status, errbuf, sizeof (errbuf)));
888                         return;
889                 }
891                 write_threads_num++;
892         } /* for (i) */
893 } /* }}} void start_write_threads */
895 static void stop_write_threads (void) /* {{{ */
897         write_queue_t *q;
898         size_t i;
900         if (write_threads == NULL)
901                 return;
903         INFO ("collectd: Stopping %zu write threads.", write_threads_num);
905         pthread_mutex_lock (&write_lock);
906         write_loop = 0;
907         DEBUG ("plugin: stop_write_threads: Signalling `write_cond'");
908         pthread_cond_broadcast (&write_cond);
909         pthread_mutex_unlock (&write_lock);
911         for (i = 0; i < write_threads_num; i++)
912         {
913                 if (pthread_join (write_threads[i], NULL) != 0)
914                 {
915                         ERROR ("plugin: stop_write_threads: pthread_join failed.");
916                 }
917                 write_threads[i] = (pthread_t) 0;
918         }
919         sfree (write_threads);
920         write_threads_num = 0;
922         pthread_mutex_lock (&write_lock);
923         i = 0;
924         for (q = write_queue_head; q != NULL; )
925         {
926                 write_queue_t *q1 = q;
927                 plugin_value_list_free (q->vl);
928                 q = q->next;
929                 sfree (q1);
930                 i++;
931         }
932         write_queue_head = NULL;
933         write_queue_tail = NULL;
934         write_queue_length = 0;
935         pthread_mutex_unlock (&write_lock);
937         if (i > 0)
938         {
939                 WARNING ("plugin: %zu value list%s left after shutting down "
940                                 "the write threads.",
941                                 i, (i == 1) ? " was" : "s were");
942         }
943 } /* }}} void stop_write_threads */
945 /*
946  * Public functions
947  */
948 void plugin_set_dir (const char *dir)
950         sfree (plugindir);
952         if (dir == NULL)
953         {
954                 plugindir = NULL;
955                 return;
956         }
958         plugindir = strdup (dir);
959         if (plugindir == NULL)
960                 ERROR ("plugin_set_dir: strdup(\"%s\") failed", dir);
963 static _Bool plugin_is_loaded (char const *name)
965         int status;
967         if (plugins_loaded == NULL)
968                 plugins_loaded = c_avl_create ((int (*) (const void *, const void *)) strcasecmp);
969         assert (plugins_loaded != NULL);
971         status = c_avl_get (plugins_loaded, name, /* ret_value = */ NULL);
972         return (status == 0);
975 static int plugin_mark_loaded (char const *name)
977         char *name_copy;
978         int status;
980         name_copy = strdup (name);
981         if (name_copy == NULL)
982                 return (ENOMEM);
984         status = c_avl_insert (plugins_loaded,
985                         /* key = */ name_copy, /* value = */ NULL);
986         return (status);
989 static void plugin_free_loaded (void)
991         void *key;
992         void *value;
994         if (plugins_loaded == NULL)
995                 return;
997         while (c_avl_pick (plugins_loaded, &key, &value) == 0)
998         {
999                 sfree (key);
1000                 assert (value == NULL);
1001         }
1003         c_avl_destroy (plugins_loaded);
1004         plugins_loaded = NULL;
1007 #define BUFSIZE 512
1008 int plugin_load (char const *plugin_name, uint32_t flags)
1010         DIR  *dh;
1011         const char *dir;
1012         char  filename[BUFSIZE] = "";
1013         char  typename[BUFSIZE];
1014         int   ret;
1015         struct stat    statbuf;
1016         struct dirent *de;
1017         int status;
1019         if (plugin_name == NULL)
1020                 return (EINVAL);
1022         /* Check if plugin is already loaded and don't do anything in this
1023          * case. */
1024         if (plugin_is_loaded (plugin_name))
1025                 return (0);
1027         dir = plugin_get_dir ();
1028         ret = 1;
1030         /*
1031          * XXX: Magic at work:
1032          *
1033          * Some of the language bindings, for example the Python and Perl
1034          * plugins, need to be able to export symbols to the scripts they run.
1035          * For this to happen, the "Globals" flag needs to be set.
1036          * Unfortunately, this technical detail is hard to explain to the
1037          * average user and she shouldn't have to worry about this, ideally.
1038          * So in order to save everyone's sanity use a different default for a
1039          * handful of special plugins. --octo
1040          */
1041         if ((strcasecmp ("perl", plugin_name) == 0)
1042                         || (strcasecmp ("python", plugin_name) == 0))
1043                 flags |= PLUGIN_FLAGS_GLOBAL;
1045         /* `cpu' should not match `cpufreq'. To solve this we add `.so' to the
1046          * type when matching the filename */
1047         status = ssnprintf (typename, sizeof (typename), "%s.so", plugin_name);
1048         if ((status < 0) || ((size_t) status >= sizeof (typename)))
1049         {
1050                 WARNING ("plugin_load: Filename too long: \"%s.so\"", plugin_name);
1051                 return (-1);
1052         }
1054         if ((dh = opendir (dir)) == NULL)
1055         {
1056                 char errbuf[1024];
1057                 ERROR ("plugin_load: opendir (%s) failed: %s", dir,
1058                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1059                 return (-1);
1060         }
1062         while ((de = readdir (dh)) != NULL)
1063         {
1064                 if (strcasecmp (de->d_name, typename))
1065                         continue;
1067                 status = ssnprintf (filename, sizeof (filename),
1068                                 "%s/%s", dir, de->d_name);
1069                 if ((status < 0) || ((size_t) status >= sizeof (filename)))
1070                 {
1071                         WARNING ("plugin_load: Filename too long: \"%s/%s\"",
1072                                         dir, de->d_name);
1073                         continue;
1074                 }
1076                 if (lstat (filename, &statbuf) == -1)
1077                 {
1078                         char errbuf[1024];
1079                         WARNING ("plugin_load: stat (\"%s\") failed: %s",
1080                                         filename,
1081                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1082                         continue;
1083                 }
1084                 else if (!S_ISREG (statbuf.st_mode))
1085                 {
1086                         /* don't follow symlinks */
1087                         WARNING ("plugin_load: %s is not a regular file.",
1088                                         filename);
1089                         continue;
1090                 }
1092                 status = plugin_load_file (filename, flags);
1093                 if (status == 0)
1094                 {
1095                         /* success */
1096                         plugin_mark_loaded (plugin_name);
1097                         ret = 0;
1098                         INFO ("plugin_load: plugin \"%s\" successfully loaded.", plugin_name);
1099                         break;
1100                 }
1101                 else
1102                 {
1103                         ERROR ("plugin_load: Load plugin \"%s\" failed with "
1104                                         "status %i.", plugin_name, status);
1105                 }
1106         }
1108         closedir (dh);
1110         if (filename[0] == 0)
1111                 ERROR ("plugin_load: Could not find plugin \"%s\" in %s",
1112                                 plugin_name, dir);
1114         return (ret);
1117 /*
1118  * The `register_*' functions follow
1119  */
1120 int plugin_register_config (const char *name,
1121                 int (*callback) (const char *key, const char *val),
1122                 const char **keys, int keys_num)
1124         cf_register (name, callback, keys, keys_num);
1125         return (0);
1126 } /* int plugin_register_config */
1128 int plugin_register_complex_config (const char *type,
1129                 int (*callback) (oconfig_item_t *))
1131         return (cf_register_complex (type, callback));
1132 } /* int plugin_register_complex_config */
1134 int plugin_register_init (const char *name,
1135                 int (*callback) (void))
1137         return (create_register_callback (&list_init, name, (void *) callback,
1138                                 /* user_data = */ NULL));
1139 } /* plugin_register_init */
1141 static int plugin_compare_read_func (const void *arg0, const void *arg1)
1143         const read_func_t *rf0;
1144         const read_func_t *rf1;
1146         rf0 = arg0;
1147         rf1 = arg1;
1149         if (rf0->rf_next_read < rf1->rf_next_read)
1150                 return (-1);
1151         else if (rf0->rf_next_read > rf1->rf_next_read)
1152                 return (1);
1153         else
1154                 return (0);
1155 } /* int plugin_compare_read_func */
1157 /* Add a read function to both, the heap and a linked list. The linked list if
1158  * used to look-up read functions, especially for the remove function. The heap
1159  * is used to determine which plugin to read next. */
1160 static int plugin_insert_read (read_func_t *rf)
1162         int status;
1163         llentry_t *le;
1165         rf->rf_next_read = cdtime ();
1166         rf->rf_effective_interval = rf->rf_interval;
1168         pthread_mutex_lock (&read_lock);
1170         if (read_list == NULL)
1171         {
1172                 read_list = llist_create ();
1173                 if (read_list == NULL)
1174                 {
1175                         pthread_mutex_unlock (&read_lock);
1176                         ERROR ("plugin_insert_read: read_list failed.");
1177                         return (-1);
1178                 }
1179         }
1181         if (read_heap == NULL)
1182         {
1183                 read_heap = c_heap_create (plugin_compare_read_func);
1184                 if (read_heap == NULL)
1185                 {
1186                         pthread_mutex_unlock (&read_lock);
1187                         ERROR ("plugin_insert_read: c_heap_create failed.");
1188                         return (-1);
1189                 }
1190         }
1192         le = llist_search (read_list, rf->rf_name);
1193         if (le != NULL)
1194         {
1195                 pthread_mutex_unlock (&read_lock);
1196                 WARNING ("The read function \"%s\" is already registered. "
1197                                 "Check for duplicate \"LoadPlugin\" lines "
1198                                 "in your configuration!",
1199                                 rf->rf_name);
1200                 return (EINVAL);
1201         }
1203         le = llentry_create (rf->rf_name, rf);
1204         if (le == NULL)
1205         {
1206                 pthread_mutex_unlock (&read_lock);
1207                 ERROR ("plugin_insert_read: llentry_create failed.");
1208                 return (-1);
1209         }
1211         status = c_heap_insert (read_heap, rf);
1212         if (status != 0)
1213         {
1214                 pthread_mutex_unlock (&read_lock);
1215                 ERROR ("plugin_insert_read: c_heap_insert failed.");
1216                 llentry_destroy (le);
1217                 return (-1);
1218         }
1220         /* This does not fail. */
1221         llist_append (read_list, le);
1223         /* Wake up all the read threads. */
1224         pthread_cond_broadcast (&read_cond);
1225         pthread_mutex_unlock (&read_lock);
1226         return (0);
1227 } /* int plugin_insert_read */
1229 int plugin_register_read (const char *name,
1230                 int (*callback) (void))
1232         read_func_t *rf;
1233         int status;
1235         rf = calloc (1, sizeof (*rf));
1236         if (rf == NULL)
1237         {
1238                 ERROR ("plugin_register_read: calloc failed.");
1239                 return (ENOMEM);
1240         }
1242         rf->rf_callback = (void *) callback;
1243         rf->rf_udata.data = NULL;
1244         rf->rf_udata.free_func = NULL;
1245         rf->rf_ctx = plugin_get_ctx ();
1246         rf->rf_group[0] = '\0';
1247         rf->rf_name = strdup (name);
1248         rf->rf_type = RF_SIMPLE;
1249         rf->rf_interval = plugin_get_interval ();
1251         status = plugin_insert_read (rf);
1252         if (status != 0) {
1253                 sfree (rf->rf_name);
1254                 sfree (rf);
1255         }
1257         return (status);
1258 } /* int plugin_register_read */
1260 int plugin_register_complex_read (const char *group, const char *name,
1261                 plugin_read_cb callback,
1262                 cdtime_t interval,
1263                 user_data_t const *user_data)
1265         read_func_t *rf;
1266         int status;
1268         rf = calloc (1,sizeof (*rf));
1269         if (rf == NULL)
1270         {
1271                 ERROR ("plugin_register_complex_read: calloc failed.");
1272                 return (ENOMEM);
1273         }
1275         rf->rf_callback = (void *) callback;
1276         if (group != NULL)
1277                 sstrncpy (rf->rf_group, group, sizeof (rf->rf_group));
1278         else
1279                 rf->rf_group[0] = '\0';
1280         rf->rf_name = strdup (name);
1281         rf->rf_type = RF_COMPLEX;
1282         rf->rf_interval = (interval != 0) ? interval : plugin_get_interval ();
1284         /* Set user data */
1285         if (user_data == NULL)
1286         {
1287                 rf->rf_udata.data = NULL;
1288                 rf->rf_udata.free_func = NULL;
1289         }
1290         else
1291         {
1292                 rf->rf_udata = *user_data;
1293         }
1295         rf->rf_ctx = plugin_get_ctx ();
1297         status = plugin_insert_read (rf);
1298         if (status != 0) {
1299                 sfree (rf->rf_name);
1300                 sfree (rf);
1301         }
1303         return (status);
1304 } /* int plugin_register_complex_read */
1306 int plugin_register_write (const char *name,
1307                 plugin_write_cb callback, user_data_t const *ud)
1309         return (create_register_callback (&list_write, name,
1310                                 (void *) callback, ud));
1311 } /* int plugin_register_write */
1313 static int plugin_flush_timeout_callback (user_data_t *ud)
1315         flush_callback_t *cb = ud->data;
1317         return plugin_flush (cb->name, cb->timeout, /* identifier = */ NULL);
1318 } /* static int plugin_flush_callback */
1320 static void plugin_flush_timeout_callback_free (void *data)
1322         flush_callback_t *cb = data;
1324         if (cb == NULL) return;
1326         sfree (cb->name);
1327         sfree (cb);
1328 } /* static void plugin_flush_callback_free */
1330 static char *plugin_flush_callback_name (const char *name)
1332         const char *flush_prefix = "flush/";
1333         size_t prefix_size;
1334         char *flush_name;
1335         size_t name_size;
1337         prefix_size = strlen(flush_prefix);
1338         name_size = strlen(name);
1340         flush_name = malloc (name_size + prefix_size + 1);
1341         if (flush_name == NULL)
1342         {
1343                 ERROR ("plugin_flush_callback_name: malloc failed.");
1344                 return (NULL);
1345         }
1347         sstrncpy (flush_name, flush_prefix, prefix_size + 1);
1348         sstrncpy (flush_name + prefix_size, name, name_size + 1);
1350         return flush_name;
1351 } /* static char *plugin_flush_callback_name */
1353 int plugin_register_flush (const char *name,
1354                 plugin_flush_cb callback, user_data_t const *ud)
1356         int status;
1357         plugin_ctx_t ctx = plugin_get_ctx ();
1359         status = create_register_callback (&list_flush, name,
1360                 (void *) callback, ud);
1361         if (status != 0)
1362                 return status;
1364         if (ctx.flush_interval != 0)
1365         {
1366                 char *flush_name;
1367                 flush_callback_t *cb;
1369                 flush_name = plugin_flush_callback_name (name);
1370                 if (flush_name == NULL)
1371                         return (-1);
1373                 cb = malloc(sizeof (*cb));
1374                 if (cb == NULL)
1375                 {
1376                         ERROR ("plugin_register_flush: malloc failed.");
1377                         sfree (flush_name);
1378                         return (-1);
1379                 }
1381                 cb->name = strdup (name);
1382                 if (cb->name == NULL)
1383                 {
1384                         ERROR ("plugin_register_flush: strdup failed.");
1385                         sfree (cb);
1386                         sfree (flush_name);
1387                         return (-1);
1388                 }
1389                 cb->timeout = ctx.flush_timeout;
1391                 status = plugin_register_complex_read (
1392                         /* group     = */ "flush",
1393                         /* name      = */ flush_name,
1394                         /* callback  = */ plugin_flush_timeout_callback,
1395                         /* interval  = */ ctx.flush_interval,
1396                         /* user data = */ &(user_data_t) {
1397                                 .data = cb,
1398                                 .free_func = plugin_flush_timeout_callback_free,
1399                         });
1401                 sfree (flush_name);
1402                 if (status != 0)
1403                 {
1404                         sfree (cb->name);
1405                         sfree (cb);
1406                         return status;
1407                 }
1408         }
1410         return 0;
1411 } /* int plugin_register_flush */
1413 int plugin_register_missing (const char *name,
1414                 plugin_missing_cb callback, user_data_t const *ud)
1416         return (create_register_callback (&list_missing, name,
1417                                 (void *) callback, ud));
1418 } /* int plugin_register_missing */
1420 int plugin_register_shutdown (const char *name,
1421                 int (*callback) (void))
1423         return (create_register_callback (&list_shutdown, name,
1424                                 (void *) callback, /* user_data = */ NULL));
1425 } /* int plugin_register_shutdown */
1427 static void plugin_free_data_sets (void)
1429         void *key;
1430         void *value;
1432         if (data_sets == NULL)
1433                 return;
1435         while (c_avl_pick (data_sets, &key, &value) == 0)
1436         {
1437                 data_set_t *ds = value;
1438                 /* key is a pointer to ds->type */
1440                 sfree (ds->ds);
1441                 sfree (ds);
1442         }
1444         c_avl_destroy (data_sets);
1445         data_sets = NULL;
1446 } /* void plugin_free_data_sets */
1448 int plugin_register_data_set (const data_set_t *ds)
1450         data_set_t *ds_copy;
1452         if ((data_sets != NULL)
1453                         && (c_avl_get (data_sets, ds->type, NULL) == 0))
1454         {
1455                 NOTICE ("Replacing DS `%s' with another version.", ds->type);
1456                 plugin_unregister_data_set (ds->type);
1457         }
1458         else if (data_sets == NULL)
1459         {
1460                 data_sets = c_avl_create ((int (*) (const void *, const void *)) strcmp);
1461                 if (data_sets == NULL)
1462                         return (-1);
1463         }
1465         ds_copy = malloc (sizeof (*ds_copy));
1466         if (ds_copy == NULL)
1467                 return (-1);
1468         memcpy(ds_copy, ds, sizeof (data_set_t));
1470         ds_copy->ds = malloc (sizeof (*ds_copy->ds)
1471                         * ds->ds_num);
1472         if (ds_copy->ds == NULL)
1473         {
1474                 sfree (ds_copy);
1475                 return (-1);
1476         }
1478         for (size_t i = 0; i < ds->ds_num; i++)
1479                 memcpy (ds_copy->ds + i, ds->ds + i, sizeof (data_source_t));
1481         return (c_avl_insert (data_sets, (void *) ds_copy->type, (void *) ds_copy));
1482 } /* int plugin_register_data_set */
1484 int plugin_register_log (const char *name,
1485                 plugin_log_cb callback, user_data_t const *ud)
1487         return (create_register_callback (&list_log, name,
1488                                 (void *) callback, ud));
1489 } /* int plugin_register_log */
1491 int plugin_register_notification (const char *name,
1492                 plugin_notification_cb callback, user_data_t const *ud)
1494         return (create_register_callback (&list_notification, name,
1495                                 (void *) callback, ud));
1496 } /* int plugin_register_log */
1498 int plugin_unregister_config (const char *name)
1500         cf_unregister (name);
1501         return (0);
1502 } /* int plugin_unregister_config */
1504 int plugin_unregister_complex_config (const char *name)
1506         cf_unregister_complex (name);
1507         return (0);
1508 } /* int plugin_unregister_complex_config */
1510 int plugin_unregister_init (const char *name)
1512         return (plugin_unregister (list_init, name));
1515 int plugin_unregister_read (const char *name) /* {{{ */
1517         llentry_t *le;
1518         read_func_t *rf;
1520         if (name == NULL)
1521                 return (-ENOENT);
1523         pthread_mutex_lock (&read_lock);
1525         if (read_list == NULL)
1526         {
1527                 pthread_mutex_unlock (&read_lock);
1528                 return (-ENOENT);
1529         }
1531         le = llist_search (read_list, name);
1532         if (le == NULL)
1533         {
1534                 pthread_mutex_unlock (&read_lock);
1535                 WARNING ("plugin_unregister_read: No such read function: %s",
1536                                 name);
1537                 return (-ENOENT);
1538         }
1540         llist_remove (read_list, le);
1542         rf = le->value;
1543         assert (rf != NULL);
1544         rf->rf_type = RF_REMOVE;
1546         pthread_mutex_unlock (&read_lock);
1548         llentry_destroy (le);
1550         DEBUG ("plugin_unregister_read: Marked `%s' for removal.", name);
1552         return (0);
1553 } /* }}} int plugin_unregister_read */
1555 void plugin_log_available_writers (void)
1557         log_list_callbacks (&list_write, "Available write targets:");
1560 static int compare_read_func_group (llentry_t *e, void *ud) /* {{{ */
1562         read_func_t *rf    = e->value;
1563         char        *group = ud;
1565         return strcmp (rf->rf_group, (const char *)group);
1566 } /* }}} int compare_read_func_group */
1568 int plugin_unregister_read_group (const char *group) /* {{{ */
1570         llentry_t *le;
1571         read_func_t *rf;
1573         int found = 0;
1575         if (group == NULL)
1576                 return (-ENOENT);
1578         pthread_mutex_lock (&read_lock);
1580         if (read_list == NULL)
1581         {
1582                 pthread_mutex_unlock (&read_lock);
1583                 return (-ENOENT);
1584         }
1586         while (42)
1587         {
1588                 le = llist_search_custom (read_list,
1589                                 compare_read_func_group, (void *)group);
1591                 if (le == NULL)
1592                         break;
1594                 ++found;
1596                 llist_remove (read_list, le);
1598                 rf = le->value;
1599                 assert (rf != NULL);
1600                 rf->rf_type = RF_REMOVE;
1602                 llentry_destroy (le);
1604                 DEBUG ("plugin_unregister_read_group: "
1605                                 "Marked `%s' (group `%s') for removal.",
1606                                 rf->rf_name, group);
1607         }
1609         pthread_mutex_unlock (&read_lock);
1611         if (found == 0)
1612         {
1613                 WARNING ("plugin_unregister_read_group: No such "
1614                                 "group of read function: %s", group);
1615                 return (-ENOENT);
1616         }
1618         return (0);
1619 } /* }}} int plugin_unregister_read_group */
1621 int plugin_unregister_write (const char *name)
1623         return (plugin_unregister (list_write, name));
1626 int plugin_unregister_flush (const char *name)
1628         plugin_ctx_t ctx = plugin_get_ctx ();
1630         if (ctx.flush_interval != 0)
1631         {
1632                 char *flush_name;
1634                 flush_name = plugin_flush_callback_name (name);
1635                 if (flush_name != NULL)
1636                 {
1637                         plugin_unregister_read(flush_name);
1638                         sfree (flush_name);
1639                 }
1640         }
1642         return plugin_unregister (list_flush, name);
1645 int plugin_unregister_missing (const char *name)
1647         return (plugin_unregister (list_missing, name));
1650 int plugin_unregister_shutdown (const char *name)
1652         return (plugin_unregister (list_shutdown, name));
1655 int plugin_unregister_data_set (const char *name)
1657         data_set_t *ds;
1659         if (data_sets == NULL)
1660                 return (-1);
1662         if (c_avl_remove (data_sets, name, NULL, (void *) &ds) != 0)
1663                 return (-1);
1665         sfree (ds->ds);
1666         sfree (ds);
1668         return (0);
1669 } /* int plugin_unregister_data_set */
1671 int plugin_unregister_log (const char *name)
1673         return (plugin_unregister (list_log, name));
1676 int plugin_unregister_notification (const char *name)
1678         return (plugin_unregister (list_notification, name));
1681 int plugin_init_all (void)
1683         char const *chain_name;
1684         llentry_t *le;
1685         int status;
1686         int ret = 0;
1688         /* Init the value cache */
1689         uc_init ();
1691         if (IS_TRUE (global_option_get ("CollectInternalStats")))
1692                 record_statistics = 1;
1694         chain_name = global_option_get ("PreCacheChain");
1695         pre_cache_chain = fc_chain_get_by_name (chain_name);
1697         chain_name = global_option_get ("PostCacheChain");
1698         post_cache_chain = fc_chain_get_by_name (chain_name);
1700         write_limit_high = global_option_get_long ("WriteQueueLimitHigh",
1701                         /* default = */ 0);
1702         if (write_limit_high < 0)
1703         {
1704                 ERROR ("WriteQueueLimitHigh must be positive or zero.");
1705                 write_limit_high = 0;
1706         }
1708         write_limit_low = global_option_get_long ("WriteQueueLimitLow",
1709                         /* default = */ write_limit_high / 2);
1710         if (write_limit_low < 0)
1711         {
1712                 ERROR ("WriteQueueLimitLow must be positive or zero.");
1713                 write_limit_low = write_limit_high / 2;
1714         }
1715         else if (write_limit_low > write_limit_high)
1716         {
1717                 ERROR ("WriteQueueLimitLow must not be larger than "
1718                                 "WriteQueueLimitHigh.");
1719                 write_limit_low = write_limit_high;
1720         }
1722         write_threads_num = global_option_get_long ("WriteThreads",
1723                         /* default = */ 5);
1724         if (write_threads_num < 1)
1725         {
1726                 ERROR ("WriteThreads must be positive.");
1727                 write_threads_num = 5;
1728         }
1730         if ((list_init == NULL) && (read_heap == NULL))
1731                 return ret;
1733         /* Calling all init callbacks before checking if read callbacks
1734          * are available allows the init callbacks to register the read
1735          * callback. */
1736         le = llist_head (list_init);
1737         while (le != NULL)
1738         {
1739                 callback_func_t *cf;
1740                 plugin_init_cb callback;
1741                 plugin_ctx_t old_ctx;
1743                 cf = le->value;
1744                 old_ctx = plugin_set_ctx (cf->cf_ctx);
1745                 callback = cf->cf_callback;
1746                 status = (*callback) ();
1747                 plugin_set_ctx (old_ctx);
1749                 if (status != 0)
1750                 {
1751                         ERROR ("Initialization of plugin `%s' "
1752                                         "failed with status %i. "
1753                                         "Plugin will be unloaded.",
1754                                         le->key, status);
1755                         /* Plugins that register read callbacks from the init
1756                          * callback should take care of appropriate error
1757                          * handling themselves. */
1758                         /* FIXME: Unload _all_ functions */
1759                         plugin_unregister_read (le->key);
1760                         ret = -1;
1761                 }
1763                 le = le->next;
1764         }
1766         start_write_threads ((size_t) write_threads_num);
1768         max_read_interval = global_option_get_time ("MaxReadInterval",
1769                         DEFAULT_MAX_READ_INTERVAL);
1771         /* Start read-threads */
1772         if (read_heap != NULL)
1773         {
1774                 const char *rt;
1775                 int num;
1777                 rt = global_option_get ("ReadThreads");
1778                 num = atoi (rt);
1779                 if (num != -1)
1780                         start_read_threads ((num > 0) ? num : 5);
1781         }
1782         return ret;
1783 } /* void plugin_init_all */
1785 /* TODO: Rename this function. */
1786 void plugin_read_all (void)
1788         if(record_statistics) {
1789                 plugin_update_internal_statistics ();
1790         }
1791         uc_check_timeout ();
1793         return;
1794 } /* void plugin_read_all */
1796 /* Read function called when the `-T' command line argument is given. */
1797 int plugin_read_all_once (void)
1799         int status;
1800         int return_status = 0;
1802         if (read_heap == NULL)
1803         {
1804                 NOTICE ("No read-functions are registered.");
1805                 return (0);
1806         }
1808         while (42)
1809         {
1810                 read_func_t *rf;
1811                 plugin_ctx_t old_ctx;
1813                 rf = c_heap_get_root (read_heap);
1814                 if (rf == NULL)
1815                         break;
1817                 old_ctx = plugin_set_ctx (rf->rf_ctx);
1819                 if (rf->rf_type == RF_SIMPLE)
1820                 {
1821                         int (*callback) (void);
1823                         callback = rf->rf_callback;
1824                         status = (*callback) ();
1825                 }
1826                 else
1827                 {
1828                         plugin_read_cb callback;
1830                         callback = rf->rf_callback;
1831                         status = (*callback) (&rf->rf_udata);
1832                 }
1834                 plugin_set_ctx (old_ctx);
1836                 if (status != 0)
1837                 {
1838                         NOTICE ("read-function of plugin `%s' failed.",
1839                                         rf->rf_name);
1840                         return_status = -1;
1841                 }
1843                 sfree (rf->rf_name);
1844                 destroy_callback ((void *) rf);
1845         }
1847         return (return_status);
1848 } /* int plugin_read_all_once */
1850 int plugin_write (const char *plugin, /* {{{ */
1851                 const data_set_t *ds, const value_list_t *vl)
1853   llentry_t *le;
1854   int status;
1856   if (vl == NULL)
1857     return (EINVAL);
1859   if (list_write == NULL)
1860     return (ENOENT);
1862   if (ds == NULL)
1863   {
1864     ds = plugin_get_ds (vl->type);
1865     if (ds == NULL)
1866     {
1867       ERROR ("plugin_write: Unable to lookup type `%s'.", vl->type);
1868       return (ENOENT);
1869     }
1870   }
1872   if (plugin == NULL)
1873   {
1874     int success = 0;
1875     int failure = 0;
1877     le = llist_head (list_write);
1878     while (le != NULL)
1879     {
1880       callback_func_t *cf = le->value;
1881       plugin_write_cb callback;
1883       /* do not switch plugin context; rather keep the context (interval)
1884        * information of the calling read plugin */
1886       DEBUG ("plugin: plugin_write: Writing values via %s.", le->key);
1887       callback = cf->cf_callback;
1888       status = (*callback) (ds, vl, &cf->cf_udata);
1889       if (status != 0)
1890         failure++;
1891       else
1892         success++;
1894       le = le->next;
1895     }
1897     if ((success == 0) && (failure != 0))
1898       status = -1;
1899     else
1900       status = 0;
1901   }
1902   else /* plugin != NULL */
1903   {
1904     callback_func_t *cf;
1905     plugin_write_cb callback;
1907     le = llist_head (list_write);
1908     while (le != NULL)
1909     {
1910       if (strcasecmp (plugin, le->key) == 0)
1911         break;
1913       le = le->next;
1914     }
1916     if (le == NULL)
1917       return (ENOENT);
1919     cf = le->value;
1921     /* do not switch plugin context; rather keep the context (interval)
1922      * information of the calling read plugin */
1924     DEBUG ("plugin: plugin_write: Writing values via %s.", le->key);
1925     callback = cf->cf_callback;
1926     status = (*callback) (ds, vl, &cf->cf_udata);
1927   }
1929   return (status);
1930 } /* }}} int plugin_write */
1932 int plugin_flush (const char *plugin, cdtime_t timeout, const char *identifier)
1934   llentry_t *le;
1936   if (list_flush == NULL)
1937     return (0);
1939   le = llist_head (list_flush);
1940   while (le != NULL)
1941   {
1942     callback_func_t *cf;
1943     plugin_flush_cb callback;
1944     plugin_ctx_t old_ctx;
1946     if ((plugin != NULL)
1947         && (strcmp (plugin, le->key) != 0))
1948     {
1949       le = le->next;
1950       continue;
1951     }
1953     cf = le->value;
1954     old_ctx = plugin_set_ctx (cf->cf_ctx);
1955     callback = cf->cf_callback;
1957     (*callback) (timeout, identifier, &cf->cf_udata);
1959     plugin_set_ctx (old_ctx);
1961     le = le->next;
1962   }
1963   return (0);
1964 } /* int plugin_flush */
1966 int plugin_shutdown_all (void)
1968         llentry_t *le;
1969         int ret = 0;  // Assume success.
1971         destroy_all_callbacks (&list_init);
1973         stop_read_threads ();
1975         pthread_mutex_lock (&read_lock);
1976         llist_destroy (read_list);
1977         read_list = NULL;
1978         pthread_mutex_unlock (&read_lock);
1980         destroy_read_heap ();
1982         /* blocks until all write threads have shut down. */
1983         stop_write_threads ();
1985         /* ask all plugins to write out the state they kept. */
1986         plugin_flush (/* plugin = */ NULL,
1987                         /* timeout = */ 0,
1988                         /* identifier = */ NULL);
1990         le = NULL;
1991         if (list_shutdown != NULL)
1992                 le = llist_head (list_shutdown);
1994         while (le != NULL)
1995         {
1996                 callback_func_t *cf;
1997                 plugin_shutdown_cb callback;
1998                 plugin_ctx_t old_ctx;
2000                 cf = le->value;
2001                 old_ctx = plugin_set_ctx (cf->cf_ctx);
2002                 callback = cf->cf_callback;
2004                 /* Advance the pointer before calling the callback allows
2005                  * shutdown functions to unregister themselves. If done the
2006                  * other way around the memory `le' points to will be freed
2007                  * after callback returns. */
2008                 le = le->next;
2010                 if ((*callback) () != 0)
2011                         ret = -1;
2013                 plugin_set_ctx (old_ctx);
2014         }
2016         /* Write plugins which use the `user_data' pointer usually need the
2017          * same data available to the flush callback. If this is the case, set
2018          * the free_function to NULL when registering the flush callback and to
2019          * the real free function when registering the write callback. This way
2020          * the data isn't freed twice. */
2021         destroy_all_callbacks (&list_flush);
2022         destroy_all_callbacks (&list_missing);
2023         destroy_all_callbacks (&list_write);
2025         destroy_all_callbacks (&list_notification);
2026         destroy_all_callbacks (&list_shutdown);
2027         destroy_all_callbacks (&list_log);
2029         plugin_free_loaded ();
2030         plugin_free_data_sets ();
2031         return (ret);
2032 } /* void plugin_shutdown_all */
2034 int plugin_dispatch_missing (const value_list_t *vl) /* {{{ */
2036   llentry_t *le;
2038   if (list_missing == NULL)
2039     return (0);
2041   le = llist_head (list_missing);
2042   while (le != NULL)
2043   {
2044     callback_func_t *cf;
2045     plugin_missing_cb callback;
2046     plugin_ctx_t old_ctx;
2047     int status;
2049     cf = le->value;
2050     old_ctx = plugin_set_ctx (cf->cf_ctx);
2051     callback = cf->cf_callback;
2053     status = (*callback) (vl, &cf->cf_udata);
2054     plugin_set_ctx (old_ctx);
2055     if (status != 0)
2056     {
2057       if (status < 0)
2058       {
2059         ERROR ("plugin_dispatch_missing: Callback function \"%s\" "
2060             "failed with status %i.",
2061             le->key, status);
2062         return (status);
2063       }
2064       else
2065       {
2066         return (0);
2067       }
2068     }
2070     le = le->next;
2071   }
2072   return (0);
2073 } /* int }}} plugin_dispatch_missing */
2075 static int plugin_dispatch_values_internal (value_list_t *vl)
2077         int status;
2078         static c_complain_t no_write_complaint = C_COMPLAIN_INIT_STATIC;
2080         data_set_t *ds;
2082         _Bool free_meta_data = 0;
2084         assert (vl != NULL);
2086         /* These fields are initialized by plugin_value_list_clone() if needed: */
2087         assert (vl->host[0] != 0);
2088         assert (vl->time != 0); /* The time is determined at _enqueue_ time. */
2089         assert (vl->interval != 0);
2091         if (vl->type[0] == 0 || vl->values == NULL || vl->values_len < 1)
2092         {
2093                 ERROR ("plugin_dispatch_values: Invalid value list "
2094                                 "from plugin %s.", vl->plugin);
2095                 return (-1);
2096         }
2098         /* Free meta data only if the calling function didn't specify any. In
2099          * this case matches and targets may add some and the calling function
2100          * may not expect (and therefore free) that data. */
2101         if (vl->meta == NULL)
2102                 free_meta_data = 1;
2104         if (list_write == NULL)
2105                 c_complain_once (LOG_WARNING, &no_write_complaint,
2106                                 "plugin_dispatch_values: No write callback has been "
2107                                 "registered. Please load at least one output plugin, "
2108                                 "if you want the collected data to be stored.");
2110         if (data_sets == NULL)
2111         {
2112                 ERROR ("plugin_dispatch_values: No data sets registered. "
2113                                 "Could the types database be read? Check "
2114                                 "your `TypesDB' setting!");
2115                 return (-1);
2116         }
2118         if (c_avl_get (data_sets, vl->type, (void *) &ds) != 0)
2119         {
2120                 char ident[6 * DATA_MAX_NAME_LEN];
2122                 FORMAT_VL (ident, sizeof (ident), vl);
2123                 INFO ("plugin_dispatch_values: Dataset not found: %s "
2124                                 "(from \"%s\"), check your types.db!",
2125                                 vl->type, ident);
2126                 return (-1);
2127         }
2129         DEBUG ("plugin_dispatch_values: time = %.3f; interval = %.3f; "
2130                         "host = %s; "
2131                         "plugin = %s; plugin_instance = %s; "
2132                         "type = %s; type_instance = %s;",
2133                         CDTIME_T_TO_DOUBLE (vl->time),
2134                         CDTIME_T_TO_DOUBLE (vl->interval),
2135                         vl->host,
2136                         vl->plugin, vl->plugin_instance,
2137                         vl->type, vl->type_instance);
2139 #if COLLECT_DEBUG
2140         assert (0 == strcmp (ds->type, vl->type));
2141 #else
2142         if (0 != strcmp (ds->type, vl->type))
2143                 WARNING ("plugin_dispatch_values: (ds->type = %s) != (vl->type = %s)",
2144                                 ds->type, vl->type);
2145 #endif
2147 #if COLLECT_DEBUG
2148         assert (ds->ds_num == vl->values_len);
2149 #else
2150         if (ds->ds_num != vl->values_len)
2151         {
2152                 ERROR ("plugin_dispatch_values: ds->type = %s: "
2153                                 "(ds->ds_num = %zu) != "
2154                                 "(vl->values_len = %zu)",
2155                                 ds->type, ds->ds_num, vl->values_len);
2156                 return (-1);
2157         }
2158 #endif
2160         escape_slashes (vl->host, sizeof (vl->host));
2161         escape_slashes (vl->plugin, sizeof (vl->plugin));
2162         escape_slashes (vl->plugin_instance, sizeof (vl->plugin_instance));
2163         escape_slashes (vl->type, sizeof (vl->type));
2164         escape_slashes (vl->type_instance, sizeof (vl->type_instance));
2166         if (pre_cache_chain != NULL)
2167         {
2168                 status = fc_process_chain (ds, vl, pre_cache_chain);
2169                 if (status < 0)
2170                 {
2171                         WARNING ("plugin_dispatch_values: Running the "
2172                                         "pre-cache chain failed with "
2173                                         "status %i (%#x).",
2174                                         status, status);
2175                 }
2176                 else if (status == FC_TARGET_STOP)
2177                         return (0);
2178         }
2180         /* Update the value cache */
2181         uc_update (ds, vl);
2183         if (post_cache_chain != NULL)
2184         {
2185                 status = fc_process_chain (ds, vl, post_cache_chain);
2186                 if (status < 0)
2187                 {
2188                         WARNING ("plugin_dispatch_values: Running the "
2189                                         "post-cache chain failed with "
2190                                         "status %i (%#x).",
2191                                         status, status);
2192                 }
2193         }
2194         else
2195                 fc_default_action (ds, vl);
2197         if ((free_meta_data != 0) && (vl->meta != NULL))
2198         {
2199                 meta_data_destroy (vl->meta);
2200                 vl->meta = NULL;
2201         }
2203         return (0);
2204 } /* int plugin_dispatch_values_internal */
2206 static double get_drop_probability (void) /* {{{ */
2208         long pos;
2209         long size;
2210         long wql;
2212         pthread_mutex_lock (&write_lock);
2213         wql = write_queue_length;
2214         pthread_mutex_unlock (&write_lock);
2216         if (wql < write_limit_low)
2217                 return (0.0);
2218         if (wql >= write_limit_high)
2219                 return (1.0);
2221         pos = 1 + wql - write_limit_low;
2222         size = 1 + write_limit_high - write_limit_low;
2224         return (((double) pos) / ((double) size));
2225 } /* }}} double get_drop_probability */
2227 static _Bool check_drop_value (void) /* {{{ */
2229         static cdtime_t last_message_time = 0;
2230         static pthread_mutex_t last_message_lock = PTHREAD_MUTEX_INITIALIZER;
2232         double p;
2233         double q;
2234         int status;
2236         if (write_limit_high == 0)
2237                 return (0);
2239         p = get_drop_probability ();
2240         if (p == 0.0)
2241                 return (0);
2243         status = pthread_mutex_trylock (&last_message_lock);
2244         if (status == 0)
2245         {
2246                 cdtime_t now;
2248                 now = cdtime ();
2249                 if ((now - last_message_time) > TIME_T_TO_CDTIME_T (1))
2250                 {
2251                         last_message_time = now;
2252                         ERROR ("plugin_dispatch_values: Low water mark "
2253                                         "reached. Dropping %.0f%% of metrics.",
2254                                         100.0 * p);
2255                 }
2256                 pthread_mutex_unlock (&last_message_lock);
2257         }
2259         if (p == 1.0)
2260                 return (1);
2262         q = cdrand_d ();
2263         if (q > p)
2264                 return (1);
2265         else
2266                 return (0);
2267 } /* }}} _Bool check_drop_value */
2269 int plugin_dispatch_values (value_list_t const *vl)
2271         int status;
2272         static pthread_mutex_t statistics_lock = PTHREAD_MUTEX_INITIALIZER;
2274         if (check_drop_value ()) {
2275                 if(record_statistics) {
2276                         pthread_mutex_lock(&statistics_lock);
2277                         stats_values_dropped++;
2278                         pthread_mutex_unlock(&statistics_lock);
2279                 }
2280                 return (0);
2281         }
2283         status = plugin_write_enqueue (vl);
2284         if (status != 0)
2285         {
2286                 char errbuf[1024];
2287                 ERROR ("plugin_dispatch_values: plugin_write_enqueue failed "
2288                                 "with status %i (%s).", status,
2289                                 sstrerror (status, errbuf, sizeof (errbuf)));
2290                 return (status);
2291         }
2293         return (0);
2296 __attribute__((sentinel))
2297 int plugin_dispatch_multivalue (value_list_t const *template, /* {{{ */
2298                 _Bool store_percentage, int store_type, ...)
2300         value_list_t *vl;
2301         int failed = 0;
2302         gauge_t sum = 0.0;
2303         va_list ap;
2305         assert (template->values_len == 1);
2307         /* Calculate sum for Gauge to calculate percent if needed */
2308         if (DS_TYPE_GAUGE == store_type)        {
2309                 va_start (ap, store_type);
2310                 while (42)
2311                 {
2312                         char const *name;
2313                         gauge_t value;
2315                         name = va_arg (ap, char const *);
2316                         if (name == NULL)
2317                                 break;
2319                         value = va_arg (ap, gauge_t);
2320                         if (!isnan (value))
2321                                 sum += value;
2322                 }
2323                 va_end (ap);
2324         }
2327         vl = plugin_value_list_clone (template);
2328         /* plugin_value_list_clone makes sure vl->time is set to non-zero. */
2329         if (store_percentage)
2330                 sstrncpy (vl->type, "percent", sizeof (vl->type));
2332         va_start (ap, store_type);
2333         while (42)
2334         {
2335                 char const *name;
2336                 int status;
2338                 /* Set the type instance. */
2339                 name = va_arg (ap, char const *);
2340                 if (name == NULL)
2341                         break;
2342                 sstrncpy (vl->type_instance, name, sizeof (vl->type_instance));
2344                 /* Set the value. */
2345                 switch (store_type)
2346                 {
2347                 case DS_TYPE_GAUGE:
2348                         vl->values[0].gauge = va_arg (ap, gauge_t);
2349                         if (store_percentage)
2350                                 vl->values[0].gauge *= sum ? (100.0 / sum) : NAN;
2351                         break;
2352                 case DS_TYPE_ABSOLUTE:
2353                         vl->values[0].absolute = va_arg (ap, absolute_t);
2354                         break;
2355                 case DS_TYPE_COUNTER:
2356                         vl->values[0].counter  = va_arg (ap, counter_t);
2357                         break;
2358                 case DS_TYPE_DERIVE:
2359                         vl->values[0].derive   = va_arg (ap, derive_t);
2360                         break;
2361                 default:
2362                         ERROR ("plugin_dispatch_multivalue: given store_type is incorrect.");
2363                         failed++;
2364                 }
2367                 status = plugin_write_enqueue (vl);
2368                 if (status != 0)
2369                         failed++;
2370         }
2371         va_end (ap);
2373         plugin_value_list_free (vl);
2374         return (failed);
2375 } /* }}} int plugin_dispatch_multivalue */
2377 int plugin_dispatch_notification (const notification_t *notif)
2379         llentry_t *le;
2380         /* Possible TODO: Add flap detection here */
2382         DEBUG ("plugin_dispatch_notification: severity = %i; message = %s; "
2383                         "time = %.3f; host = %s;",
2384                         notif->severity, notif->message,
2385                         CDTIME_T_TO_DOUBLE (notif->time), notif->host);
2387         /* Nobody cares for notifications */
2388         if (list_notification == NULL)
2389                 return (-1);
2391         le = llist_head (list_notification);
2392         while (le != NULL)
2393         {
2394                 callback_func_t *cf;
2395                 plugin_notification_cb callback;
2396                 int status;
2398                 /* do not switch plugin context; rather keep the context
2399                  * (interval) information of the calling plugin */
2401                 cf = le->value;
2402                 callback = cf->cf_callback;
2403                 status = (*callback) (notif, &cf->cf_udata);
2404                 if (status != 0)
2405                 {
2406                         WARNING ("plugin_dispatch_notification: Notification "
2407                                         "callback %s returned %i.",
2408                                         le->key, status);
2409                 }
2411                 le = le->next;
2412         }
2414         return (0);
2415 } /* int plugin_dispatch_notification */
2417 void plugin_log (int level, const char *format, ...)
2419         char msg[1024];
2420         va_list ap;
2421         llentry_t *le;
2423 #if !COLLECT_DEBUG
2424         if (level >= LOG_DEBUG)
2425                 return;
2426 #endif
2428         va_start (ap, format);
2429         vsnprintf (msg, sizeof (msg), format, ap);
2430         msg[sizeof (msg) - 1] = '\0';
2431         va_end (ap);
2433         if (list_log == NULL)
2434         {
2435                 fprintf (stderr, "%s\n", msg);
2436                 return;
2437         }
2439         le = llist_head (list_log);
2440         while (le != NULL)
2441         {
2442                 callback_func_t *cf;
2443                 plugin_log_cb callback;
2445                 cf = le->value;
2446                 callback = cf->cf_callback;
2448                 /* do not switch plugin context; rather keep the context
2449                  * (interval) information of the calling plugin */
2451                 (*callback) (level, msg, &cf->cf_udata);
2453                 le = le->next;
2454         }
2455 } /* void plugin_log */
2457 int parse_log_severity (const char *severity)
2459         int log_level = -1;
2461         if ((0 == strcasecmp (severity, "emerg"))
2462                         || (0 == strcasecmp (severity, "alert"))
2463                         || (0 == strcasecmp (severity, "crit"))
2464                         || (0 == strcasecmp (severity, "err")))
2465                 log_level = LOG_ERR;
2466         else if (0 == strcasecmp (severity, "warning"))
2467                 log_level = LOG_WARNING;
2468         else if (0 == strcasecmp (severity, "notice"))
2469                 log_level = LOG_NOTICE;
2470         else if (0 == strcasecmp (severity, "info"))
2471                 log_level = LOG_INFO;
2472 #if COLLECT_DEBUG
2473         else if (0 == strcasecmp (severity, "debug"))
2474                 log_level = LOG_DEBUG;
2475 #endif /* COLLECT_DEBUG */
2477         return (log_level);
2478 } /* int parse_log_severity */
2480 int parse_notif_severity (const char *severity)
2482         int notif_severity = -1;
2484         if (strcasecmp (severity, "FAILURE") == 0)
2485                 notif_severity = NOTIF_FAILURE;
2486         else if (strcmp (severity, "OKAY") == 0)
2487                 notif_severity = NOTIF_OKAY;
2488         else if ((strcmp (severity, "WARNING") == 0)
2489                         || (strcmp (severity, "WARN") == 0))
2490                 notif_severity = NOTIF_WARNING;
2492         return (notif_severity);
2493 } /* int parse_notif_severity */
2495 const data_set_t *plugin_get_ds (const char *name)
2497         data_set_t *ds;
2499         if (data_sets == NULL)
2500         {
2501                 ERROR ("plugin_get_ds: No data sets are defined yet.");
2502                 return (NULL);
2503         }
2505         if (c_avl_get (data_sets, name, (void *) &ds) != 0)
2506         {
2507                 DEBUG ("No such dataset registered: %s", name);
2508                 return (NULL);
2509         }
2511         return (ds);
2512 } /* data_set_t *plugin_get_ds */
2514 static int plugin_notification_meta_add (notification_t *n,
2515     const char *name,
2516     enum notification_meta_type_e type,
2517     const void *value)
2519   notification_meta_t *meta;
2520   notification_meta_t *tail;
2522   if ((n == NULL) || (name == NULL) || (value == NULL))
2523   {
2524     ERROR ("plugin_notification_meta_add: A pointer is NULL!");
2525     return (-1);
2526   }
2528   meta = calloc (1, sizeof (*meta));
2529   if (meta == NULL)
2530   {
2531     ERROR ("plugin_notification_meta_add: calloc failed.");
2532     return (-1);
2533   }
2535   sstrncpy (meta->name, name, sizeof (meta->name));
2536   meta->type = type;
2538   switch (type)
2539   {
2540     case NM_TYPE_STRING:
2541     {
2542       meta->nm_value.nm_string = strdup ((const char *) value);
2543       if (meta->nm_value.nm_string == NULL)
2544       {
2545         ERROR ("plugin_notification_meta_add: strdup failed.");
2546         sfree (meta);
2547         return (-1);
2548       }
2549       break;
2550     }
2551     case NM_TYPE_SIGNED_INT:
2552     {
2553       meta->nm_value.nm_signed_int = *((int64_t *) value);
2554       break;
2555     }
2556     case NM_TYPE_UNSIGNED_INT:
2557     {
2558       meta->nm_value.nm_unsigned_int = *((uint64_t *) value);
2559       break;
2560     }
2561     case NM_TYPE_DOUBLE:
2562     {
2563       meta->nm_value.nm_double = *((double *) value);
2564       break;
2565     }
2566     case NM_TYPE_BOOLEAN:
2567     {
2568       meta->nm_value.nm_boolean = *((_Bool *) value);
2569       break;
2570     }
2571     default:
2572     {
2573       ERROR ("plugin_notification_meta_add: Unknown type: %i", type);
2574       sfree (meta);
2575       return (-1);
2576     }
2577   } /* switch (type) */
2579   meta->next = NULL;
2580   tail = n->meta;
2581   while ((tail != NULL) && (tail->next != NULL))
2582     tail = tail->next;
2584   if (tail == NULL)
2585     n->meta = meta;
2586   else
2587     tail->next = meta;
2589   return (0);
2590 } /* int plugin_notification_meta_add */
2592 int plugin_notification_meta_add_string (notification_t *n,
2593     const char *name,
2594     const char *value)
2596   return (plugin_notification_meta_add (n, name, NM_TYPE_STRING, value));
2599 int plugin_notification_meta_add_signed_int (notification_t *n,
2600     const char *name,
2601     int64_t value)
2603   return (plugin_notification_meta_add (n, name, NM_TYPE_SIGNED_INT, &value));
2606 int plugin_notification_meta_add_unsigned_int (notification_t *n,
2607     const char *name,
2608     uint64_t value)
2610   return (plugin_notification_meta_add (n, name, NM_TYPE_UNSIGNED_INT, &value));
2613 int plugin_notification_meta_add_double (notification_t *n,
2614     const char *name,
2615     double value)
2617   return (plugin_notification_meta_add (n, name, NM_TYPE_DOUBLE, &value));
2620 int plugin_notification_meta_add_boolean (notification_t *n,
2621     const char *name,
2622     _Bool value)
2624   return (plugin_notification_meta_add (n, name, NM_TYPE_BOOLEAN, &value));
2627 int plugin_notification_meta_copy (notification_t *dst,
2628     const notification_t *src)
2630   assert (dst != NULL);
2631   assert (src != NULL);
2632   assert (dst != src);
2633   assert ((src->meta == NULL) || (src->meta != dst->meta));
2635   for (notification_meta_t *meta = src->meta; meta != NULL; meta = meta->next)
2636   {
2637     if (meta->type == NM_TYPE_STRING)
2638       plugin_notification_meta_add_string (dst, meta->name,
2639           meta->nm_value.nm_string);
2640     else if (meta->type == NM_TYPE_SIGNED_INT)
2641       plugin_notification_meta_add_signed_int (dst, meta->name,
2642           meta->nm_value.nm_signed_int);
2643     else if (meta->type == NM_TYPE_UNSIGNED_INT)
2644       plugin_notification_meta_add_unsigned_int (dst, meta->name,
2645           meta->nm_value.nm_unsigned_int);
2646     else if (meta->type == NM_TYPE_DOUBLE)
2647       plugin_notification_meta_add_double (dst, meta->name,
2648           meta->nm_value.nm_double);
2649     else if (meta->type == NM_TYPE_BOOLEAN)
2650       plugin_notification_meta_add_boolean (dst, meta->name,
2651           meta->nm_value.nm_boolean);
2652   }
2654   return (0);
2655 } /* int plugin_notification_meta_copy */
2657 int plugin_notification_meta_free (notification_meta_t *n)
2659   notification_meta_t *this;
2660   notification_meta_t *next;
2662   if (n == NULL)
2663   {
2664     ERROR ("plugin_notification_meta_free: n == NULL!");
2665     return (-1);
2666   }
2668   this = n;
2669   while (this != NULL)
2670   {
2671     next = this->next;
2673     if (this->type == NM_TYPE_STRING)
2674     {
2675       /* Assign to a temporary variable to work around nm_string's const
2676        * modifier. */
2677       void *tmp = (void *) this->nm_value.nm_string;
2679       sfree (tmp);
2680       this->nm_value.nm_string = NULL;
2681     }
2682     sfree (this);
2684     this = next;
2685   }
2687   return (0);
2688 } /* int plugin_notification_meta_free */
2690 static void plugin_ctx_destructor (void *ctx)
2692         sfree (ctx);
2693 } /* void plugin_ctx_destructor */
2695 static plugin_ctx_t ctx_init = { /* interval = */ 0 };
2697 static plugin_ctx_t *plugin_ctx_create (void)
2699         plugin_ctx_t *ctx;
2701         ctx = malloc (sizeof (*ctx));
2702         if (ctx == NULL) {
2703                 char errbuf[1024];
2704                 ERROR ("Failed to allocate plugin context: %s",
2705                                 sstrerror (errno, errbuf, sizeof (errbuf)));
2706                 return NULL;
2707         }
2709         *ctx = ctx_init;
2710         assert (plugin_ctx_key_initialized);
2711         pthread_setspecific (plugin_ctx_key, ctx);
2712         DEBUG("Created new plugin context.");
2713         return (ctx);
2714 } /* int plugin_ctx_create */
2716 void plugin_init_ctx (void)
2718         pthread_key_create (&plugin_ctx_key, plugin_ctx_destructor);
2719         plugin_ctx_key_initialized = 1;
2720 } /* void plugin_init_ctx */
2722 plugin_ctx_t plugin_get_ctx (void)
2724         plugin_ctx_t *ctx;
2726         assert (plugin_ctx_key_initialized);
2727         ctx = pthread_getspecific (plugin_ctx_key);
2729         if (ctx == NULL) {
2730                 ctx = plugin_ctx_create ();
2731                 /* this must no happen -- exit() instead? */
2732                 if (ctx == NULL)
2733                         return ctx_init;
2734         }
2736         return (*ctx);
2737 } /* plugin_ctx_t plugin_get_ctx */
2739 plugin_ctx_t plugin_set_ctx (plugin_ctx_t ctx)
2741         plugin_ctx_t *c;
2742         plugin_ctx_t old;
2744         assert (plugin_ctx_key_initialized);
2745         c = pthread_getspecific (plugin_ctx_key);
2747         if (c == NULL) {
2748                 c = plugin_ctx_create ();
2749                 /* this must no happen -- exit() instead? */
2750                 if (c == NULL)
2751                         return ctx_init;
2752         }
2754         old = *c;
2755         *c = ctx;
2757         return (old);
2758 } /* void plugin_set_ctx */
2760 cdtime_t plugin_get_interval (void)
2762         cdtime_t interval;
2764         interval = plugin_get_ctx().interval;
2765         if (interval > 0)
2766                 return interval;
2768         return cf_get_default_interval ();
2769 } /* cdtime_t plugin_get_interval */
2771 typedef struct {
2772         plugin_ctx_t ctx;
2773         void *(*start_routine) (void *);
2774         void *arg;
2775 } plugin_thread_t;
2777 static void *plugin_thread_start (void *arg)
2779         plugin_thread_t *plugin_thread = arg;
2781         void *(*start_routine) (void *) = plugin_thread->start_routine;
2782         void *plugin_arg = plugin_thread->arg;
2784         plugin_set_ctx (plugin_thread->ctx);
2786         sfree (plugin_thread);
2788         return start_routine (plugin_arg);
2789 } /* void *plugin_thread_start */
2791 int plugin_thread_create (pthread_t *thread, const pthread_attr_t *attr,
2792                 void *(*start_routine) (void *), void *arg)
2794         plugin_thread_t *plugin_thread;
2796         plugin_thread = malloc (sizeof (*plugin_thread));
2797         if (plugin_thread == NULL)
2798                 return -1;
2800         plugin_thread->ctx           = plugin_get_ctx ();
2801         plugin_thread->start_routine = start_routine;
2802         plugin_thread->arg           = arg;
2804         return pthread_create (thread, attr,
2805                         plugin_thread_start, plugin_thread);
2806 } /* int plugin_thread_create */
2808 /* vim: set sw=8 ts=8 noet fdm=marker : */