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>
28 /* _GNU_SOURCE is needed in Linux to use pthread_setname_np */
33 #include "configfile.h"
34 #include "filter_chain.h"
36 #include "utils/avltree/avltree.h"
37 #include "utils/common/common.h"
38 #include "utils/heap/heap.h"
39 #include "utils_cache.h"
40 #include "utils_complain.h"
41 #include "utils_llist.h"
42 #include "utils_random.h"
43 #include "utils_time.h"
46 #define EXPORT __declspec(dllexport)
54 #include <pthread_np.h> /* for pthread_set_name_np(3) */
62 struct callback_func_s {
67 typedef struct callback_func_s callback_func_t;
71 #define RF_REMOVE 65535
73 /* `read_func_t' "inherits" from `callback_func_t'.
74 * The `rf_super' member MUST be the first one in this structure! */
75 #define rf_callback rf_super.cf_callback
76 #define rf_udata rf_super.cf_udata
77 #define rf_ctx rf_super.cf_ctx
78 callback_func_t rf_super;
79 char rf_group[DATA_MAX_NAME_LEN];
83 cdtime_t rf_effective_interval;
84 cdtime_t rf_next_read;
86 typedef struct read_func_s read_func_t;
88 struct cache_event_func_s {
89 plugin_cache_event_cb callback;
91 user_data_t user_data;
92 plugin_ctx_t plugin_ctx;
94 typedef struct cache_event_func_s cache_event_func_t;
97 typedef struct write_queue_s write_queue_t;
98 struct write_queue_s {
104 struct flush_callback_s {
108 typedef struct flush_callback_s flush_callback_t;
113 static c_avl_tree_t *plugins_loaded;
115 static llist_t *list_init;
116 static llist_t *list_write;
117 static llist_t *list_flush;
118 static llist_t *list_missing;
119 static llist_t *list_shutdown;
120 static llist_t *list_log;
121 static llist_t *list_notification;
123 static size_t list_cache_event_num;
124 static cache_event_func_t list_cache_event[32];
126 static fc_chain_t *pre_cache_chain;
127 static fc_chain_t *post_cache_chain;
129 static c_avl_tree_t *data_sets;
131 static char *plugindir;
133 #ifndef DEFAULT_MAX_READ_INTERVAL
134 #define DEFAULT_MAX_READ_INTERVAL TIME_T_TO_CDTIME_T_STATIC(86400)
136 static c_heap_t *read_heap;
137 static llist_t *read_list;
138 static int read_loop = 1;
139 static pthread_mutex_t read_lock = PTHREAD_MUTEX_INITIALIZER;
140 static pthread_cond_t read_cond = PTHREAD_COND_INITIALIZER;
141 static pthread_t *read_threads;
142 static size_t read_threads_num;
143 static cdtime_t max_read_interval = DEFAULT_MAX_READ_INTERVAL;
145 static write_queue_t *write_queue_head;
146 static write_queue_t *write_queue_tail;
147 static long write_queue_length;
148 static bool write_loop = true;
149 static pthread_mutex_t write_lock = PTHREAD_MUTEX_INITIALIZER;
150 static pthread_cond_t write_cond = PTHREAD_COND_INITIALIZER;
151 static pthread_t *write_threads;
152 static size_t write_threads_num;
154 static pthread_key_t plugin_ctx_key;
155 static bool plugin_ctx_key_initialized;
157 static long write_limit_high;
158 static long write_limit_low;
160 static pthread_mutex_t statistics_lock = PTHREAD_MUTEX_INITIALIZER;
161 static derive_t stats_values_dropped;
162 static bool record_statistics;
167 static int plugin_dispatch_values_internal(value_list_t *vl);
169 static const char *plugin_get_dir(void) {
170 if (plugindir == NULL)
176 static int plugin_update_internal_statistics(void) { /* {{{ */
177 gauge_t copy_write_queue_length = (gauge_t)write_queue_length;
179 /* Initialize `vl' */
180 value_list_t vl = VALUE_LIST_INIT;
181 sstrncpy(vl.plugin, "collectd", sizeof(vl.plugin));
182 vl.interval = plugin_get_interval();
185 sstrncpy(vl.plugin_instance, "write_queue", sizeof(vl.plugin_instance));
187 /* Write queue : queue length */
188 vl.values = &(value_t){.gauge = copy_write_queue_length};
190 sstrncpy(vl.type, "queue_length", sizeof(vl.type));
191 vl.type_instance[0] = 0;
192 plugin_dispatch_values(&vl);
194 /* Write queue : Values dropped (queue length > low limit) */
195 vl.values = &(value_t){.gauge = (gauge_t)stats_values_dropped};
197 sstrncpy(vl.type, "derive", sizeof(vl.type));
198 sstrncpy(vl.type_instance, "dropped", sizeof(vl.type_instance));
199 plugin_dispatch_values(&vl);
202 sstrncpy(vl.plugin_instance, "cache", sizeof(vl.plugin_instance));
204 /* Cache : Nb entry in cache tree */
205 vl.values = &(value_t){.gauge = (gauge_t)uc_get_size()};
207 sstrncpy(vl.type, "cache_size", sizeof(vl.type));
208 vl.type_instance[0] = 0;
209 plugin_dispatch_values(&vl);
212 } /* }}} int plugin_update_internal_statistics */
214 static void free_userdata(user_data_t const *ud) /* {{{ */
219 if ((ud->data != NULL) && (ud->free_func != NULL)) {
220 ud->free_func(ud->data);
222 } /* }}} void free_userdata */
224 static void destroy_callback(callback_func_t *cf) /* {{{ */
228 free_userdata(&cf->cf_udata);
230 } /* }}} void destroy_callback */
232 static void destroy_all_callbacks(llist_t **list) /* {{{ */
239 le = llist_head(*list);
246 destroy_callback(le->value);
252 llist_destroy(*list);
254 } /* }}} void destroy_all_callbacks */
256 static void destroy_read_heap(void) /* {{{ */
258 if (read_heap == NULL)
264 rf = c_heap_get_root(read_heap);
268 destroy_callback((callback_func_t *)rf);
271 c_heap_destroy(read_heap);
273 } /* }}} void destroy_read_heap */
275 static int register_callback(llist_t **list, /* {{{ */
276 const char *name, callback_func_t *cf) {
279 *list = llist_create();
281 ERROR("plugin: register_callback: "
282 "llist_create failed.");
283 destroy_callback(cf);
288 char *key = strdup(name);
290 ERROR("plugin: register_callback: strdup failed.");
291 destroy_callback(cf);
295 llentry_t *le = llist_search(*list, name);
297 le = llentry_create(key, cf);
299 ERROR("plugin: register_callback: "
300 "llentry_create failed.");
302 destroy_callback(cf);
306 llist_append(*list, le);
308 callback_func_t *old_cf = le->value;
311 P_WARNING("register_callback: "
312 "a callback named `%s' already exists - "
313 "overwriting the old entry!",
316 destroy_callback(old_cf);
321 } /* }}} int register_callback */
323 static void log_list_callbacks(llist_t **list, /* {{{ */
324 const char *comment) {
331 n = llist_size(*list);
333 INFO("%s: [none]", comment);
337 char **keys = calloc(n, sizeof(*keys));
339 ERROR("%s: failed to allocate memory for list of callbacks", comment);
343 for (le = llist_head(*list), i = 0, len = 0; le != NULL; le = le->next, i++) {
345 len += strlen(le->key) + 6;
347 str = malloc(len + 10);
349 ERROR("%s: failed to allocate memory for list of callbacks", comment);
352 strjoin(str, len, keys, n, "', '");
353 INFO("%s ['%s']", comment, str);
357 } /* }}} void log_list_callbacks */
359 static int create_register_callback(llist_t **list, /* {{{ */
360 const char *name, void *callback,
361 user_data_t const *ud) {
363 if (name == NULL || callback == NULL)
366 callback_func_t *cf = calloc(1, sizeof(*cf));
369 ERROR("plugin: create_register_callback: calloc failed.");
373 cf->cf_callback = callback;
375 cf->cf_udata = (user_data_t){
376 .data = NULL, .free_func = NULL,
382 cf->cf_ctx = plugin_get_ctx();
384 return register_callback(list, name, cf);
385 } /* }}} int create_register_callback */
387 static int plugin_unregister(llist_t *list, const char *name) /* {{{ */
394 e = llist_search(list, name);
398 llist_remove(list, e);
401 destroy_callback(e->value);
406 } /* }}} int plugin_unregister */
408 /* plugin_load_file loads the shared object "file" and calls its
409 * "module_register" function. Returns zero on success, non-zero otherwise. */
410 static int plugin_load_file(char const *file, bool global) {
411 int flags = RTLD_NOW;
413 flags |= RTLD_GLOBAL;
415 void *dlh = dlopen(file, flags);
417 char errbuf[1024] = "";
419 snprintf(errbuf, sizeof(errbuf),
420 "dlopen(\"%s\") failed: %s. "
421 "The most common cause for this problem is missing dependencies. "
422 "Use ldd(1) to check the dependencies of the plugin / shared "
426 /* This error is printed to STDERR unconditionally. If list_log is NULL,
427 * plugin_log() will also print to STDERR. We avoid duplicate output by
428 * checking that the list of log handlers, list_log, is not NULL. */
429 fprintf(stderr, "ERROR: %s\n", errbuf);
430 if (list_log != NULL) {
437 void (*reg_handle)(void) = dlsym(dlh, "module_register");
438 if (reg_handle == NULL) {
439 ERROR("Couldn't find symbol \"module_register\" in \"%s\": %s\n", file,
449 static void *plugin_read_thread(void __attribute__((unused)) * args) {
450 while (read_loop != 0) {
452 plugin_ctx_t old_ctx;
460 /* Get the read function that needs to be read next.
461 * We don't need to hold "read_lock" for the heap, but we need
462 * to call c_heap_get_root() and pthread_cond_wait() in the
463 * same protected block. */
464 pthread_mutex_lock(&read_lock);
465 rf = c_heap_get_root(read_heap);
467 pthread_cond_wait(&read_cond, &read_lock);
468 pthread_mutex_unlock(&read_lock);
471 pthread_mutex_unlock(&read_lock);
473 if (rf->rf_interval == 0) {
474 /* this should not happen, because the interval is set
475 * for each plugin when loading it
476 * XXX: issue a warning? */
477 rf->rf_interval = plugin_get_interval();
478 rf->rf_effective_interval = rf->rf_interval;
480 rf->rf_next_read = cdtime();
483 /* sleep until this entry is due,
484 * using pthread_cond_timedwait */
485 pthread_mutex_lock(&read_lock);
486 /* In pthread_cond_timedwait, spurious wakeups are possible
487 * (and really happen, at least on NetBSD with > 1 CPU), thus
488 * we need to re-evaluate the condition every time
489 * pthread_cond_timedwait returns. */
491 while ((read_loop != 0) && (cdtime() < rf->rf_next_read) && rc == 0) {
492 rc = pthread_cond_timedwait(&read_cond, &read_lock,
493 &CDTIME_T_TO_TIMESPEC(rf->rf_next_read));
496 /* Must hold `read_lock' when accessing `rf->rf_type'. */
497 rf_type = rf->rf_type;
498 pthread_mutex_unlock(&read_lock);
500 /* Check if we're supposed to stop.. This may have interrupted
502 if (read_loop == 0) {
503 /* Insert `rf' again, so it can be free'd correctly */
504 c_heap_insert(read_heap, rf);
508 /* The entry has been marked for deletion. The linked list
509 * entry has already been removed by `plugin_unregister_read'.
510 * All we have to do here is free the `read_func_t' and
512 if (rf_type == RF_REMOVE) {
513 DEBUG("plugin_read_thread: Destroying the `%s' "
517 destroy_callback((callback_func_t *)rf);
522 DEBUG("plugin_read_thread: Handling `%s'.", rf->rf_name);
526 old_ctx = plugin_set_ctx(rf->rf_ctx);
528 if (rf_type == RF_SIMPLE) {
529 int (*callback)(void);
531 callback = rf->rf_callback;
532 status = (*callback)();
534 plugin_read_cb callback;
536 assert(rf_type == RF_COMPLEX);
538 callback = rf->rf_callback;
539 status = (*callback)(&rf->rf_udata);
542 plugin_set_ctx(old_ctx);
544 /* If the function signals failure, we will increase the
545 * intervals in which it will be called. */
547 rf->rf_effective_interval *= 2;
548 if (rf->rf_effective_interval > max_read_interval)
549 rf->rf_effective_interval = max_read_interval;
551 NOTICE("read-function of plugin `%s' failed. "
552 "Will suspend it for %.3f seconds.",
553 rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
555 /* Success: Restore the interval, if it was changed. */
556 rf->rf_effective_interval = rf->rf_interval;
559 /* update the ``next read due'' field */
562 /* calculate the time spent in the read function */
563 elapsed = (now - start);
565 if (elapsed > rf->rf_effective_interval)
567 "plugin_read_thread: read-function of the `%s' plugin took %.3f "
568 "seconds, which is above its read interval (%.3f seconds). You might "
569 "want to adjust the `Interval' or `ReadThreads' settings.",
570 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed),
571 CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
573 DEBUG("plugin_read_thread: read-function of the `%s' plugin took "
575 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed));
577 DEBUG("plugin_read_thread: Effective interval of the "
578 "`%s' plugin is %.3f seconds.",
579 rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
581 /* Calculate the next (absolute) time at which this function
582 * should be called. */
583 rf->rf_next_read += rf->rf_effective_interval;
585 /* Check, if `rf_next_read' is in the past. */
586 if (rf->rf_next_read < now) {
587 /* `rf_next_read' is in the past. Insert `now'
588 * so this value doesn't trail off into the
590 rf->rf_next_read = now;
593 DEBUG("plugin_read_thread: Next read of the `%s' plugin at %.3f.",
594 rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_next_read));
596 /* Re-insert this read function into the heap again. */
597 c_heap_insert(read_heap, rf);
598 } /* while (read_loop) */
602 } /* void *plugin_read_thread */
604 #ifdef PTHREAD_MAX_NAMELEN_NP
605 #define THREAD_NAME_MAX PTHREAD_MAX_NAMELEN_NP
607 #define THREAD_NAME_MAX 16
610 static void set_thread_name(pthread_t tid, char const *name) {
611 #if defined(HAVE_PTHREAD_SETNAME_NP) || defined(HAVE_PTHREAD_SET_NAME_NP)
613 /* glibc limits the length of the name and fails if the passed string
614 * is too long, so we truncate it here. */
615 char n[THREAD_NAME_MAX];
616 if (strlen(name) >= THREAD_NAME_MAX)
617 WARNING("set_thread_name(\"%s\"): name too long", name);
618 sstrncpy(n, name, sizeof(n));
620 #if defined(HAVE_PTHREAD_SETNAME_NP)
621 int status = pthread_setname_np(tid, n);
623 ERROR("set_thread_name(\"%s\"): %s", n, STRERROR(status));
625 #else /* if defined(HAVE_PTHREAD_SET_NAME_NP) */
626 pthread_set_name_np(tid, n);
632 static void start_read_threads(size_t num) /* {{{ */
634 if (read_threads != NULL)
637 read_threads = calloc(num, sizeof(*read_threads));
638 if (read_threads == NULL) {
639 ERROR("plugin: start_read_threads: calloc failed.");
643 read_threads_num = 0;
644 for (size_t i = 0; i < num; i++) {
645 int status = pthread_create(read_threads + read_threads_num,
646 /* attr = */ NULL, plugin_read_thread,
649 ERROR("plugin: start_read_threads: pthread_create failed with status %i "
651 status, STRERROR(status));
655 char name[THREAD_NAME_MAX];
656 snprintf(name, sizeof(name), "reader#%" PRIu64, (uint64_t)read_threads_num);
657 set_thread_name(read_threads[read_threads_num], name);
661 } /* }}} void start_read_threads */
663 static void stop_read_threads(void) {
664 if (read_threads == NULL)
667 INFO("collectd: Stopping %" PRIsz " read threads.", read_threads_num);
669 pthread_mutex_lock(&read_lock);
671 DEBUG("plugin: stop_read_threads: Signalling `read_cond'");
672 pthread_cond_broadcast(&read_cond);
673 pthread_mutex_unlock(&read_lock);
675 for (size_t i = 0; i < read_threads_num; i++) {
676 if (pthread_join(read_threads[i], NULL) != 0) {
677 ERROR("plugin: stop_read_threads: pthread_join failed.");
679 read_threads[i] = (pthread_t)0;
682 read_threads_num = 0;
683 } /* void stop_read_threads */
685 static void plugin_value_list_free(value_list_t *vl) /* {{{ */
690 meta_data_destroy(vl->meta);
693 } /* }}} void plugin_value_list_free */
695 static value_list_t *
696 plugin_value_list_clone(value_list_t const *vl_orig) /* {{{ */
703 vl = malloc(sizeof(*vl));
706 memcpy(vl, vl_orig, sizeof(*vl));
708 if (vl->host[0] == 0)
709 sstrncpy(vl->host, hostname_g, sizeof(vl->host));
711 vl->values = calloc(vl_orig->values_len, sizeof(*vl->values));
712 if (vl->values == NULL) {
713 plugin_value_list_free(vl);
716 memcpy(vl->values, vl_orig->values,
717 vl_orig->values_len * sizeof(*vl->values));
719 vl->meta = meta_data_clone(vl->meta);
720 if ((vl_orig->meta != NULL) && (vl->meta == NULL)) {
721 plugin_value_list_free(vl);
728 /* Fill in the interval from the thread context, if it is zero. */
729 if (vl->interval == 0)
730 vl->interval = plugin_get_interval();
733 } /* }}} value_list_t *plugin_value_list_clone */
735 static int plugin_write_enqueue(value_list_t const *vl) /* {{{ */
739 q = malloc(sizeof(*q));
744 q->vl = plugin_value_list_clone(vl);
750 /* Store context of caller (read plugin); otherwise, it would not be
751 * available to the write plugins when actually dispatching the
752 * value-list later on. */
753 q->ctx = plugin_get_ctx();
755 pthread_mutex_lock(&write_lock);
757 if (write_queue_tail == NULL) {
758 write_queue_head = q;
759 write_queue_tail = q;
760 write_queue_length = 1;
762 write_queue_tail->next = q;
763 write_queue_tail = q;
764 write_queue_length += 1;
767 pthread_cond_signal(&write_cond);
768 pthread_mutex_unlock(&write_lock);
771 } /* }}} int plugin_write_enqueue */
773 static value_list_t *plugin_write_dequeue(void) /* {{{ */
778 pthread_mutex_lock(&write_lock);
780 while (write_loop && (write_queue_head == NULL))
781 pthread_cond_wait(&write_cond, &write_lock);
783 if (write_queue_head == NULL) {
784 pthread_mutex_unlock(&write_lock);
788 q = write_queue_head;
789 write_queue_head = q->next;
790 write_queue_length -= 1;
791 if (write_queue_head == NULL) {
792 write_queue_tail = NULL;
793 assert(0 == write_queue_length);
796 pthread_mutex_unlock(&write_lock);
798 (void)plugin_set_ctx(q->ctx);
803 } /* }}} value_list_t *plugin_write_dequeue */
805 static void *plugin_write_thread(void __attribute__((unused)) * args) /* {{{ */
808 value_list_t *vl = plugin_write_dequeue();
812 plugin_dispatch_values_internal(vl);
814 plugin_value_list_free(vl);
819 } /* }}} void *plugin_write_thread */
821 static void start_write_threads(size_t num) /* {{{ */
823 if (write_threads != NULL)
826 write_threads = calloc(num, sizeof(*write_threads));
827 if (write_threads == NULL) {
828 ERROR("plugin: start_write_threads: calloc failed.");
832 write_threads_num = 0;
833 for (size_t i = 0; i < num; i++) {
834 int status = pthread_create(write_threads + write_threads_num,
835 /* attr = */ NULL, plugin_write_thread,
838 ERROR("plugin: start_write_threads: pthread_create failed with status %i "
840 status, STRERROR(status));
844 char name[THREAD_NAME_MAX];
845 snprintf(name, sizeof(name), "writer#%" PRIu64,
846 (uint64_t)write_threads_num);
847 set_thread_name(write_threads[write_threads_num], name);
851 } /* }}} void start_write_threads */
853 static void stop_write_threads(void) /* {{{ */
858 if (write_threads == NULL)
861 INFO("collectd: Stopping %" PRIsz " write threads.", write_threads_num);
863 pthread_mutex_lock(&write_lock);
865 DEBUG("plugin: stop_write_threads: Signalling `write_cond'");
866 pthread_cond_broadcast(&write_cond);
867 pthread_mutex_unlock(&write_lock);
869 for (i = 0; i < write_threads_num; i++) {
870 if (pthread_join(write_threads[i], NULL) != 0) {
871 ERROR("plugin: stop_write_threads: pthread_join failed.");
873 write_threads[i] = (pthread_t)0;
875 sfree(write_threads);
876 write_threads_num = 0;
878 pthread_mutex_lock(&write_lock);
880 for (q = write_queue_head; q != NULL;) {
881 write_queue_t *q1 = q;
882 plugin_value_list_free(q->vl);
887 write_queue_head = NULL;
888 write_queue_tail = NULL;
889 write_queue_length = 0;
890 pthread_mutex_unlock(&write_lock);
893 WARNING("plugin: %" PRIsz " value list%s left after shutting down "
894 "the write threads.",
895 i, (i == 1) ? " was" : "s were");
897 } /* }}} void stop_write_threads */
902 void plugin_set_dir(const char *dir) {
910 plugindir = strdup(dir);
911 if (plugindir == NULL)
912 ERROR("plugin_set_dir: strdup(\"%s\") failed", dir);
915 static bool plugin_is_loaded(char const *name) {
918 if (plugins_loaded == NULL)
920 c_avl_create((int (*)(const void *, const void *))strcasecmp);
921 assert(plugins_loaded != NULL);
923 status = c_avl_get(plugins_loaded, name, /* ret_value = */ NULL);
927 static int plugin_mark_loaded(char const *name) {
931 name_copy = strdup(name);
932 if (name_copy == NULL)
935 status = c_avl_insert(plugins_loaded,
936 /* key = */ name_copy, /* value = */ NULL);
940 static void plugin_free_loaded(void) {
944 if (plugins_loaded == NULL)
947 while (c_avl_pick(plugins_loaded, &key, &value) == 0) {
949 assert(value == NULL);
952 c_avl_destroy(plugins_loaded);
953 plugins_loaded = NULL;
958 #define SHLIB_SUFFIX ".dll"
960 #define SHLIB_SUFFIX ".so"
962 int plugin_load(char const *plugin_name, bool global) {
965 char filename[BUFSIZE] = "";
966 char typename[BUFSIZE];
972 if (plugin_name == NULL)
975 /* Check if plugin is already loaded and don't do anything in this
977 if (plugin_is_loaded(plugin_name))
980 dir = plugin_get_dir();
984 * XXX: Magic at work:
986 * Some of the language bindings, for example the Python and Perl
987 * plugins, need to be able to export symbols to the scripts they run.
988 * For this to happen, the "Globals" flag needs to be set.
989 * Unfortunately, this technical detail is hard to explain to the
990 * average user and she shouldn't have to worry about this, ideally.
991 * So in order to save everyone's sanity use a different default for a
992 * handful of special plugins. --octo
994 if ((strcasecmp("perl", plugin_name) == 0) ||
995 (strcasecmp("python", plugin_name) == 0))
998 /* `cpu' should not match `cpufreq'. To solve this we add SHLIB_SUFFIX to the
999 * type when matching the filename */
1000 status = snprintf(typename, sizeof(typename), "%s" SHLIB_SUFFIX, plugin_name);
1001 if ((status < 0) || ((size_t)status >= sizeof(typename))) {
1002 WARNING("plugin_load: Filename too long: \"%s" SHLIB_SUFFIX "\"",
1007 if ((dh = opendir(dir)) == NULL) {
1008 ERROR("plugin_load: opendir (%s) failed: %s", dir, STRERRNO);
1012 while ((de = readdir(dh)) != NULL) {
1013 if (strcasecmp(de->d_name, typename))
1016 status = snprintf(filename, sizeof(filename), "%s/%s", dir, de->d_name);
1017 if ((status < 0) || ((size_t)status >= sizeof(filename))) {
1018 WARNING("plugin_load: Filename too long: \"%s/%s\"", dir, de->d_name);
1022 if (lstat(filename, &statbuf) == -1) {
1023 WARNING("plugin_load: stat (\"%s\") failed: %s", filename, STRERRNO);
1025 } else if (!S_ISREG(statbuf.st_mode)) {
1026 /* don't follow symlinks */
1027 WARNING("plugin_load: %s is not a regular file.", filename);
1031 status = plugin_load_file(filename, global);
1034 plugin_mark_loaded(plugin_name);
1036 INFO("plugin_load: plugin \"%s\" successfully loaded.", plugin_name);
1039 ERROR("plugin_load: Load plugin \"%s\" failed with "
1041 plugin_name, status);
1047 if (filename[0] == 0)
1048 ERROR("plugin_load: Could not find plugin \"%s\" in %s", plugin_name, dir);
1054 * The `register_*' functions follow
1056 EXPORT int plugin_register_config(const char *name,
1057 int (*callback)(const char *key,
1059 const char **keys, int keys_num) {
1060 cf_register(name, callback, keys, keys_num);
1062 } /* int plugin_register_config */
1064 EXPORT int plugin_register_complex_config(const char *type,
1065 int (*callback)(oconfig_item_t *)) {
1066 return cf_register_complex(type, callback);
1067 } /* int plugin_register_complex_config */
1069 EXPORT int plugin_register_init(const char *name, int (*callback)(void)) {
1070 return create_register_callback(&list_init, name, (void *)callback, NULL);
1071 } /* plugin_register_init */
1073 static int plugin_compare_read_func(const void *arg0, const void *arg1) {
1074 const read_func_t *rf0;
1075 const read_func_t *rf1;
1080 if (rf0->rf_next_read < rf1->rf_next_read)
1082 else if (rf0->rf_next_read > rf1->rf_next_read)
1086 } /* int plugin_compare_read_func */
1088 /* Add a read function to both, the heap and a linked list. The linked list if
1089 * used to look-up read functions, especially for the remove function. The heap
1090 * is used to determine which plugin to read next. */
1091 static int plugin_insert_read(read_func_t *rf) {
1095 rf->rf_next_read = cdtime();
1096 rf->rf_effective_interval = rf->rf_interval;
1098 pthread_mutex_lock(&read_lock);
1100 if (read_list == NULL) {
1101 read_list = llist_create();
1102 if (read_list == NULL) {
1103 pthread_mutex_unlock(&read_lock);
1104 ERROR("plugin_insert_read: read_list failed.");
1109 if (read_heap == NULL) {
1110 read_heap = c_heap_create(plugin_compare_read_func);
1111 if (read_heap == NULL) {
1112 pthread_mutex_unlock(&read_lock);
1113 ERROR("plugin_insert_read: c_heap_create failed.");
1118 le = llist_search(read_list, rf->rf_name);
1120 pthread_mutex_unlock(&read_lock);
1121 P_WARNING("The read function \"%s\" is already registered. "
1122 "Check for duplicates in your configuration!",
1127 le = llentry_create(rf->rf_name, rf);
1129 pthread_mutex_unlock(&read_lock);
1130 ERROR("plugin_insert_read: llentry_create failed.");
1134 status = c_heap_insert(read_heap, rf);
1136 pthread_mutex_unlock(&read_lock);
1137 ERROR("plugin_insert_read: c_heap_insert failed.");
1138 llentry_destroy(le);
1142 /* This does not fail. */
1143 llist_append(read_list, le);
1145 /* Wake up all the read threads. */
1146 pthread_cond_broadcast(&read_cond);
1147 pthread_mutex_unlock(&read_lock);
1149 } /* int plugin_insert_read */
1151 EXPORT int plugin_register_read(const char *name, int (*callback)(void)) {
1155 rf = calloc(1, sizeof(*rf));
1157 ERROR("plugin_register_read: calloc failed.");
1161 rf->rf_callback = (void *)callback;
1162 rf->rf_udata.data = NULL;
1163 rf->rf_udata.free_func = NULL;
1164 rf->rf_ctx = plugin_get_ctx();
1165 rf->rf_group[0] = '\0';
1166 rf->rf_name = strdup(name);
1167 rf->rf_type = RF_SIMPLE;
1168 rf->rf_interval = plugin_get_interval();
1169 rf->rf_ctx.interval = rf->rf_interval;
1171 status = plugin_insert_read(rf);
1178 } /* int plugin_register_read */
1180 EXPORT int plugin_register_complex_read(const char *group, const char *name,
1181 plugin_read_cb callback,
1183 user_data_t const *user_data) {
1187 rf = calloc(1, sizeof(*rf));
1189 free_userdata(user_data);
1190 ERROR("plugin_register_complex_read: calloc failed.");
1194 rf->rf_callback = (void *)callback;
1196 sstrncpy(rf->rf_group, group, sizeof(rf->rf_group));
1198 rf->rf_group[0] = '\0';
1199 rf->rf_name = strdup(name);
1200 rf->rf_type = RF_COMPLEX;
1201 rf->rf_interval = (interval != 0) ? interval : plugin_get_interval();
1204 if (user_data == NULL) {
1205 rf->rf_udata.data = NULL;
1206 rf->rf_udata.free_func = NULL;
1208 rf->rf_udata = *user_data;
1211 rf->rf_ctx = plugin_get_ctx();
1212 rf->rf_ctx.interval = rf->rf_interval;
1214 status = plugin_insert_read(rf);
1216 free_userdata(&rf->rf_udata);
1222 } /* int plugin_register_complex_read */
1224 EXPORT int plugin_register_write(const char *name, plugin_write_cb callback,
1225 user_data_t const *ud) {
1226 return create_register_callback(&list_write, name, (void *)callback, ud);
1227 } /* int plugin_register_write */
1229 static int plugin_flush_timeout_callback(user_data_t *ud) {
1230 flush_callback_t *cb = ud->data;
1232 return plugin_flush(cb->name, cb->timeout, NULL);
1233 } /* static int plugin_flush_callback */
1235 static void plugin_flush_timeout_callback_free(void *data) {
1236 flush_callback_t *cb = data;
1243 } /* static void plugin_flush_callback_free */
1245 static char *plugin_flush_callback_name(const char *name) {
1246 const char *flush_prefix = "flush/";
1251 prefix_size = strlen(flush_prefix);
1252 name_size = strlen(name);
1254 flush_name = malloc(name_size + prefix_size + 1);
1255 if (flush_name == NULL) {
1256 ERROR("plugin_flush_callback_name: malloc failed.");
1260 sstrncpy(flush_name, flush_prefix, prefix_size + 1);
1261 sstrncpy(flush_name + prefix_size, name, name_size + 1);
1264 } /* static char *plugin_flush_callback_name */
1266 EXPORT int plugin_register_flush(const char *name, plugin_flush_cb callback,
1267 user_data_t const *ud) {
1269 plugin_ctx_t ctx = plugin_get_ctx();
1271 status = create_register_callback(&list_flush, name, (void *)callback, ud);
1275 if (ctx.flush_interval != 0) {
1277 flush_callback_t *cb;
1279 flush_name = plugin_flush_callback_name(name);
1280 if (flush_name == NULL)
1283 cb = malloc(sizeof(*cb));
1285 ERROR("plugin_register_flush: malloc failed.");
1290 cb->name = strdup(name);
1291 if (cb->name == NULL) {
1292 ERROR("plugin_register_flush: strdup failed.");
1297 cb->timeout = ctx.flush_timeout;
1299 status = plugin_register_complex_read(
1300 /* group = */ "flush",
1301 /* name = */ flush_name,
1302 /* callback = */ plugin_flush_timeout_callback,
1303 /* interval = */ ctx.flush_interval,
1304 /* user data = */ &(user_data_t){
1305 .data = cb, .free_func = plugin_flush_timeout_callback_free,
1313 } /* int plugin_register_flush */
1315 EXPORT int plugin_register_missing(const char *name, plugin_missing_cb callback,
1316 user_data_t const *ud) {
1317 return create_register_callback(&list_missing, name, (void *)callback, ud);
1318 } /* int plugin_register_missing */
1320 EXPORT int plugin_register_cache_event(const char *name,
1321 plugin_cache_event_cb callback,
1322 user_data_t const *ud) {
1324 if (name == NULL || callback == NULL)
1327 char *name_copy = strdup(name);
1328 if (name_copy == NULL) {
1329 P_ERROR("plugin_register_cache_event: strdup failed.");
1334 if (list_cache_event_num >= 32) {
1335 P_ERROR("plugin_register_cache_event: Too much cache event callbacks tried "
1336 "to be registered.");
1341 for (size_t i = 0; i < list_cache_event_num; i++) {
1342 cache_event_func_t *cef = &list_cache_event[i];
1346 if (strcmp(name, cef->name) == 0) {
1347 P_ERROR("plugin_register_cache_event: a callback named `%s' already "
1355 user_data_t user_data;
1357 user_data = (user_data_t){
1358 .data = NULL, .free_func = NULL,
1364 list_cache_event[list_cache_event_num] =
1365 (cache_event_func_t){.callback = callback,
1367 .user_data = user_data,
1368 .plugin_ctx = plugin_get_ctx()};
1369 list_cache_event_num++;
1372 } /* int plugin_register_cache_event */
1374 EXPORT int plugin_register_shutdown(const char *name, int (*callback)(void)) {
1375 return create_register_callback(&list_shutdown, name, (void *)callback, NULL);
1376 } /* int plugin_register_shutdown */
1378 static void plugin_free_data_sets(void) {
1382 if (data_sets == NULL)
1385 while (c_avl_pick(data_sets, &key, &value) == 0) {
1386 data_set_t *ds = value;
1387 /* key is a pointer to ds->type */
1393 c_avl_destroy(data_sets);
1395 } /* void plugin_free_data_sets */
1397 EXPORT int plugin_register_data_set(const data_set_t *ds) {
1398 data_set_t *ds_copy;
1400 if ((data_sets != NULL) && (c_avl_get(data_sets, ds->type, NULL) == 0)) {
1401 NOTICE("Replacing DS `%s' with another version.", ds->type);
1402 plugin_unregister_data_set(ds->type);
1403 } else if (data_sets == NULL) {
1404 data_sets = c_avl_create((int (*)(const void *, const void *))strcmp);
1405 if (data_sets == NULL)
1409 ds_copy = malloc(sizeof(*ds_copy));
1410 if (ds_copy == NULL)
1412 memcpy(ds_copy, ds, sizeof(data_set_t));
1414 ds_copy->ds = malloc(sizeof(*ds_copy->ds) * ds->ds_num);
1415 if (ds_copy->ds == NULL) {
1420 for (size_t i = 0; i < ds->ds_num; i++)
1421 memcpy(ds_copy->ds + i, ds->ds + i, sizeof(data_source_t));
1423 return c_avl_insert(data_sets, (void *)ds_copy->type, (void *)ds_copy);
1424 } /* int plugin_register_data_set */
1426 EXPORT int plugin_register_log(const char *name, plugin_log_cb callback,
1427 user_data_t const *ud) {
1428 return create_register_callback(&list_log, name, (void *)callback, ud);
1429 } /* int plugin_register_log */
1431 EXPORT int plugin_register_notification(const char *name,
1432 plugin_notification_cb callback,
1433 user_data_t const *ud) {
1434 return create_register_callback(&list_notification, name, (void *)callback,
1436 } /* int plugin_register_log */
1438 EXPORT int plugin_unregister_config(const char *name) {
1439 cf_unregister(name);
1441 } /* int plugin_unregister_config */
1443 EXPORT int plugin_unregister_complex_config(const char *name) {
1444 cf_unregister_complex(name);
1446 } /* int plugin_unregister_complex_config */
1448 EXPORT int plugin_unregister_init(const char *name) {
1449 return plugin_unregister(list_init, name);
1452 EXPORT int plugin_unregister_read(const char *name) /* {{{ */
1460 pthread_mutex_lock(&read_lock);
1462 if (read_list == NULL) {
1463 pthread_mutex_unlock(&read_lock);
1467 le = llist_search(read_list, name);
1469 pthread_mutex_unlock(&read_lock);
1470 WARNING("plugin_unregister_read: No such read function: %s", name);
1474 llist_remove(read_list, le);
1478 rf->rf_type = RF_REMOVE;
1480 pthread_mutex_unlock(&read_lock);
1482 llentry_destroy(le);
1484 DEBUG("plugin_unregister_read: Marked `%s' for removal.", name);
1487 } /* }}} int plugin_unregister_read */
1489 EXPORT void plugin_log_available_writers(void) {
1490 log_list_callbacks(&list_write, "Available write targets:");
1493 static int compare_read_func_group(llentry_t *e, void *ud) /* {{{ */
1495 read_func_t *rf = e->value;
1498 return strcmp(rf->rf_group, (const char *)group);
1499 } /* }}} int compare_read_func_group */
1501 EXPORT int plugin_unregister_read_group(const char *group) /* {{{ */
1511 pthread_mutex_lock(&read_lock);
1513 if (read_list == NULL) {
1514 pthread_mutex_unlock(&read_lock);
1519 le = llist_search_custom(read_list, compare_read_func_group, (void *)group);
1526 llist_remove(read_list, le);
1530 rf->rf_type = RF_REMOVE;
1532 llentry_destroy(le);
1534 DEBUG("plugin_unregister_read_group: "
1535 "Marked `%s' (group `%s') for removal.",
1536 rf->rf_name, group);
1539 pthread_mutex_unlock(&read_lock);
1542 WARNING("plugin_unregister_read_group: No such "
1543 "group of read function: %s",
1549 } /* }}} int plugin_unregister_read_group */
1551 EXPORT int plugin_unregister_write(const char *name) {
1552 return plugin_unregister(list_write, name);
1555 EXPORT int plugin_unregister_flush(const char *name) {
1556 plugin_ctx_t ctx = plugin_get_ctx();
1558 if (ctx.flush_interval != 0) {
1561 flush_name = plugin_flush_callback_name(name);
1562 if (flush_name != NULL) {
1563 plugin_unregister_read(flush_name);
1568 return plugin_unregister(list_flush, name);
1571 EXPORT int plugin_unregister_missing(const char *name) {
1572 return plugin_unregister(list_missing, name);
1575 EXPORT int plugin_unregister_cache_event(const char *name) {
1576 for (size_t i = 0; i < list_cache_event_num; i++) {
1577 cache_event_func_t *cef = &list_cache_event[i];
1580 if (strcmp(name, cef->name) == 0) {
1581 /* Mark callback as inactive, so mask in cache entries remains actual */
1582 cef->callback = NULL;
1584 free_userdata(&cef->user_data);
1590 static void destroy_cache_event_callbacks() {
1591 for (size_t i = 0; i < list_cache_event_num; i++) {
1592 cache_event_func_t *cef = &list_cache_event[i];
1595 cef->callback = NULL;
1597 free_userdata(&cef->user_data);
1601 EXPORT int plugin_unregister_shutdown(const char *name) {
1602 return plugin_unregister(list_shutdown, name);
1605 EXPORT int plugin_unregister_data_set(const char *name) {
1608 if (data_sets == NULL)
1611 if (c_avl_remove(data_sets, name, NULL, (void *)&ds) != 0)
1618 } /* int plugin_unregister_data_set */
1620 EXPORT int plugin_unregister_log(const char *name) {
1621 return plugin_unregister(list_log, name);
1624 EXPORT int plugin_unregister_notification(const char *name) {
1625 return plugin_unregister(list_notification, name);
1628 EXPORT int plugin_init_all(void) {
1629 char const *chain_name;
1634 /* Init the value cache */
1637 if (IS_TRUE(global_option_get("CollectInternalStats"))) {
1638 record_statistics = true;
1639 plugin_register_read("collectd", plugin_update_internal_statistics);
1642 chain_name = global_option_get("PreCacheChain");
1643 pre_cache_chain = fc_chain_get_by_name(chain_name);
1645 chain_name = global_option_get("PostCacheChain");
1646 post_cache_chain = fc_chain_get_by_name(chain_name);
1648 write_limit_high = global_option_get_long("WriteQueueLimitHigh",
1650 if (write_limit_high < 0) {
1651 ERROR("WriteQueueLimitHigh must be positive or zero.");
1652 write_limit_high = 0;
1656 global_option_get_long("WriteQueueLimitLow",
1657 /* default = */ write_limit_high / 2);
1658 if (write_limit_low < 0) {
1659 ERROR("WriteQueueLimitLow must be positive or zero.");
1660 write_limit_low = write_limit_high / 2;
1661 } else if (write_limit_low > write_limit_high) {
1662 ERROR("WriteQueueLimitLow must not be larger than "
1663 "WriteQueueLimitHigh.");
1664 write_limit_low = write_limit_high;
1667 write_threads_num = global_option_get_long("WriteThreads",
1669 if (write_threads_num < 1) {
1670 ERROR("WriteThreads must be positive.");
1671 write_threads_num = 5;
1674 if ((list_init == NULL) && (read_heap == NULL))
1677 /* Calling all init callbacks before checking if read callbacks
1678 * are available allows the init callbacks to register the read
1680 le = llist_head(list_init);
1681 while (le != NULL) {
1682 callback_func_t *cf;
1683 plugin_init_cb callback;
1684 plugin_ctx_t old_ctx;
1687 old_ctx = plugin_set_ctx(cf->cf_ctx);
1688 callback = cf->cf_callback;
1689 status = (*callback)();
1690 plugin_set_ctx(old_ctx);
1693 ERROR("Initialization of plugin `%s' "
1694 "failed with status %i. "
1695 "Plugin will be unloaded.",
1697 /* Plugins that register read callbacks from the init
1698 * callback should take care of appropriate error
1699 * handling themselves. */
1700 /* FIXME: Unload _all_ functions */
1701 plugin_unregister_read(le->key);
1708 start_write_threads((size_t)write_threads_num);
1711 global_option_get_time("MaxReadInterval", DEFAULT_MAX_READ_INTERVAL);
1713 /* Start read-threads */
1714 if (read_heap != NULL) {
1718 rt = global_option_get("ReadThreads");
1721 start_read_threads((num > 0) ? ((size_t)num) : 5);
1724 } /* void plugin_init_all */
1726 /* TODO: Rename this function. */
1727 EXPORT void plugin_read_all(void) {
1731 } /* void plugin_read_all */
1733 /* Read function called when the `-T' command line argument is given. */
1734 EXPORT int plugin_read_all_once(void) {
1736 int return_status = 0;
1738 if (read_heap == NULL) {
1739 NOTICE("No read-functions are registered.");
1745 plugin_ctx_t old_ctx;
1747 rf = c_heap_get_root(read_heap);
1751 old_ctx = plugin_set_ctx(rf->rf_ctx);
1753 if (rf->rf_type == RF_SIMPLE) {
1754 int (*callback)(void);
1756 callback = rf->rf_callback;
1757 status = (*callback)();
1759 plugin_read_cb callback;
1761 callback = rf->rf_callback;
1762 status = (*callback)(&rf->rf_udata);
1765 plugin_set_ctx(old_ctx);
1768 NOTICE("read-function of plugin `%s' failed.", rf->rf_name);
1773 destroy_callback((void *)rf);
1776 return return_status;
1777 } /* int plugin_read_all_once */
1779 EXPORT int plugin_write(const char *plugin, /* {{{ */
1780 const data_set_t *ds, const value_list_t *vl) {
1787 if (list_write == NULL)
1791 ds = plugin_get_ds(vl->type);
1793 ERROR("plugin_write: Unable to lookup type `%s'.", vl->type);
1798 if (plugin == NULL) {
1802 le = llist_head(list_write);
1803 while (le != NULL) {
1804 callback_func_t *cf = le->value;
1805 plugin_write_cb callback;
1807 /* Keep the read plugin's interval and flush information but update the
1809 plugin_ctx_t old_ctx = plugin_get_ctx();
1810 plugin_ctx_t ctx = old_ctx;
1811 ctx.name = cf->cf_ctx.name;
1812 plugin_set_ctx(ctx);
1814 DEBUG("plugin: plugin_write: Writing values via %s.", le->key);
1815 callback = cf->cf_callback;
1816 status = (*callback)(ds, vl, &cf->cf_udata);
1822 plugin_set_ctx(old_ctx);
1826 if ((success == 0) && (failure != 0))
1830 } else /* plugin != NULL */
1832 callback_func_t *cf;
1833 plugin_write_cb callback;
1835 le = llist_head(list_write);
1836 while (le != NULL) {
1837 if (strcasecmp(plugin, le->key) == 0)
1848 /* do not switch plugin context; rather keep the context (interval)
1849 * information of the calling read plugin */
1851 DEBUG("plugin: plugin_write: Writing values via %s.", le->key);
1852 callback = cf->cf_callback;
1853 status = (*callback)(ds, vl, &cf->cf_udata);
1857 } /* }}} int plugin_write */
1859 EXPORT int plugin_flush(const char *plugin, cdtime_t timeout,
1860 const char *identifier) {
1863 if (list_flush == NULL)
1866 le = llist_head(list_flush);
1867 while (le != NULL) {
1868 callback_func_t *cf;
1869 plugin_flush_cb callback;
1870 plugin_ctx_t old_ctx;
1872 if ((plugin != NULL) && (strcmp(plugin, le->key) != 0)) {
1878 old_ctx = plugin_set_ctx(cf->cf_ctx);
1879 callback = cf->cf_callback;
1881 (*callback)(timeout, identifier, &cf->cf_udata);
1883 plugin_set_ctx(old_ctx);
1888 } /* int plugin_flush */
1890 EXPORT int plugin_shutdown_all(void) {
1892 int ret = 0; // Assume success.
1894 destroy_all_callbacks(&list_init);
1896 stop_read_threads();
1898 pthread_mutex_lock(&read_lock);
1899 llist_destroy(read_list);
1901 pthread_mutex_unlock(&read_lock);
1903 destroy_read_heap();
1905 /* blocks until all write threads have shut down. */
1906 stop_write_threads();
1908 /* ask all plugins to write out the state they kept. */
1909 plugin_flush(/* plugin = */ NULL,
1911 /* identifier = */ NULL);
1914 if (list_shutdown != NULL)
1915 le = llist_head(list_shutdown);
1917 while (le != NULL) {
1918 callback_func_t *cf;
1919 plugin_shutdown_cb callback;
1920 plugin_ctx_t old_ctx;
1923 old_ctx = plugin_set_ctx(cf->cf_ctx);
1924 callback = cf->cf_callback;
1926 /* Advance the pointer before calling the callback allows
1927 * shutdown functions to unregister themselves. If done the
1928 * other way around the memory `le' points to will be freed
1929 * after callback returns. */
1932 if ((*callback)() != 0)
1935 plugin_set_ctx(old_ctx);
1938 /* Write plugins which use the `user_data' pointer usually need the
1939 * same data available to the flush callback. If this is the case, set
1940 * the free_function to NULL when registering the flush callback and to
1941 * the real free function when registering the write callback. This way
1942 * the data isn't freed twice. */
1943 destroy_all_callbacks(&list_flush);
1944 destroy_all_callbacks(&list_missing);
1945 destroy_cache_event_callbacks();
1946 destroy_all_callbacks(&list_write);
1948 destroy_all_callbacks(&list_notification);
1949 destroy_all_callbacks(&list_shutdown);
1950 destroy_all_callbacks(&list_log);
1952 plugin_free_loaded();
1953 plugin_free_data_sets();
1955 } /* void plugin_shutdown_all */
1957 EXPORT int plugin_dispatch_missing(const value_list_t *vl) /* {{{ */
1959 if (list_missing == NULL)
1962 llentry_t *le = llist_head(list_missing);
1963 while (le != NULL) {
1964 callback_func_t *cf = le->value;
1965 plugin_ctx_t old_ctx = plugin_set_ctx(cf->cf_ctx);
1966 plugin_missing_cb callback = cf->cf_callback;
1968 int status = (*callback)(vl, &cf->cf_udata);
1969 plugin_set_ctx(old_ctx);
1972 ERROR("plugin_dispatch_missing: Callback function \"%s\" "
1973 "failed with status %i.",
1984 } /* int }}} plugin_dispatch_missing */
1986 void plugin_dispatch_cache_event(enum cache_event_type_e event_type,
1987 unsigned long callbacks_mask, const char *name,
1988 const value_list_t *vl) {
1989 switch (event_type) {
1992 for (size_t i = 0; i < list_cache_event_num; i++) {
1993 cache_event_func_t *cef = &list_cache_event[i];
1994 plugin_cache_event_cb callback = cef->callback;
1999 cache_event_t event = (cache_event_t){.type = event_type,
2001 .value_list_name = name,
2004 plugin_ctx_t old_ctx = plugin_set_ctx(cef->plugin_ctx);
2005 int status = (*callback)(&event, &cef->user_data);
2006 plugin_set_ctx(old_ctx);
2009 ERROR("plugin_dispatch_cache_event: Callback \"%s\" failed with status "
2010 "%i for event NEW.",
2015 "plugin_dispatch_cache_event: Callback \"%s\" subscribed to %s.",
2017 callbacks_mask |= (1 << (i));
2019 DEBUG("plugin_dispatch_cache_event: Callback \"%s\" ignores %s.",
2026 uc_set_callbacks_mask(name, callbacks_mask);
2029 case CE_VALUE_UPDATE:
2030 case CE_VALUE_EXPIRED:
2031 for (size_t i = 0; i < list_cache_event_num; i++) {
2032 cache_event_func_t *cef = &list_cache_event[i];
2033 plugin_cache_event_cb callback = cef->callback;
2038 if (callbacks_mask && (1 << (i)) == 0)
2041 cache_event_t event = (cache_event_t){.type = event_type,
2043 .value_list_name = name,
2046 plugin_ctx_t old_ctx = plugin_set_ctx(cef->plugin_ctx);
2047 int status = (*callback)(&event, &cef->user_data);
2048 plugin_set_ctx(old_ctx);
2051 ERROR("plugin_dispatch_cache_event: Callback \"%s\" failed with status "
2054 ((event_type == CE_VALUE_UPDATE) ? "UPDATE" : "EXPIRED"));
2062 static int plugin_dispatch_values_internal(value_list_t *vl) {
2064 static c_complain_t no_write_complaint = C_COMPLAIN_INIT_STATIC;
2066 bool free_meta_data = false;
2070 /* These fields are initialized by plugin_value_list_clone() if needed: */
2071 assert(vl->host[0] != 0);
2072 assert(vl->time != 0); /* The time is determined at _enqueue_ time. */
2073 assert(vl->interval != 0);
2075 if (vl->type[0] == 0 || vl->values == NULL || vl->values_len < 1) {
2076 ERROR("plugin_dispatch_values: Invalid value list "
2082 /* Free meta data only if the calling function didn't specify any. In
2083 * this case matches and targets may add some and the calling function
2084 * may not expect (and therefore free) that data. */
2085 if (vl->meta == NULL)
2086 free_meta_data = true;
2088 if (list_write == NULL)
2089 c_complain_once(LOG_WARNING, &no_write_complaint,
2090 "plugin_dispatch_values: No write callback has been "
2091 "registered. Please load at least one output plugin, "
2092 "if you want the collected data to be stored.");
2094 if (data_sets == NULL) {
2095 ERROR("plugin_dispatch_values: No data sets registered. "
2096 "Could the types database be read? Check "
2097 "your `TypesDB' setting!");
2101 data_set_t *ds = NULL;
2102 if (c_avl_get(data_sets, vl->type, (void *)&ds) != 0) {
2103 char ident[6 * DATA_MAX_NAME_LEN];
2105 FORMAT_VL(ident, sizeof(ident), vl);
2106 INFO("plugin_dispatch_values: Dataset not found: %s "
2107 "(from \"%s\"), check your types.db!",
2112 DEBUG("plugin_dispatch_values: time = %.3f; interval = %.3f; "
2114 "plugin = %s; plugin_instance = %s; "
2115 "type = %s; type_instance = %s;",
2116 CDTIME_T_TO_DOUBLE(vl->time), CDTIME_T_TO_DOUBLE(vl->interval),
2117 vl->host, vl->plugin, vl->plugin_instance, vl->type, vl->type_instance);
2120 assert(0 == strcmp(ds->type, vl->type));
2122 if (0 != strcmp(ds->type, vl->type))
2123 WARNING("plugin_dispatch_values: (ds->type = %s) != (vl->type = %s)",
2124 ds->type, vl->type);
2128 assert(ds->ds_num == vl->values_len);
2130 if (ds->ds_num != vl->values_len) {
2131 ERROR("plugin_dispatch_values: ds->type = %s: "
2132 "(ds->ds_num = %" PRIsz ") != "
2133 "(vl->values_len = %" PRIsz ")",
2134 ds->type, ds->ds_num, vl->values_len);
2139 escape_slashes(vl->host, sizeof(vl->host));
2140 escape_slashes(vl->plugin, sizeof(vl->plugin));
2141 escape_slashes(vl->plugin_instance, sizeof(vl->plugin_instance));
2142 escape_slashes(vl->type, sizeof(vl->type));
2143 escape_slashes(vl->type_instance, sizeof(vl->type_instance));
2145 if (pre_cache_chain != NULL) {
2146 status = fc_process_chain(ds, vl, pre_cache_chain);
2148 WARNING("plugin_dispatch_values: Running the "
2149 "pre-cache chain failed with "
2152 } else if (status == FC_TARGET_STOP)
2156 /* Update the value cache */
2159 if (post_cache_chain != NULL) {
2160 status = fc_process_chain(ds, vl, post_cache_chain);
2162 WARNING("plugin_dispatch_values: Running the "
2163 "post-cache chain failed with "
2168 fc_default_action(ds, vl);
2170 if ((free_meta_data == true) && (vl->meta != NULL)) {
2171 meta_data_destroy(vl->meta);
2176 } /* int plugin_dispatch_values_internal */
2178 static double get_drop_probability(void) /* {{{ */
2184 pthread_mutex_lock(&write_lock);
2185 wql = write_queue_length;
2186 pthread_mutex_unlock(&write_lock);
2188 if (wql < write_limit_low)
2190 if (wql >= write_limit_high)
2193 pos = 1 + wql - write_limit_low;
2194 size = 1 + write_limit_high - write_limit_low;
2196 return (double)pos / (double)size;
2197 } /* }}} double get_drop_probability */
2199 static bool check_drop_value(void) /* {{{ */
2201 static cdtime_t last_message_time;
2202 static pthread_mutex_t last_message_lock = PTHREAD_MUTEX_INITIALIZER;
2208 if (write_limit_high == 0)
2211 p = get_drop_probability();
2215 status = pthread_mutex_trylock(&last_message_lock);
2220 if ((now - last_message_time) > TIME_T_TO_CDTIME_T(1)) {
2221 last_message_time = now;
2222 ERROR("plugin_dispatch_values: Low water mark "
2223 "reached. Dropping %.0f%% of metrics.",
2226 pthread_mutex_unlock(&last_message_lock);
2237 } /* }}} bool check_drop_value */
2239 EXPORT int plugin_dispatch_values(value_list_t const *vl) {
2242 if (check_drop_value()) {
2243 if (record_statistics) {
2244 pthread_mutex_lock(&statistics_lock);
2245 stats_values_dropped++;
2246 pthread_mutex_unlock(&statistics_lock);
2251 status = plugin_write_enqueue(vl);
2253 ERROR("plugin_dispatch_values: plugin_write_enqueue failed with status %i "
2255 status, STRERROR(status));
2262 __attribute__((sentinel)) int
2263 plugin_dispatch_multivalue(value_list_t const *template, /* {{{ */
2264 bool store_percentage, int store_type, ...) {
2270 if (check_drop_value()) {
2271 if (record_statistics) {
2272 pthread_mutex_lock(&statistics_lock);
2273 stats_values_dropped++;
2274 pthread_mutex_unlock(&statistics_lock);
2279 assert(template->values_len == 1);
2281 /* Calculate sum for Gauge to calculate percent if needed */
2282 if (DS_TYPE_GAUGE == store_type) {
2283 va_start(ap, store_type);
2288 name = va_arg(ap, char const *);
2292 value = va_arg(ap, gauge_t);
2299 vl = plugin_value_list_clone(template);
2300 /* plugin_value_list_clone makes sure vl->time is set to non-zero. */
2301 if (store_percentage)
2302 sstrncpy(vl->type, "percent", sizeof(vl->type));
2304 va_start(ap, store_type);
2309 /* Set the type instance. */
2310 name = va_arg(ap, char const *);
2313 sstrncpy(vl->type_instance, name, sizeof(vl->type_instance));
2315 /* Set the value. */
2316 switch (store_type) {
2318 vl->values[0].gauge = va_arg(ap, gauge_t);
2319 if (store_percentage)
2320 vl->values[0].gauge *= sum ? (100.0 / sum) : NAN;
2322 case DS_TYPE_ABSOLUTE:
2323 vl->values[0].absolute = va_arg(ap, absolute_t);
2325 case DS_TYPE_COUNTER:
2326 vl->values[0].counter = va_arg(ap, counter_t);
2328 case DS_TYPE_DERIVE:
2329 vl->values[0].derive = va_arg(ap, derive_t);
2332 ERROR("plugin_dispatch_multivalue: given store_type is incorrect.");
2336 status = plugin_write_enqueue(vl);
2342 plugin_value_list_free(vl);
2344 } /* }}} int plugin_dispatch_multivalue */
2346 EXPORT int plugin_dispatch_notification(const notification_t *notif) {
2348 /* Possible TODO: Add flap detection here */
2350 DEBUG("plugin_dispatch_notification: severity = %i; message = %s; "
2351 "time = %.3f; host = %s;",
2352 notif->severity, notif->message, CDTIME_T_TO_DOUBLE(notif->time),
2355 /* Nobody cares for notifications */
2356 if (list_notification == NULL)
2359 le = llist_head(list_notification);
2360 while (le != NULL) {
2361 callback_func_t *cf;
2362 plugin_notification_cb callback;
2365 /* do not switch plugin context; rather keep the context
2366 * (interval) information of the calling plugin */
2369 callback = cf->cf_callback;
2370 status = (*callback)(notif, &cf->cf_udata);
2372 WARNING("plugin_dispatch_notification: Notification "
2373 "callback %s returned %i.",
2381 } /* int plugin_dispatch_notification */
2383 EXPORT void plugin_log(int level, const char *format, ...) {
2389 if (level >= LOG_DEBUG)
2393 va_start(ap, format);
2394 vsnprintf(msg, sizeof(msg), format, ap);
2395 msg[sizeof(msg) - 1] = '\0';
2398 if (list_log == NULL) {
2399 fprintf(stderr, "%s\n", msg);
2403 le = llist_head(list_log);
2404 while (le != NULL) {
2405 callback_func_t *cf;
2406 plugin_log_cb callback;
2409 callback = cf->cf_callback;
2411 /* do not switch plugin context; rather keep the context
2412 * (interval) information of the calling plugin */
2414 (*callback)(level, msg, &cf->cf_udata);
2418 } /* void plugin_log */
2420 void daemon_log(int level, const char *format, ...) {
2421 char msg[1024] = ""; // Size inherits from plugin_log()
2423 char const *name = plugin_get_ctx().name;
2428 va_start(ap, format);
2429 vsnprintf(msg, sizeof(msg), format, ap);
2432 plugin_log(level, "%s plugin: %s", name, msg);
2433 } /* void daemon_log */
2435 int parse_log_severity(const char *severity) {
2438 if ((0 == strcasecmp(severity, "emerg")) ||
2439 (0 == strcasecmp(severity, "alert")) ||
2440 (0 == strcasecmp(severity, "crit")) || (0 == strcasecmp(severity, "err")))
2441 log_level = LOG_ERR;
2442 else if (0 == strcasecmp(severity, "warning"))
2443 log_level = LOG_WARNING;
2444 else if (0 == strcasecmp(severity, "notice"))
2445 log_level = LOG_NOTICE;
2446 else if (0 == strcasecmp(severity, "info"))
2447 log_level = LOG_INFO;
2449 else if (0 == strcasecmp(severity, "debug"))
2450 log_level = LOG_DEBUG;
2451 #endif /* COLLECT_DEBUG */
2454 } /* int parse_log_severity */
2456 EXPORT int parse_notif_severity(const char *severity) {
2457 int notif_severity = -1;
2459 if (strcasecmp(severity, "FAILURE") == 0)
2460 notif_severity = NOTIF_FAILURE;
2461 else if (strcmp(severity, "OKAY") == 0)
2462 notif_severity = NOTIF_OKAY;
2463 else if ((strcmp(severity, "WARNING") == 0) ||
2464 (strcmp(severity, "WARN") == 0))
2465 notif_severity = NOTIF_WARNING;
2467 return notif_severity;
2468 } /* int parse_notif_severity */
2470 EXPORT const data_set_t *plugin_get_ds(const char *name) {
2473 if (data_sets == NULL) {
2474 P_ERROR("plugin_get_ds: No data sets are defined yet.");
2478 if (c_avl_get(data_sets, name, (void *)&ds) != 0) {
2479 DEBUG("No such dataset registered: %s", name);
2484 } /* data_set_t *plugin_get_ds */
2486 static int plugin_notification_meta_add(notification_t *n, const char *name,
2487 enum notification_meta_type_e type,
2488 const void *value) {
2489 notification_meta_t *meta;
2490 notification_meta_t *tail;
2492 if ((n == NULL) || (name == NULL) || (value == NULL)) {
2493 ERROR("plugin_notification_meta_add: A pointer is NULL!");
2497 meta = calloc(1, sizeof(*meta));
2499 ERROR("plugin_notification_meta_add: calloc failed.");
2503 sstrncpy(meta->name, name, sizeof(meta->name));
2507 case NM_TYPE_STRING: {
2508 meta->nm_value.nm_string = strdup((const char *)value);
2509 if (meta->nm_value.nm_string == NULL) {
2510 ERROR("plugin_notification_meta_add: strdup failed.");
2516 case NM_TYPE_SIGNED_INT: {
2517 meta->nm_value.nm_signed_int = *((int64_t *)value);
2520 case NM_TYPE_UNSIGNED_INT: {
2521 meta->nm_value.nm_unsigned_int = *((uint64_t *)value);
2524 case NM_TYPE_DOUBLE: {
2525 meta->nm_value.nm_double = *((double *)value);
2528 case NM_TYPE_BOOLEAN: {
2529 meta->nm_value.nm_boolean = *((bool *)value);
2533 ERROR("plugin_notification_meta_add: Unknown type: %i", type);
2537 } /* switch (type) */
2541 while ((tail != NULL) && (tail->next != NULL))
2550 } /* int plugin_notification_meta_add */
2552 int plugin_notification_meta_add_string(notification_t *n, const char *name,
2553 const char *value) {
2554 return plugin_notification_meta_add(n, name, NM_TYPE_STRING, value);
2557 int plugin_notification_meta_add_signed_int(notification_t *n, const char *name,
2559 return plugin_notification_meta_add(n, name, NM_TYPE_SIGNED_INT, &value);
2562 int plugin_notification_meta_add_unsigned_int(notification_t *n,
2565 return plugin_notification_meta_add(n, name, NM_TYPE_UNSIGNED_INT, &value);
2568 int plugin_notification_meta_add_double(notification_t *n, const char *name,
2570 return plugin_notification_meta_add(n, name, NM_TYPE_DOUBLE, &value);
2573 int plugin_notification_meta_add_boolean(notification_t *n, const char *name,
2575 return plugin_notification_meta_add(n, name, NM_TYPE_BOOLEAN, &value);
2578 int plugin_notification_meta_copy(notification_t *dst,
2579 const notification_t *src) {
2580 assert(dst != NULL);
2581 assert(src != NULL);
2583 assert((src->meta == NULL) || (src->meta != dst->meta));
2585 for (notification_meta_t *meta = src->meta; meta != NULL; meta = meta->next) {
2586 if (meta->type == NM_TYPE_STRING)
2587 plugin_notification_meta_add_string(dst, meta->name,
2588 meta->nm_value.nm_string);
2589 else if (meta->type == NM_TYPE_SIGNED_INT)
2590 plugin_notification_meta_add_signed_int(dst, meta->name,
2591 meta->nm_value.nm_signed_int);
2592 else if (meta->type == NM_TYPE_UNSIGNED_INT)
2593 plugin_notification_meta_add_unsigned_int(dst, meta->name,
2594 meta->nm_value.nm_unsigned_int);
2595 else if (meta->type == NM_TYPE_DOUBLE)
2596 plugin_notification_meta_add_double(dst, meta->name,
2597 meta->nm_value.nm_double);
2598 else if (meta->type == NM_TYPE_BOOLEAN)
2599 plugin_notification_meta_add_boolean(dst, meta->name,
2600 meta->nm_value.nm_boolean);
2604 } /* int plugin_notification_meta_copy */
2606 int plugin_notification_meta_free(notification_meta_t *n) {
2607 notification_meta_t *this;
2608 notification_meta_t *next;
2611 ERROR("plugin_notification_meta_free: n == NULL!");
2616 while (this != NULL) {
2619 if (this->type == NM_TYPE_STRING) {
2620 /* Assign to a temporary variable to work around nm_string's const
2622 void *tmp = (void *)this->nm_value.nm_string;
2625 this->nm_value.nm_string = NULL;
2633 } /* int plugin_notification_meta_free */
2635 static void plugin_ctx_destructor(void *ctx) {
2637 } /* void plugin_ctx_destructor */
2639 static plugin_ctx_t ctx_init = {/* interval = */ 0};
2641 static plugin_ctx_t *plugin_ctx_create(void) {
2644 ctx = malloc(sizeof(*ctx));
2646 ERROR("Failed to allocate plugin context: %s", STRERRNO);
2651 assert(plugin_ctx_key_initialized);
2652 pthread_setspecific(plugin_ctx_key, ctx);
2653 DEBUG("Created new plugin context.");
2655 } /* int plugin_ctx_create */
2657 EXPORT void plugin_init_ctx(void) {
2658 pthread_key_create(&plugin_ctx_key, plugin_ctx_destructor);
2659 plugin_ctx_key_initialized = true;
2660 } /* void plugin_init_ctx */
2662 EXPORT plugin_ctx_t plugin_get_ctx(void) {
2665 assert(plugin_ctx_key_initialized);
2666 ctx = pthread_getspecific(plugin_ctx_key);
2669 ctx = plugin_ctx_create();
2670 /* this must no happen -- exit() instead? */
2676 } /* plugin_ctx_t plugin_get_ctx */
2678 EXPORT plugin_ctx_t plugin_set_ctx(plugin_ctx_t ctx) {
2682 assert(plugin_ctx_key_initialized);
2683 c = pthread_getspecific(plugin_ctx_key);
2686 c = plugin_ctx_create();
2687 /* this must no happen -- exit() instead? */
2696 } /* void plugin_set_ctx */
2698 EXPORT cdtime_t plugin_get_interval(void) {
2701 interval = plugin_get_ctx().interval;
2705 P_ERROR("plugin_get_interval: Unable to determine Interval from context.");
2707 return cf_get_default_interval();
2708 } /* cdtime_t plugin_get_interval */
2712 void *(*start_routine)(void *);
2716 static void *plugin_thread_start(void *arg) {
2717 plugin_thread_t *plugin_thread = arg;
2719 void *(*start_routine)(void *) = plugin_thread->start_routine;
2720 void *plugin_arg = plugin_thread->arg;
2722 plugin_set_ctx(plugin_thread->ctx);
2724 sfree(plugin_thread);
2726 return start_routine(plugin_arg);
2727 } /* void *plugin_thread_start */
2729 int plugin_thread_create(pthread_t *thread, const pthread_attr_t *attr,
2730 void *(*start_routine)(void *), void *arg,
2732 plugin_thread_t *plugin_thread;
2734 plugin_thread = malloc(sizeof(*plugin_thread));
2735 if (plugin_thread == NULL)
2738 plugin_thread->ctx = plugin_get_ctx();
2739 plugin_thread->start_routine = start_routine;
2740 plugin_thread->arg = arg;
2742 int ret = pthread_create(thread, attr, plugin_thread_start, plugin_thread);
2744 sfree(plugin_thread);
2749 set_thread_name(*thread, name);
2752 } /* int plugin_thread_create */