2 * collectd - src/plugin.c
3 * Copyright (C) 2005-2014 Florian octo Forster
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:
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
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.
24 * Florian octo Forster <octo at collectd.org>
25 * Sebastian Harl <sh at tokkee.org>
33 #include "configfile.h"
34 #include "filter_chain.h"
35 #include "utils_avltree.h"
36 #include "utils_cache.h"
37 #include "utils_complain.h"
38 #include "utils_llist.h"
39 #include "utils_heap.h"
40 #include "utils_time.h"
41 #include "utils_random.h"
48 struct callback_func_s
54 typedef struct callback_func_s callback_func_t;
58 #define RF_REMOVE 65535
61 /* `read_func_t' "inherits" from `callback_func_t'.
62 * The `rf_super' member MUST be the first one in this structure! */
63 #define rf_callback rf_super.cf_callback
64 #define rf_udata rf_super.cf_udata
65 #define rf_ctx rf_super.cf_ctx
66 callback_func_t rf_super;
67 char rf_group[DATA_MAX_NAME_LEN];
71 cdtime_t rf_effective_interval;
72 cdtime_t rf_next_read;
74 typedef struct read_func_s read_func_t;
77 typedef struct write_queue_s write_queue_t;
85 struct flush_callback_s {
89 typedef struct flush_callback_s flush_callback_t;
94 static c_avl_tree_t *plugins_loaded = NULL;
96 static llist_t *list_init;
97 static llist_t *list_write;
98 static llist_t *list_flush;
99 static llist_t *list_missing;
100 static llist_t *list_shutdown;
101 static llist_t *list_log;
102 static llist_t *list_notification;
104 static fc_chain_t *pre_cache_chain = NULL;
105 static fc_chain_t *post_cache_chain = NULL;
107 static c_avl_tree_t *data_sets;
109 static char *plugindir = NULL;
111 #ifndef DEFAULT_MAX_READ_INTERVAL
112 # define DEFAULT_MAX_READ_INTERVAL TIME_T_TO_CDTIME_T_STATIC (86400)
114 static c_heap_t *read_heap = NULL;
115 static llist_t *read_list;
116 static int read_loop = 1;
117 static pthread_mutex_t read_lock = PTHREAD_MUTEX_INITIALIZER;
118 static pthread_cond_t read_cond = PTHREAD_COND_INITIALIZER;
119 static pthread_t *read_threads = NULL;
120 static int read_threads_num = 0;
121 static cdtime_t max_read_interval = DEFAULT_MAX_READ_INTERVAL;
123 static write_queue_t *write_queue_head;
124 static write_queue_t *write_queue_tail;
125 static long write_queue_length = 0;
126 static _Bool write_loop = 1;
127 static pthread_mutex_t write_lock = PTHREAD_MUTEX_INITIALIZER;
128 static pthread_cond_t write_cond = PTHREAD_COND_INITIALIZER;
129 static pthread_t *write_threads = NULL;
130 static size_t write_threads_num = 0;
132 static pthread_key_t plugin_ctx_key;
133 static _Bool plugin_ctx_key_initialized = 0;
135 static long write_limit_high = 0;
136 static long write_limit_low = 0;
138 static derive_t stats_values_dropped = 0;
139 static _Bool record_statistics = 0;
144 static int plugin_dispatch_values_internal (value_list_t *vl);
146 static const char *plugin_get_dir (void)
148 if (plugindir == NULL)
154 static void plugin_update_internal_statistics (void) { /* {{{ */
156 gauge_t copy_write_queue_length = (gauge_t) write_queue_length;
158 /* Initialize `vl' */
159 value_list_t vl = VALUE_LIST_INIT;
160 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
161 sstrncpy (vl.plugin, "collectd", sizeof (vl.plugin));
164 sstrncpy (vl.plugin_instance, "write_queue",
165 sizeof (vl.plugin_instance));
167 /* Write queue : queue length */
168 vl.values = &(value_t) { .gauge = copy_write_queue_length };
170 sstrncpy (vl.type, "queue_length", sizeof (vl.type));
171 vl.type_instance[0] = 0;
172 plugin_dispatch_values (&vl);
174 /* Write queue : Values dropped (queue length > low limit) */
175 vl.values = &(value_t) { .gauge = (gauge_t) stats_values_dropped };
177 sstrncpy (vl.type, "derive", sizeof (vl.type));
178 sstrncpy (vl.type_instance, "dropped", sizeof (vl.type_instance));
179 plugin_dispatch_values (&vl);
182 sstrncpy (vl.plugin_instance, "cache",
183 sizeof (vl.plugin_instance));
185 /* Cache : Nb entry in cache tree */
186 vl.values = &(value_t) { .gauge = (gauge_t) uc_get_size() };
188 sstrncpy (vl.type, "cache_size", sizeof (vl.type));
189 vl.type_instance[0] = 0;
190 plugin_dispatch_values (&vl);
193 } /* }}} void plugin_update_internal_statistics */
195 static void destroy_callback (callback_func_t *cf) /* {{{ */
200 if ((cf->cf_udata.data != NULL) && (cf->cf_udata.free_func != NULL))
202 cf->cf_udata.free_func (cf->cf_udata.data);
203 cf->cf_udata.data = NULL;
204 cf->cf_udata.free_func = NULL;
207 } /* }}} void destroy_callback */
209 static void destroy_all_callbacks (llist_t **list) /* {{{ */
216 le = llist_head (*list);
224 destroy_callback (le->value);
230 llist_destroy (*list);
232 } /* }}} void destroy_all_callbacks */
234 static void destroy_read_heap (void) /* {{{ */
236 if (read_heap == NULL)
243 rf = c_heap_get_root (read_heap);
247 destroy_callback ((callback_func_t *) rf);
250 c_heap_destroy (read_heap);
252 } /* }}} void destroy_read_heap */
254 static int register_callback (llist_t **list, /* {{{ */
255 const char *name, callback_func_t *cf)
262 *list = llist_create ();
265 ERROR ("plugin: register_callback: "
266 "llist_create failed.");
267 destroy_callback (cf);
275 ERROR ("plugin: register_callback: strdup failed.");
276 destroy_callback (cf);
280 le = llist_search (*list, name);
283 le = llentry_create (key, cf);
286 ERROR ("plugin: register_callback: "
287 "llentry_create failed.");
289 destroy_callback (cf);
293 llist_append (*list, le);
297 callback_func_t *old_cf;
302 WARNING ("plugin: register_callback: "
303 "a callback named `%s' already exists - "
304 "overwriting the old entry!", name);
306 destroy_callback (old_cf);
311 } /* }}} int register_callback */
313 static void log_list_callbacks (llist_t **list, /* {{{ */
323 n = llist_size(*list);
326 INFO("%s [none]", comment);
330 keys = calloc(n, sizeof(char*));
334 ERROR("%s: failed to allocate memory for list of callbacks",
340 for (le = llist_head (*list), i = 0, len = 0;
345 len += strlen(le->key) + 6;
347 str = malloc(len + 10);
350 ERROR("%s: failed to allocate memory for list of callbacks",
356 strjoin(str, len, keys, n, "', '");
357 INFO("%s ['%s']", comment, str);
361 } /* }}} void log_list_callbacks */
363 static int create_register_callback (llist_t **list, /* {{{ */
364 const char *name, void *callback, user_data_t const *ud)
368 cf = calloc (1, sizeof (*cf));
371 ERROR ("plugin: create_register_callback: calloc failed.");
375 cf->cf_callback = callback;
378 cf->cf_udata.data = NULL;
379 cf->cf_udata.free_func = NULL;
386 cf->cf_ctx = plugin_get_ctx ();
388 return (register_callback (list, name, cf));
389 } /* }}} int create_register_callback */
391 static int plugin_unregister (llist_t *list, const char *name) /* {{{ */
398 e = llist_search (list, name);
402 llist_remove (list, e);
405 destroy_callback (e->value);
410 } /* }}} int plugin_unregister */
413 * (Try to) load the shared object `file'. Won't complain if it isn't a shared
414 * object, but it will bitch about a shared object not having a
415 * ``module_register'' symbol..
417 static int plugin_load_file (char *file, uint32_t flags)
420 void (*reg_handle) (void);
423 lt_dlerror (); /* clear errors */
425 #if LIBTOOL_VERSION == 2
426 if (flags & PLUGIN_FLAGS_GLOBAL) {
428 lt_dladvise_init(&advise);
429 lt_dladvise_global(&advise);
430 dlh = lt_dlopenadvise(file, advise);
431 lt_dladvise_destroy(&advise);
433 dlh = lt_dlopen (file);
435 #else /* if LIBTOOL_VERSION == 1 */
436 if (flags & PLUGIN_FLAGS_GLOBAL)
437 WARNING ("plugin_load_file: The global flag is not supported, "
438 "libtool 2 is required for this.");
439 dlh = lt_dlopen (file);
444 char errbuf[1024] = "";
446 ssnprintf (errbuf, sizeof (errbuf),
447 "lt_dlopen (\"%s\") failed: %s. "
448 "The most common cause for this problem is "
449 "missing dependencies. Use ldd(1) to check "
450 "the dependencies of the plugin "
452 file, lt_dlerror ());
454 ERROR ("%s", errbuf);
455 /* Make sure this is printed to STDERR in any case, but also
456 * make sure it's printed only once. */
457 if (list_log != NULL)
458 fprintf (stderr, "ERROR: %s\n", errbuf);
463 if ((reg_handle = (void (*) (void)) lt_dlsym (dlh, "module_register")) == NULL)
465 WARNING ("Couldn't find symbol \"module_register\" in \"%s\": %s\n",
466 file, lt_dlerror ());
476 static void *plugin_read_thread (void __attribute__((unused)) *args)
478 while (read_loop != 0)
481 plugin_ctx_t old_ctx;
489 /* Get the read function that needs to be read next.
490 * We don't need to hold "read_lock" for the heap, but we need
491 * to call c_heap_get_root() and pthread_cond_wait() in the
492 * same protected block. */
493 pthread_mutex_lock (&read_lock);
494 rf = c_heap_get_root (read_heap);
497 pthread_cond_wait (&read_cond, &read_lock);
498 pthread_mutex_unlock (&read_lock);
501 pthread_mutex_unlock (&read_lock);
503 if (rf->rf_interval == 0)
505 /* this should not happen, because the interval is set
506 * for each plugin when loading it
507 * XXX: issue a warning? */
508 rf->rf_interval = plugin_get_interval ();
509 rf->rf_effective_interval = rf->rf_interval;
511 rf->rf_next_read = cdtime ();
514 /* sleep until this entry is due,
515 * using pthread_cond_timedwait */
516 pthread_mutex_lock (&read_lock);
517 /* In pthread_cond_timedwait, spurious wakeups are possible
518 * (and really happen, at least on NetBSD with > 1 CPU), thus
519 * we need to re-evaluate the condition every time
520 * pthread_cond_timedwait returns. */
522 while ((read_loop != 0)
523 && (cdtime () < rf->rf_next_read)
526 rc = pthread_cond_timedwait (&read_cond, &read_lock,
527 &CDTIME_T_TO_TIMESPEC (rf->rf_next_read));
530 /* Must hold `read_lock' when accessing `rf->rf_type'. */
531 rf_type = rf->rf_type;
532 pthread_mutex_unlock (&read_lock);
534 /* Check if we're supposed to stop.. This may have interrupted
538 /* Insert `rf' again, so it can be free'd correctly */
539 c_heap_insert (read_heap, rf);
543 /* The entry has been marked for deletion. The linked list
544 * entry has already been removed by `plugin_unregister_read'.
545 * All we have to do here is free the `read_func_t' and
547 if (rf_type == RF_REMOVE)
549 DEBUG ("plugin_read_thread: Destroying the `%s' "
550 "callback.", rf->rf_name);
552 destroy_callback ((callback_func_t *) rf);
557 DEBUG ("plugin_read_thread: Handling `%s'.", rf->rf_name);
561 old_ctx = plugin_set_ctx (rf->rf_ctx);
563 if (rf_type == RF_SIMPLE)
565 int (*callback) (void);
567 callback = rf->rf_callback;
568 status = (*callback) ();
572 plugin_read_cb callback;
574 assert (rf_type == RF_COMPLEX);
576 callback = rf->rf_callback;
577 status = (*callback) (&rf->rf_udata);
580 plugin_set_ctx (old_ctx);
582 /* If the function signals failure, we will increase the
583 * intervals in which it will be called. */
586 rf->rf_effective_interval *= 2;
587 if (rf->rf_effective_interval > max_read_interval)
588 rf->rf_effective_interval = max_read_interval;
590 NOTICE ("read-function of plugin `%s' failed. "
591 "Will suspend it for %.3f seconds.",
593 CDTIME_T_TO_DOUBLE (rf->rf_effective_interval));
597 /* Success: Restore the interval, if it was changed. */
598 rf->rf_effective_interval = rf->rf_interval;
601 /* update the ``next read due'' field */
604 /* calculate the time spent in the read function */
605 elapsed = (now - start);
607 if (elapsed > rf->rf_effective_interval)
608 WARNING ("plugin_read_thread: read-function of the `%s' plugin took %.3f "
609 "seconds, which is above its read interval (%.3f seconds). You might "
610 "want to adjust the `Interval' or `ReadThreads' settings.",
611 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed),
612 CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
614 DEBUG ("plugin_read_thread: read-function of the `%s' plugin took "
616 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed));
618 DEBUG ("plugin_read_thread: Effective interval of the "
619 "`%s' plugin is %.3f seconds.",
621 CDTIME_T_TO_DOUBLE (rf->rf_effective_interval));
623 /* Calculate the next (absolute) time at which this function
624 * should be called. */
625 rf->rf_next_read += rf->rf_effective_interval;
627 /* Check, if `rf_next_read' is in the past. */
628 if (rf->rf_next_read < now)
630 /* `rf_next_read' is in the past. Insert `now'
631 * so this value doesn't trail off into the
633 rf->rf_next_read = now;
636 DEBUG ("plugin_read_thread: Next read of the `%s' plugin at %.3f.",
638 CDTIME_T_TO_DOUBLE (rf->rf_next_read));
640 /* Re-insert this read function into the heap again. */
641 c_heap_insert (read_heap, rf);
642 } /* while (read_loop) */
646 } /* void *plugin_read_thread */
648 static void start_read_threads (int num)
650 if (read_threads != NULL)
653 read_threads = (pthread_t *) calloc (num, sizeof (pthread_t));
654 if (read_threads == NULL)
656 ERROR ("plugin: start_read_threads: calloc failed.");
660 read_threads_num = 0;
661 for (int i = 0; i < num; i++)
663 if (pthread_create (read_threads + read_threads_num, NULL,
664 plugin_read_thread, NULL) == 0)
666 #if defined(HAVE_PTHREAD_SETNAME_NP) || defined(HAVE_PTHREAD_SET_NAME_NP)
667 char thread_name[16];
668 sstrncpy (thread_name, "plugin reader", sizeof(thread_name));
669 # if defined(HAVE_PTHREAD_SETNAME_NP)
670 pthread_setname_np (*(read_threads + read_threads_num),
672 # elif defined(HAVE_PTHREAD_SET_NAME_NP)
673 pthread_set_name_np (*(read_threads + read_threads_num),
681 ERROR ("plugin: start_read_threads: pthread_create failed.");
685 } /* void start_read_threads */
687 static void stop_read_threads (void)
689 if (read_threads == NULL)
692 INFO ("collectd: Stopping %i read threads.", read_threads_num);
694 pthread_mutex_lock (&read_lock);
696 DEBUG ("plugin: stop_read_threads: Signalling `read_cond'");
697 pthread_cond_broadcast (&read_cond);
698 pthread_mutex_unlock (&read_lock);
700 for (int i = 0; i < read_threads_num; i++)
702 if (pthread_join (read_threads[i], NULL) != 0)
704 ERROR ("plugin: stop_read_threads: pthread_join failed.");
706 read_threads[i] = (pthread_t) 0;
708 sfree (read_threads);
709 read_threads_num = 0;
710 } /* void stop_read_threads */
712 static void plugin_value_list_free (value_list_t *vl) /* {{{ */
717 meta_data_destroy (vl->meta);
720 } /* }}} void plugin_value_list_free */
722 static value_list_t *plugin_value_list_clone (value_list_t const *vl_orig) /* {{{ */
729 vl = malloc (sizeof (*vl));
732 memcpy (vl, vl_orig, sizeof (*vl));
734 if (vl->host[0] == 0)
735 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
737 vl->values = calloc (vl_orig->values_len, sizeof (*vl->values));
738 if (vl->values == NULL)
740 plugin_value_list_free (vl);
743 memcpy (vl->values, vl_orig->values,
744 vl_orig->values_len * sizeof (*vl->values));
746 vl->meta = meta_data_clone (vl->meta);
747 if ((vl_orig->meta != NULL) && (vl->meta == NULL))
749 plugin_value_list_free (vl);
754 vl->time = cdtime ();
756 /* Fill in the interval from the thread context, if it is zero. */
757 if (vl->interval == 0)
759 plugin_ctx_t ctx = plugin_get_ctx ();
761 if (ctx.interval != 0)
762 vl->interval = ctx.interval;
765 char name[6 * DATA_MAX_NAME_LEN];
766 FORMAT_VL (name, sizeof (name), vl);
767 ERROR ("plugin_value_list_clone: Unable to determine "
768 "interval from context for "
769 "value list \"%s\". "
770 "This indicates a broken plugin. "
771 "Please report this problem to the "
772 "collectd mailing list or at "
773 "<http://collectd.org/bugs/>.", name);
774 vl->interval = cf_get_default_interval ();
779 } /* }}} value_list_t *plugin_value_list_clone */
781 static int plugin_write_enqueue (value_list_t const *vl) /* {{{ */
785 q = malloc (sizeof (*q));
790 q->vl = plugin_value_list_clone (vl);
797 /* Store context of caller (read plugin); otherwise, it would not be
798 * available to the write plugins when actually dispatching the
799 * value-list later on. */
800 q->ctx = plugin_get_ctx ();
802 pthread_mutex_lock (&write_lock);
804 if (write_queue_tail == NULL)
806 write_queue_head = q;
807 write_queue_tail = q;
808 write_queue_length = 1;
812 write_queue_tail->next = q;
813 write_queue_tail = q;
814 write_queue_length += 1;
817 pthread_cond_signal (&write_cond);
818 pthread_mutex_unlock (&write_lock);
821 } /* }}} int plugin_write_enqueue */
823 static value_list_t *plugin_write_dequeue (void) /* {{{ */
828 pthread_mutex_lock (&write_lock);
830 while (write_loop && (write_queue_head == NULL))
831 pthread_cond_wait (&write_cond, &write_lock);
833 if (write_queue_head == NULL)
835 pthread_mutex_unlock (&write_lock);
839 q = write_queue_head;
840 write_queue_head = q->next;
841 write_queue_length -= 1;
842 if (write_queue_head == NULL) {
843 write_queue_tail = NULL;
844 assert(0 == write_queue_length);
847 pthread_mutex_unlock (&write_lock);
849 (void) plugin_set_ctx (q->ctx);
854 } /* }}} value_list_t *plugin_write_dequeue */
856 static void *plugin_write_thread (void __attribute__((unused)) *args) /* {{{ */
860 value_list_t *vl = plugin_write_dequeue ();
864 plugin_dispatch_values_internal (vl);
866 plugin_value_list_free (vl);
871 } /* }}} void *plugin_write_thread */
873 static void start_write_threads (size_t num) /* {{{ */
875 if (write_threads != NULL)
878 write_threads = (pthread_t *) calloc (num, sizeof (pthread_t));
879 if (write_threads == NULL)
881 ERROR ("plugin: start_write_threads: calloc failed.");
885 write_threads_num = 0;
886 for (size_t i = 0; i < num; i++)
890 status = pthread_create (write_threads + write_threads_num,
897 ERROR ("plugin: start_write_threads: pthread_create failed "
898 "with status %i (%s).", status,
899 sstrerror (status, errbuf, sizeof (errbuf)));
902 #if defined(HAVE_PTHREAD_SETNAME_NP) || defined(HAVE_PTHREAD_SET_NAME_NP)
903 char thread_name[16];
904 sstrncpy (thread_name, "plugin writer", sizeof(thread_name));
905 # if defined(HAVE_PTHREAD_SETNAME_NP)
906 pthread_setname_np (*(write_threads + write_threads_num),
908 # elif defined(HAVE_PTHREAD_SET_NAME_NP)
909 pthread_set_name_np (*(write_threads + write_threads_num),
916 } /* }}} void start_write_threads */
918 static void stop_write_threads (void) /* {{{ */
923 if (write_threads == NULL)
926 INFO ("collectd: Stopping %zu write threads.", write_threads_num);
928 pthread_mutex_lock (&write_lock);
930 DEBUG ("plugin: stop_write_threads: Signalling `write_cond'");
931 pthread_cond_broadcast (&write_cond);
932 pthread_mutex_unlock (&write_lock);
934 for (i = 0; i < write_threads_num; i++)
936 if (pthread_join (write_threads[i], NULL) != 0)
938 ERROR ("plugin: stop_write_threads: pthread_join failed.");
940 write_threads[i] = (pthread_t) 0;
942 sfree (write_threads);
943 write_threads_num = 0;
945 pthread_mutex_lock (&write_lock);
947 for (q = write_queue_head; q != NULL; )
949 write_queue_t *q1 = q;
950 plugin_value_list_free (q->vl);
955 write_queue_head = NULL;
956 write_queue_tail = NULL;
957 write_queue_length = 0;
958 pthread_mutex_unlock (&write_lock);
962 WARNING ("plugin: %zu value list%s left after shutting down "
963 "the write threads.",
964 i, (i == 1) ? " was" : "s were");
966 } /* }}} void stop_write_threads */
971 void plugin_set_dir (const char *dir)
981 plugindir = strdup (dir);
982 if (plugindir == NULL)
983 ERROR ("plugin_set_dir: strdup(\"%s\") failed", dir);
986 static _Bool plugin_is_loaded (char const *name)
990 if (plugins_loaded == NULL)
991 plugins_loaded = c_avl_create ((int (*) (const void *, const void *)) strcasecmp);
992 assert (plugins_loaded != NULL);
994 status = c_avl_get (plugins_loaded, name, /* ret_value = */ NULL);
995 return (status == 0);
998 static int plugin_mark_loaded (char const *name)
1003 name_copy = strdup (name);
1004 if (name_copy == NULL)
1007 status = c_avl_insert (plugins_loaded,
1008 /* key = */ name_copy, /* value = */ NULL);
1012 static void plugin_free_loaded (void)
1017 if (plugins_loaded == NULL)
1020 while (c_avl_pick (plugins_loaded, &key, &value) == 0)
1023 assert (value == NULL);
1026 c_avl_destroy (plugins_loaded);
1027 plugins_loaded = NULL;
1031 int plugin_load (char const *plugin_name, uint32_t flags)
1035 char filename[BUFSIZE] = "";
1036 char typename[BUFSIZE];
1038 struct stat statbuf;
1042 if (plugin_name == NULL)
1045 /* Check if plugin is already loaded and don't do anything in this
1047 if (plugin_is_loaded (plugin_name))
1050 dir = plugin_get_dir ();
1054 * XXX: Magic at work:
1056 * Some of the language bindings, for example the Python and Perl
1057 * plugins, need to be able to export symbols to the scripts they run.
1058 * For this to happen, the "Globals" flag needs to be set.
1059 * Unfortunately, this technical detail is hard to explain to the
1060 * average user and she shouldn't have to worry about this, ideally.
1061 * So in order to save everyone's sanity use a different default for a
1062 * handful of special plugins. --octo
1064 if ((strcasecmp ("perl", plugin_name) == 0)
1065 || (strcasecmp ("python", plugin_name) == 0))
1066 flags |= PLUGIN_FLAGS_GLOBAL;
1068 /* `cpu' should not match `cpufreq'. To solve this we add `.so' to the
1069 * type when matching the filename */
1070 status = ssnprintf (typename, sizeof (typename), "%s.so", plugin_name);
1071 if ((status < 0) || ((size_t) status >= sizeof (typename)))
1073 WARNING ("plugin_load: Filename too long: \"%s.so\"", plugin_name);
1077 if ((dh = opendir (dir)) == NULL)
1080 ERROR ("plugin_load: opendir (%s) failed: %s", dir,
1081 sstrerror (errno, errbuf, sizeof (errbuf)));
1085 while ((de = readdir (dh)) != NULL)
1087 if (strcasecmp (de->d_name, typename))
1090 status = ssnprintf (filename, sizeof (filename),
1091 "%s/%s", dir, de->d_name);
1092 if ((status < 0) || ((size_t) status >= sizeof (filename)))
1094 WARNING ("plugin_load: Filename too long: \"%s/%s\"",
1099 if (lstat (filename, &statbuf) == -1)
1102 WARNING ("plugin_load: stat (\"%s\") failed: %s",
1104 sstrerror (errno, errbuf, sizeof (errbuf)));
1107 else if (!S_ISREG (statbuf.st_mode))
1109 /* don't follow symlinks */
1110 WARNING ("plugin_load: %s is not a regular file.",
1115 status = plugin_load_file (filename, flags);
1119 plugin_mark_loaded (plugin_name);
1121 INFO ("plugin_load: plugin \"%s\" successfully loaded.", plugin_name);
1126 ERROR ("plugin_load: Load plugin \"%s\" failed with "
1127 "status %i.", plugin_name, status);
1133 if (filename[0] == 0)
1134 ERROR ("plugin_load: Could not find plugin \"%s\" in %s",
1141 * The `register_*' functions follow
1143 int plugin_register_config (const char *name,
1144 int (*callback) (const char *key, const char *val),
1145 const char **keys, int keys_num)
1147 cf_register (name, callback, keys, keys_num);
1149 } /* int plugin_register_config */
1151 int plugin_register_complex_config (const char *type,
1152 int (*callback) (oconfig_item_t *))
1154 return (cf_register_complex (type, callback));
1155 } /* int plugin_register_complex_config */
1157 int plugin_register_init (const char *name,
1158 int (*callback) (void))
1160 return (create_register_callback (&list_init, name, (void *) callback,
1161 /* user_data = */ NULL));
1162 } /* plugin_register_init */
1164 static int plugin_compare_read_func (const void *arg0, const void *arg1)
1166 const read_func_t *rf0;
1167 const read_func_t *rf1;
1172 if (rf0->rf_next_read < rf1->rf_next_read)
1174 else if (rf0->rf_next_read > rf1->rf_next_read)
1178 } /* int plugin_compare_read_func */
1180 /* Add a read function to both, the heap and a linked list. The linked list if
1181 * used to look-up read functions, especially for the remove function. The heap
1182 * is used to determine which plugin to read next. */
1183 static int plugin_insert_read (read_func_t *rf)
1188 rf->rf_next_read = cdtime ();
1189 rf->rf_effective_interval = rf->rf_interval;
1191 pthread_mutex_lock (&read_lock);
1193 if (read_list == NULL)
1195 read_list = llist_create ();
1196 if (read_list == NULL)
1198 pthread_mutex_unlock (&read_lock);
1199 ERROR ("plugin_insert_read: read_list failed.");
1204 if (read_heap == NULL)
1206 read_heap = c_heap_create (plugin_compare_read_func);
1207 if (read_heap == NULL)
1209 pthread_mutex_unlock (&read_lock);
1210 ERROR ("plugin_insert_read: c_heap_create failed.");
1215 le = llist_search (read_list, rf->rf_name);
1218 pthread_mutex_unlock (&read_lock);
1219 WARNING ("The read function \"%s\" is already registered. "
1220 "Check for duplicate \"LoadPlugin\" lines "
1221 "in your configuration!",
1226 le = llentry_create (rf->rf_name, rf);
1229 pthread_mutex_unlock (&read_lock);
1230 ERROR ("plugin_insert_read: llentry_create failed.");
1234 status = c_heap_insert (read_heap, rf);
1237 pthread_mutex_unlock (&read_lock);
1238 ERROR ("plugin_insert_read: c_heap_insert failed.");
1239 llentry_destroy (le);
1243 /* This does not fail. */
1244 llist_append (read_list, le);
1246 /* Wake up all the read threads. */
1247 pthread_cond_broadcast (&read_cond);
1248 pthread_mutex_unlock (&read_lock);
1250 } /* int plugin_insert_read */
1252 int plugin_register_read (const char *name,
1253 int (*callback) (void))
1258 rf = calloc (1, sizeof (*rf));
1261 ERROR ("plugin_register_read: calloc failed.");
1265 rf->rf_callback = (void *) callback;
1266 rf->rf_udata.data = NULL;
1267 rf->rf_udata.free_func = NULL;
1268 rf->rf_ctx = plugin_get_ctx ();
1269 rf->rf_group[0] = '\0';
1270 rf->rf_name = strdup (name);
1271 rf->rf_type = RF_SIMPLE;
1272 rf->rf_interval = plugin_get_interval ();
1274 status = plugin_insert_read (rf);
1276 sfree (rf->rf_name);
1281 } /* int plugin_register_read */
1283 int plugin_register_complex_read (const char *group, const char *name,
1284 plugin_read_cb callback,
1286 user_data_t const *user_data)
1291 rf = calloc (1,sizeof (*rf));
1294 ERROR ("plugin_register_complex_read: calloc failed.");
1298 rf->rf_callback = (void *) callback;
1300 sstrncpy (rf->rf_group, group, sizeof (rf->rf_group));
1302 rf->rf_group[0] = '\0';
1303 rf->rf_name = strdup (name);
1304 rf->rf_type = RF_COMPLEX;
1305 rf->rf_interval = (interval != 0) ? interval : plugin_get_interval ();
1308 if (user_data == NULL)
1310 rf->rf_udata.data = NULL;
1311 rf->rf_udata.free_func = NULL;
1315 rf->rf_udata = *user_data;
1318 rf->rf_ctx = plugin_get_ctx ();
1320 status = plugin_insert_read (rf);
1322 sfree (rf->rf_name);
1327 } /* int plugin_register_complex_read */
1329 int plugin_register_write (const char *name,
1330 plugin_write_cb callback, user_data_t const *ud)
1332 return (create_register_callback (&list_write, name,
1333 (void *) callback, ud));
1334 } /* int plugin_register_write */
1336 static int plugin_flush_timeout_callback (user_data_t *ud)
1338 flush_callback_t *cb = ud->data;
1340 return plugin_flush (cb->name, cb->timeout, /* identifier = */ NULL);
1341 } /* static int plugin_flush_callback */
1343 static void plugin_flush_timeout_callback_free (void *data)
1345 flush_callback_t *cb = data;
1347 if (cb == NULL) return;
1351 } /* static void plugin_flush_callback_free */
1353 static char *plugin_flush_callback_name (const char *name)
1355 const char *flush_prefix = "flush/";
1360 prefix_size = strlen(flush_prefix);
1361 name_size = strlen(name);
1363 flush_name = malloc (name_size + prefix_size + 1);
1364 if (flush_name == NULL)
1366 ERROR ("plugin_flush_callback_name: malloc failed.");
1370 sstrncpy (flush_name, flush_prefix, prefix_size + 1);
1371 sstrncpy (flush_name + prefix_size, name, name_size + 1);
1374 } /* static char *plugin_flush_callback_name */
1376 int plugin_register_flush (const char *name,
1377 plugin_flush_cb callback, user_data_t const *ud)
1380 plugin_ctx_t ctx = plugin_get_ctx ();
1382 status = create_register_callback (&list_flush, name,
1383 (void *) callback, ud);
1387 if (ctx.flush_interval != 0)
1390 flush_callback_t *cb;
1392 flush_name = plugin_flush_callback_name (name);
1393 if (flush_name == NULL)
1396 cb = malloc(sizeof (*cb));
1399 ERROR ("plugin_register_flush: malloc failed.");
1404 cb->name = strdup (name);
1405 if (cb->name == NULL)
1407 ERROR ("plugin_register_flush: strdup failed.");
1412 cb->timeout = ctx.flush_timeout;
1414 status = plugin_register_complex_read (
1415 /* group = */ "flush",
1416 /* name = */ flush_name,
1417 /* callback = */ plugin_flush_timeout_callback,
1418 /* interval = */ ctx.flush_interval,
1419 /* user data = */ &(user_data_t) {
1421 .free_func = plugin_flush_timeout_callback_free,
1434 } /* int plugin_register_flush */
1436 int plugin_register_missing (const char *name,
1437 plugin_missing_cb callback, user_data_t const *ud)
1439 return (create_register_callback (&list_missing, name,
1440 (void *) callback, ud));
1441 } /* int plugin_register_missing */
1443 int plugin_register_shutdown (const char *name,
1444 int (*callback) (void))
1446 return (create_register_callback (&list_shutdown, name,
1447 (void *) callback, /* user_data = */ NULL));
1448 } /* int plugin_register_shutdown */
1450 static void plugin_free_data_sets (void)
1455 if (data_sets == NULL)
1458 while (c_avl_pick (data_sets, &key, &value) == 0)
1460 data_set_t *ds = value;
1461 /* key is a pointer to ds->type */
1467 c_avl_destroy (data_sets);
1469 } /* void plugin_free_data_sets */
1471 int plugin_register_data_set (const data_set_t *ds)
1473 data_set_t *ds_copy;
1475 if ((data_sets != NULL)
1476 && (c_avl_get (data_sets, ds->type, NULL) == 0))
1478 NOTICE ("Replacing DS `%s' with another version.", ds->type);
1479 plugin_unregister_data_set (ds->type);
1481 else if (data_sets == NULL)
1483 data_sets = c_avl_create ((int (*) (const void *, const void *)) strcmp);
1484 if (data_sets == NULL)
1488 ds_copy = malloc (sizeof (*ds_copy));
1489 if (ds_copy == NULL)
1491 memcpy(ds_copy, ds, sizeof (data_set_t));
1493 ds_copy->ds = malloc (sizeof (*ds_copy->ds)
1495 if (ds_copy->ds == NULL)
1501 for (size_t i = 0; i < ds->ds_num; i++)
1502 memcpy (ds_copy->ds + i, ds->ds + i, sizeof (data_source_t));
1504 return (c_avl_insert (data_sets, (void *) ds_copy->type, (void *) ds_copy));
1505 } /* int plugin_register_data_set */
1507 int plugin_register_log (const char *name,
1508 plugin_log_cb callback, user_data_t const *ud)
1510 return (create_register_callback (&list_log, name,
1511 (void *) callback, ud));
1512 } /* int plugin_register_log */
1514 int plugin_register_notification (const char *name,
1515 plugin_notification_cb callback, user_data_t const *ud)
1517 return (create_register_callback (&list_notification, name,
1518 (void *) callback, ud));
1519 } /* int plugin_register_log */
1521 int plugin_unregister_config (const char *name)
1523 cf_unregister (name);
1525 } /* int plugin_unregister_config */
1527 int plugin_unregister_complex_config (const char *name)
1529 cf_unregister_complex (name);
1531 } /* int plugin_unregister_complex_config */
1533 int plugin_unregister_init (const char *name)
1535 return (plugin_unregister (list_init, name));
1538 int plugin_unregister_read (const char *name) /* {{{ */
1546 pthread_mutex_lock (&read_lock);
1548 if (read_list == NULL)
1550 pthread_mutex_unlock (&read_lock);
1554 le = llist_search (read_list, name);
1557 pthread_mutex_unlock (&read_lock);
1558 WARNING ("plugin_unregister_read: No such read function: %s",
1563 llist_remove (read_list, le);
1566 assert (rf != NULL);
1567 rf->rf_type = RF_REMOVE;
1569 pthread_mutex_unlock (&read_lock);
1571 llentry_destroy (le);
1573 DEBUG ("plugin_unregister_read: Marked `%s' for removal.", name);
1576 } /* }}} int plugin_unregister_read */
1578 void plugin_log_available_writers (void)
1580 log_list_callbacks (&list_write, "Available write targets:");
1583 static int compare_read_func_group (llentry_t *e, void *ud) /* {{{ */
1585 read_func_t *rf = e->value;
1588 return strcmp (rf->rf_group, (const char *)group);
1589 } /* }}} int compare_read_func_group */
1591 int plugin_unregister_read_group (const char *group) /* {{{ */
1601 pthread_mutex_lock (&read_lock);
1603 if (read_list == NULL)
1605 pthread_mutex_unlock (&read_lock);
1611 le = llist_search_custom (read_list,
1612 compare_read_func_group, (void *)group);
1619 llist_remove (read_list, le);
1622 assert (rf != NULL);
1623 rf->rf_type = RF_REMOVE;
1625 llentry_destroy (le);
1627 DEBUG ("plugin_unregister_read_group: "
1628 "Marked `%s' (group `%s') for removal.",
1629 rf->rf_name, group);
1632 pthread_mutex_unlock (&read_lock);
1636 WARNING ("plugin_unregister_read_group: No such "
1637 "group of read function: %s", group);
1642 } /* }}} int plugin_unregister_read_group */
1644 int plugin_unregister_write (const char *name)
1646 return (plugin_unregister (list_write, name));
1649 int plugin_unregister_flush (const char *name)
1651 plugin_ctx_t ctx = plugin_get_ctx ();
1653 if (ctx.flush_interval != 0)
1657 flush_name = plugin_flush_callback_name (name);
1658 if (flush_name != NULL)
1660 plugin_unregister_read(flush_name);
1665 return plugin_unregister (list_flush, name);
1668 int plugin_unregister_missing (const char *name)
1670 return (plugin_unregister (list_missing, name));
1673 int plugin_unregister_shutdown (const char *name)
1675 return (plugin_unregister (list_shutdown, name));
1678 int plugin_unregister_data_set (const char *name)
1682 if (data_sets == NULL)
1685 if (c_avl_remove (data_sets, name, NULL, (void *) &ds) != 0)
1692 } /* int plugin_unregister_data_set */
1694 int plugin_unregister_log (const char *name)
1696 return (plugin_unregister (list_log, name));
1699 int plugin_unregister_notification (const char *name)
1701 return (plugin_unregister (list_notification, name));
1704 int plugin_init_all (void)
1706 char const *chain_name;
1711 /* Init the value cache */
1714 if (IS_TRUE (global_option_get ("CollectInternalStats")))
1715 record_statistics = 1;
1717 chain_name = global_option_get ("PreCacheChain");
1718 pre_cache_chain = fc_chain_get_by_name (chain_name);
1720 chain_name = global_option_get ("PostCacheChain");
1721 post_cache_chain = fc_chain_get_by_name (chain_name);
1723 write_limit_high = global_option_get_long ("WriteQueueLimitHigh",
1725 if (write_limit_high < 0)
1727 ERROR ("WriteQueueLimitHigh must be positive or zero.");
1728 write_limit_high = 0;
1731 write_limit_low = global_option_get_long ("WriteQueueLimitLow",
1732 /* default = */ write_limit_high / 2);
1733 if (write_limit_low < 0)
1735 ERROR ("WriteQueueLimitLow must be positive or zero.");
1736 write_limit_low = write_limit_high / 2;
1738 else if (write_limit_low > write_limit_high)
1740 ERROR ("WriteQueueLimitLow must not be larger than "
1741 "WriteQueueLimitHigh.");
1742 write_limit_low = write_limit_high;
1745 write_threads_num = global_option_get_long ("WriteThreads",
1747 if (write_threads_num < 1)
1749 ERROR ("WriteThreads must be positive.");
1750 write_threads_num = 5;
1753 if ((list_init == NULL) && (read_heap == NULL))
1756 /* Calling all init callbacks before checking if read callbacks
1757 * are available allows the init callbacks to register the read
1759 le = llist_head (list_init);
1762 callback_func_t *cf;
1763 plugin_init_cb callback;
1764 plugin_ctx_t old_ctx;
1767 old_ctx = plugin_set_ctx (cf->cf_ctx);
1768 callback = cf->cf_callback;
1769 status = (*callback) ();
1770 plugin_set_ctx (old_ctx);
1774 ERROR ("Initialization of plugin `%s' "
1775 "failed with status %i. "
1776 "Plugin will be unloaded.",
1778 /* Plugins that register read callbacks from the init
1779 * callback should take care of appropriate error
1780 * handling themselves. */
1781 /* FIXME: Unload _all_ functions */
1782 plugin_unregister_read (le->key);
1789 start_write_threads ((size_t) write_threads_num);
1791 max_read_interval = global_option_get_time ("MaxReadInterval",
1792 DEFAULT_MAX_READ_INTERVAL);
1794 /* Start read-threads */
1795 if (read_heap != NULL)
1800 rt = global_option_get ("ReadThreads");
1803 start_read_threads ((num > 0) ? num : 5);
1806 } /* void plugin_init_all */
1808 /* TODO: Rename this function. */
1809 void plugin_read_all (void)
1811 if(record_statistics) {
1812 plugin_update_internal_statistics ();
1814 uc_check_timeout ();
1817 } /* void plugin_read_all */
1819 /* Read function called when the `-T' command line argument is given. */
1820 int plugin_read_all_once (void)
1823 int return_status = 0;
1825 if (read_heap == NULL)
1827 NOTICE ("No read-functions are registered.");
1834 plugin_ctx_t old_ctx;
1836 rf = c_heap_get_root (read_heap);
1840 old_ctx = plugin_set_ctx (rf->rf_ctx);
1842 if (rf->rf_type == RF_SIMPLE)
1844 int (*callback) (void);
1846 callback = rf->rf_callback;
1847 status = (*callback) ();
1851 plugin_read_cb callback;
1853 callback = rf->rf_callback;
1854 status = (*callback) (&rf->rf_udata);
1857 plugin_set_ctx (old_ctx);
1861 NOTICE ("read-function of plugin `%s' failed.",
1866 sfree (rf->rf_name);
1867 destroy_callback ((void *) rf);
1870 return (return_status);
1871 } /* int plugin_read_all_once */
1873 int plugin_write (const char *plugin, /* {{{ */
1874 const data_set_t *ds, const value_list_t *vl)
1882 if (list_write == NULL)
1887 ds = plugin_get_ds (vl->type);
1890 ERROR ("plugin_write: Unable to lookup type `%s'.", vl->type);
1900 le = llist_head (list_write);
1903 callback_func_t *cf = le->value;
1904 plugin_write_cb callback;
1906 /* do not switch plugin context; rather keep the context (interval)
1907 * information of the calling read plugin */
1909 DEBUG ("plugin: plugin_write: Writing values via %s.", le->key);
1910 callback = cf->cf_callback;
1911 status = (*callback) (ds, vl, &cf->cf_udata);
1920 if ((success == 0) && (failure != 0))
1925 else /* plugin != NULL */
1927 callback_func_t *cf;
1928 plugin_write_cb callback;
1930 le = llist_head (list_write);
1933 if (strcasecmp (plugin, le->key) == 0)
1944 /* do not switch plugin context; rather keep the context (interval)
1945 * information of the calling read plugin */
1947 DEBUG ("plugin: plugin_write: Writing values via %s.", le->key);
1948 callback = cf->cf_callback;
1949 status = (*callback) (ds, vl, &cf->cf_udata);
1953 } /* }}} int plugin_write */
1955 int plugin_flush (const char *plugin, cdtime_t timeout, const char *identifier)
1959 if (list_flush == NULL)
1962 le = llist_head (list_flush);
1965 callback_func_t *cf;
1966 plugin_flush_cb callback;
1967 plugin_ctx_t old_ctx;
1969 if ((plugin != NULL)
1970 && (strcmp (plugin, le->key) != 0))
1977 old_ctx = plugin_set_ctx (cf->cf_ctx);
1978 callback = cf->cf_callback;
1980 (*callback) (timeout, identifier, &cf->cf_udata);
1982 plugin_set_ctx (old_ctx);
1987 } /* int plugin_flush */
1989 int plugin_shutdown_all (void)
1992 int ret = 0; // Assume success.
1994 destroy_all_callbacks (&list_init);
1996 stop_read_threads ();
1998 pthread_mutex_lock (&read_lock);
1999 llist_destroy (read_list);
2001 pthread_mutex_unlock (&read_lock);
2003 destroy_read_heap ();
2005 /* blocks until all write threads have shut down. */
2006 stop_write_threads ();
2008 /* ask all plugins to write out the state they kept. */
2009 plugin_flush (/* plugin = */ NULL,
2011 /* identifier = */ NULL);
2014 if (list_shutdown != NULL)
2015 le = llist_head (list_shutdown);
2019 callback_func_t *cf;
2020 plugin_shutdown_cb callback;
2021 plugin_ctx_t old_ctx;
2024 old_ctx = plugin_set_ctx (cf->cf_ctx);
2025 callback = cf->cf_callback;
2027 /* Advance the pointer before calling the callback allows
2028 * shutdown functions to unregister themselves. If done the
2029 * other way around the memory `le' points to will be freed
2030 * after callback returns. */
2033 if ((*callback) () != 0)
2036 plugin_set_ctx (old_ctx);
2039 /* Write plugins which use the `user_data' pointer usually need the
2040 * same data available to the flush callback. If this is the case, set
2041 * the free_function to NULL when registering the flush callback and to
2042 * the real free function when registering the write callback. This way
2043 * the data isn't freed twice. */
2044 destroy_all_callbacks (&list_flush);
2045 destroy_all_callbacks (&list_missing);
2046 destroy_all_callbacks (&list_write);
2048 destroy_all_callbacks (&list_notification);
2049 destroy_all_callbacks (&list_shutdown);
2050 destroy_all_callbacks (&list_log);
2052 plugin_free_loaded ();
2053 plugin_free_data_sets ();
2055 } /* void plugin_shutdown_all */
2057 int plugin_dispatch_missing (const value_list_t *vl) /* {{{ */
2061 if (list_missing == NULL)
2064 le = llist_head (list_missing);
2067 callback_func_t *cf;
2068 plugin_missing_cb callback;
2069 plugin_ctx_t old_ctx;
2073 old_ctx = plugin_set_ctx (cf->cf_ctx);
2074 callback = cf->cf_callback;
2076 status = (*callback) (vl, &cf->cf_udata);
2077 plugin_set_ctx (old_ctx);
2082 ERROR ("plugin_dispatch_missing: Callback function \"%s\" "
2083 "failed with status %i.",
2096 } /* int }}} plugin_dispatch_missing */
2098 static int plugin_dispatch_values_internal (value_list_t *vl)
2101 static c_complain_t no_write_complaint = C_COMPLAIN_INIT_STATIC;
2105 _Bool free_meta_data = 0;
2107 assert (vl != NULL);
2109 /* These fields are initialized by plugin_value_list_clone() if needed: */
2110 assert (vl->host[0] != 0);
2111 assert (vl->time != 0); /* The time is determined at _enqueue_ time. */
2112 assert (vl->interval != 0);
2114 if (vl->type[0] == 0 || vl->values == NULL || vl->values_len < 1)
2116 ERROR ("plugin_dispatch_values: Invalid value list "
2117 "from plugin %s.", vl->plugin);
2121 /* Free meta data only if the calling function didn't specify any. In
2122 * this case matches and targets may add some and the calling function
2123 * may not expect (and therefore free) that data. */
2124 if (vl->meta == NULL)
2127 if (list_write == NULL)
2128 c_complain_once (LOG_WARNING, &no_write_complaint,
2129 "plugin_dispatch_values: No write callback has been "
2130 "registered. Please load at least one output plugin, "
2131 "if you want the collected data to be stored.");
2133 if (data_sets == NULL)
2135 ERROR ("plugin_dispatch_values: No data sets registered. "
2136 "Could the types database be read? Check "
2137 "your `TypesDB' setting!");
2141 if (c_avl_get (data_sets, vl->type, (void *) &ds) != 0)
2143 char ident[6 * DATA_MAX_NAME_LEN];
2145 FORMAT_VL (ident, sizeof (ident), vl);
2146 INFO ("plugin_dispatch_values: Dataset not found: %s "
2147 "(from \"%s\"), check your types.db!",
2152 DEBUG ("plugin_dispatch_values: time = %.3f; interval = %.3f; "
2154 "plugin = %s; plugin_instance = %s; "
2155 "type = %s; type_instance = %s;",
2156 CDTIME_T_TO_DOUBLE (vl->time),
2157 CDTIME_T_TO_DOUBLE (vl->interval),
2159 vl->plugin, vl->plugin_instance,
2160 vl->type, vl->type_instance);
2163 assert (0 == strcmp (ds->type, vl->type));
2165 if (0 != strcmp (ds->type, vl->type))
2166 WARNING ("plugin_dispatch_values: (ds->type = %s) != (vl->type = %s)",
2167 ds->type, vl->type);
2171 assert (ds->ds_num == vl->values_len);
2173 if (ds->ds_num != vl->values_len)
2175 ERROR ("plugin_dispatch_values: ds->type = %s: "
2176 "(ds->ds_num = %zu) != "
2177 "(vl->values_len = %zu)",
2178 ds->type, ds->ds_num, vl->values_len);
2183 escape_slashes (vl->host, sizeof (vl->host));
2184 escape_slashes (vl->plugin, sizeof (vl->plugin));
2185 escape_slashes (vl->plugin_instance, sizeof (vl->plugin_instance));
2186 escape_slashes (vl->type, sizeof (vl->type));
2187 escape_slashes (vl->type_instance, sizeof (vl->type_instance));
2189 if (pre_cache_chain != NULL)
2191 status = fc_process_chain (ds, vl, pre_cache_chain);
2194 WARNING ("plugin_dispatch_values: Running the "
2195 "pre-cache chain failed with "
2199 else if (status == FC_TARGET_STOP)
2203 /* Update the value cache */
2206 if (post_cache_chain != NULL)
2208 status = fc_process_chain (ds, vl, post_cache_chain);
2211 WARNING ("plugin_dispatch_values: Running the "
2212 "post-cache chain failed with "
2218 fc_default_action (ds, vl);
2220 if ((free_meta_data != 0) && (vl->meta != NULL))
2222 meta_data_destroy (vl->meta);
2227 } /* int plugin_dispatch_values_internal */
2229 static double get_drop_probability (void) /* {{{ */
2235 pthread_mutex_lock (&write_lock);
2236 wql = write_queue_length;
2237 pthread_mutex_unlock (&write_lock);
2239 if (wql < write_limit_low)
2241 if (wql >= write_limit_high)
2244 pos = 1 + wql - write_limit_low;
2245 size = 1 + write_limit_high - write_limit_low;
2247 return (((double) pos) / ((double) size));
2248 } /* }}} double get_drop_probability */
2250 static _Bool check_drop_value (void) /* {{{ */
2252 static cdtime_t last_message_time = 0;
2253 static pthread_mutex_t last_message_lock = PTHREAD_MUTEX_INITIALIZER;
2259 if (write_limit_high == 0)
2262 p = get_drop_probability ();
2266 status = pthread_mutex_trylock (&last_message_lock);
2272 if ((now - last_message_time) > TIME_T_TO_CDTIME_T (1))
2274 last_message_time = now;
2275 ERROR ("plugin_dispatch_values: Low water mark "
2276 "reached. Dropping %.0f%% of metrics.",
2279 pthread_mutex_unlock (&last_message_lock);
2290 } /* }}} _Bool check_drop_value */
2292 int plugin_dispatch_values (value_list_t const *vl)
2295 static pthread_mutex_t statistics_lock = PTHREAD_MUTEX_INITIALIZER;
2297 if (check_drop_value ()) {
2298 if(record_statistics) {
2299 pthread_mutex_lock(&statistics_lock);
2300 stats_values_dropped++;
2301 pthread_mutex_unlock(&statistics_lock);
2306 status = plugin_write_enqueue (vl);
2310 ERROR ("plugin_dispatch_values: plugin_write_enqueue failed "
2311 "with status %i (%s).", status,
2312 sstrerror (status, errbuf, sizeof (errbuf)));
2319 __attribute__((sentinel))
2320 int plugin_dispatch_multivalue (value_list_t const *template, /* {{{ */
2321 _Bool store_percentage, int store_type, ...)
2328 assert (template->values_len == 1);
2330 /* Calculate sum for Gauge to calculate percent if needed */
2331 if (DS_TYPE_GAUGE == store_type) {
2332 va_start (ap, store_type);
2338 name = va_arg (ap, char const *);
2342 value = va_arg (ap, gauge_t);
2350 vl = plugin_value_list_clone (template);
2351 /* plugin_value_list_clone makes sure vl->time is set to non-zero. */
2352 if (store_percentage)
2353 sstrncpy (vl->type, "percent", sizeof (vl->type));
2355 va_start (ap, store_type);
2361 /* Set the type instance. */
2362 name = va_arg (ap, char const *);
2365 sstrncpy (vl->type_instance, name, sizeof (vl->type_instance));
2367 /* Set the value. */
2371 vl->values[0].gauge = va_arg (ap, gauge_t);
2372 if (store_percentage)
2373 vl->values[0].gauge *= sum ? (100.0 / sum) : NAN;
2375 case DS_TYPE_ABSOLUTE:
2376 vl->values[0].absolute = va_arg (ap, absolute_t);
2378 case DS_TYPE_COUNTER:
2379 vl->values[0].counter = va_arg (ap, counter_t);
2381 case DS_TYPE_DERIVE:
2382 vl->values[0].derive = va_arg (ap, derive_t);
2385 ERROR ("plugin_dispatch_multivalue: given store_type is incorrect.");
2390 status = plugin_write_enqueue (vl);
2396 plugin_value_list_free (vl);
2398 } /* }}} int plugin_dispatch_multivalue */
2400 int plugin_dispatch_notification (const notification_t *notif)
2403 /* Possible TODO: Add flap detection here */
2405 DEBUG ("plugin_dispatch_notification: severity = %i; message = %s; "
2406 "time = %.3f; host = %s;",
2407 notif->severity, notif->message,
2408 CDTIME_T_TO_DOUBLE (notif->time), notif->host);
2410 /* Nobody cares for notifications */
2411 if (list_notification == NULL)
2414 le = llist_head (list_notification);
2417 callback_func_t *cf;
2418 plugin_notification_cb callback;
2421 /* do not switch plugin context; rather keep the context
2422 * (interval) information of the calling plugin */
2425 callback = cf->cf_callback;
2426 status = (*callback) (notif, &cf->cf_udata);
2429 WARNING ("plugin_dispatch_notification: Notification "
2430 "callback %s returned %i.",
2438 } /* int plugin_dispatch_notification */
2440 void plugin_log (int level, const char *format, ...)
2447 if (level >= LOG_DEBUG)
2451 va_start (ap, format);
2452 vsnprintf (msg, sizeof (msg), format, ap);
2453 msg[sizeof (msg) - 1] = '\0';
2456 if (list_log == NULL)
2458 fprintf (stderr, "%s\n", msg);
2462 le = llist_head (list_log);
2465 callback_func_t *cf;
2466 plugin_log_cb callback;
2469 callback = cf->cf_callback;
2471 /* do not switch plugin context; rather keep the context
2472 * (interval) information of the calling plugin */
2474 (*callback) (level, msg, &cf->cf_udata);
2478 } /* void plugin_log */
2480 int parse_log_severity (const char *severity)
2484 if ((0 == strcasecmp (severity, "emerg"))
2485 || (0 == strcasecmp (severity, "alert"))
2486 || (0 == strcasecmp (severity, "crit"))
2487 || (0 == strcasecmp (severity, "err")))
2488 log_level = LOG_ERR;
2489 else if (0 == strcasecmp (severity, "warning"))
2490 log_level = LOG_WARNING;
2491 else if (0 == strcasecmp (severity, "notice"))
2492 log_level = LOG_NOTICE;
2493 else if (0 == strcasecmp (severity, "info"))
2494 log_level = LOG_INFO;
2496 else if (0 == strcasecmp (severity, "debug"))
2497 log_level = LOG_DEBUG;
2498 #endif /* COLLECT_DEBUG */
2501 } /* int parse_log_severity */
2503 int parse_notif_severity (const char *severity)
2505 int notif_severity = -1;
2507 if (strcasecmp (severity, "FAILURE") == 0)
2508 notif_severity = NOTIF_FAILURE;
2509 else if (strcmp (severity, "OKAY") == 0)
2510 notif_severity = NOTIF_OKAY;
2511 else if ((strcmp (severity, "WARNING") == 0)
2512 || (strcmp (severity, "WARN") == 0))
2513 notif_severity = NOTIF_WARNING;
2515 return (notif_severity);
2516 } /* int parse_notif_severity */
2518 const data_set_t *plugin_get_ds (const char *name)
2522 if (data_sets == NULL)
2524 ERROR ("plugin_get_ds: No data sets are defined yet.");
2528 if (c_avl_get (data_sets, name, (void *) &ds) != 0)
2530 DEBUG ("No such dataset registered: %s", name);
2535 } /* data_set_t *plugin_get_ds */
2537 static int plugin_notification_meta_add (notification_t *n,
2539 enum notification_meta_type_e type,
2542 notification_meta_t *meta;
2543 notification_meta_t *tail;
2545 if ((n == NULL) || (name == NULL) || (value == NULL))
2547 ERROR ("plugin_notification_meta_add: A pointer is NULL!");
2551 meta = calloc (1, sizeof (*meta));
2554 ERROR ("plugin_notification_meta_add: calloc failed.");
2558 sstrncpy (meta->name, name, sizeof (meta->name));
2563 case NM_TYPE_STRING:
2565 meta->nm_value.nm_string = strdup ((const char *) value);
2566 if (meta->nm_value.nm_string == NULL)
2568 ERROR ("plugin_notification_meta_add: strdup failed.");
2574 case NM_TYPE_SIGNED_INT:
2576 meta->nm_value.nm_signed_int = *((int64_t *) value);
2579 case NM_TYPE_UNSIGNED_INT:
2581 meta->nm_value.nm_unsigned_int = *((uint64_t *) value);
2584 case NM_TYPE_DOUBLE:
2586 meta->nm_value.nm_double = *((double *) value);
2589 case NM_TYPE_BOOLEAN:
2591 meta->nm_value.nm_boolean = *((_Bool *) value);
2596 ERROR ("plugin_notification_meta_add: Unknown type: %i", type);
2600 } /* switch (type) */
2604 while ((tail != NULL) && (tail->next != NULL))
2613 } /* int plugin_notification_meta_add */
2615 int plugin_notification_meta_add_string (notification_t *n,
2619 return (plugin_notification_meta_add (n, name, NM_TYPE_STRING, value));
2622 int plugin_notification_meta_add_signed_int (notification_t *n,
2626 return (plugin_notification_meta_add (n, name, NM_TYPE_SIGNED_INT, &value));
2629 int plugin_notification_meta_add_unsigned_int (notification_t *n,
2633 return (plugin_notification_meta_add (n, name, NM_TYPE_UNSIGNED_INT, &value));
2636 int plugin_notification_meta_add_double (notification_t *n,
2640 return (plugin_notification_meta_add (n, name, NM_TYPE_DOUBLE, &value));
2643 int plugin_notification_meta_add_boolean (notification_t *n,
2647 return (plugin_notification_meta_add (n, name, NM_TYPE_BOOLEAN, &value));
2650 int plugin_notification_meta_copy (notification_t *dst,
2651 const notification_t *src)
2653 assert (dst != NULL);
2654 assert (src != NULL);
2655 assert (dst != src);
2656 assert ((src->meta == NULL) || (src->meta != dst->meta));
2658 for (notification_meta_t *meta = src->meta; meta != NULL; meta = meta->next)
2660 if (meta->type == NM_TYPE_STRING)
2661 plugin_notification_meta_add_string (dst, meta->name,
2662 meta->nm_value.nm_string);
2663 else if (meta->type == NM_TYPE_SIGNED_INT)
2664 plugin_notification_meta_add_signed_int (dst, meta->name,
2665 meta->nm_value.nm_signed_int);
2666 else if (meta->type == NM_TYPE_UNSIGNED_INT)
2667 plugin_notification_meta_add_unsigned_int (dst, meta->name,
2668 meta->nm_value.nm_unsigned_int);
2669 else if (meta->type == NM_TYPE_DOUBLE)
2670 plugin_notification_meta_add_double (dst, meta->name,
2671 meta->nm_value.nm_double);
2672 else if (meta->type == NM_TYPE_BOOLEAN)
2673 plugin_notification_meta_add_boolean (dst, meta->name,
2674 meta->nm_value.nm_boolean);
2678 } /* int plugin_notification_meta_copy */
2680 int plugin_notification_meta_free (notification_meta_t *n)
2682 notification_meta_t *this;
2683 notification_meta_t *next;
2687 ERROR ("plugin_notification_meta_free: n == NULL!");
2692 while (this != NULL)
2696 if (this->type == NM_TYPE_STRING)
2698 /* Assign to a temporary variable to work around nm_string's const
2700 void *tmp = (void *) this->nm_value.nm_string;
2703 this->nm_value.nm_string = NULL;
2711 } /* int plugin_notification_meta_free */
2713 static void plugin_ctx_destructor (void *ctx)
2716 } /* void plugin_ctx_destructor */
2718 static plugin_ctx_t ctx_init = { /* interval = */ 0 };
2720 static plugin_ctx_t *plugin_ctx_create (void)
2724 ctx = malloc (sizeof (*ctx));
2727 ERROR ("Failed to allocate plugin context: %s",
2728 sstrerror (errno, errbuf, sizeof (errbuf)));
2733 assert (plugin_ctx_key_initialized);
2734 pthread_setspecific (plugin_ctx_key, ctx);
2735 DEBUG("Created new plugin context.");
2737 } /* int plugin_ctx_create */
2739 void plugin_init_ctx (void)
2741 pthread_key_create (&plugin_ctx_key, plugin_ctx_destructor);
2742 plugin_ctx_key_initialized = 1;
2743 } /* void plugin_init_ctx */
2745 plugin_ctx_t plugin_get_ctx (void)
2749 assert (plugin_ctx_key_initialized);
2750 ctx = pthread_getspecific (plugin_ctx_key);
2753 ctx = plugin_ctx_create ();
2754 /* this must no happen -- exit() instead? */
2760 } /* plugin_ctx_t plugin_get_ctx */
2762 plugin_ctx_t plugin_set_ctx (plugin_ctx_t ctx)
2767 assert (plugin_ctx_key_initialized);
2768 c = pthread_getspecific (plugin_ctx_key);
2771 c = plugin_ctx_create ();
2772 /* this must no happen -- exit() instead? */
2781 } /* void plugin_set_ctx */
2783 cdtime_t plugin_get_interval (void)
2787 interval = plugin_get_ctx().interval;
2791 return cf_get_default_interval ();
2792 } /* cdtime_t plugin_get_interval */
2796 void *(*start_routine) (void *);
2800 static void *plugin_thread_start (void *arg)
2802 plugin_thread_t *plugin_thread = arg;
2804 void *(*start_routine) (void *) = plugin_thread->start_routine;
2805 void *plugin_arg = plugin_thread->arg;
2807 plugin_set_ctx (plugin_thread->ctx);
2809 sfree (plugin_thread);
2811 return start_routine (plugin_arg);
2812 } /* void *plugin_thread_start */
2814 int plugin_thread_create (pthread_t *thread, const pthread_attr_t *attr,
2815 void *(*start_routine) (void *), void *arg, char *name)
2817 plugin_thread_t *plugin_thread;
2820 plugin_thread = malloc (sizeof (*plugin_thread));
2821 if (plugin_thread == NULL)
2824 plugin_thread->ctx = plugin_get_ctx ();
2825 plugin_thread->start_routine = start_routine;
2826 plugin_thread->arg = arg;
2828 ret = pthread_create (thread, attr,
2829 plugin_thread_start, plugin_thread);
2831 if (ret == 0 && name != NULL) {
2832 #if defined(HAVE_PTHREAD_SETNAME_NP) || defined(HAVE_PTHREAD_SET_NAME_NP)
2833 char thread_name[16];
2834 sstrncpy (thread_name, name, sizeof(thread_name));
2835 # if defined(HAVE_PTHREAD_SETNAME_NP)
2836 pthread_setname_np (*thread, thread_name);
2837 # elif defined(HAVE_PTHREAD_SET_NAME_NP)
2838 pthread_set_name_np (*thread, thread_name);
2844 } /* int plugin_thread_create */
2846 /* vim: set sw=8 ts=8 noet fdm=marker : */