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 */
34 #include "configfile.h"
35 #include "filter_chain.h"
37 #include "utils_avltree.h"
38 #include "utils_cache.h"
39 #include "utils_complain.h"
40 #include "utils_heap.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;
89 typedef struct write_queue_s write_queue_t;
90 struct write_queue_s {
96 struct flush_callback_s {
100 typedef struct flush_callback_s flush_callback_t;
105 static c_avl_tree_t *plugins_loaded;
107 static llist_t *list_init;
108 static llist_t *list_write;
109 static llist_t *list_flush;
110 static llist_t *list_missing;
111 static llist_t *list_shutdown;
112 static llist_t *list_log;
113 static llist_t *list_notification;
115 static fc_chain_t *pre_cache_chain;
116 static fc_chain_t *post_cache_chain;
118 static c_avl_tree_t *data_sets;
120 static char *plugindir;
122 #ifndef DEFAULT_MAX_READ_INTERVAL
123 #define DEFAULT_MAX_READ_INTERVAL TIME_T_TO_CDTIME_T_STATIC(86400)
125 static c_heap_t *read_heap;
126 static llist_t *read_list;
127 static int read_loop = 1;
128 static pthread_mutex_t read_lock = PTHREAD_MUTEX_INITIALIZER;
129 static pthread_cond_t read_cond = PTHREAD_COND_INITIALIZER;
130 static pthread_t *read_threads;
131 static size_t read_threads_num;
132 static cdtime_t max_read_interval = DEFAULT_MAX_READ_INTERVAL;
134 static write_queue_t *write_queue_head;
135 static write_queue_t *write_queue_tail;
136 static long write_queue_length;
137 static bool write_loop = true;
138 static pthread_mutex_t write_lock = PTHREAD_MUTEX_INITIALIZER;
139 static pthread_cond_t write_cond = PTHREAD_COND_INITIALIZER;
140 static pthread_t *write_threads;
141 static size_t write_threads_num;
143 static pthread_key_t plugin_ctx_key;
144 static bool plugin_ctx_key_initialized;
146 static long write_limit_high;
147 static long write_limit_low;
149 static derive_t stats_values_dropped;
150 static bool record_statistics;
155 static int plugin_dispatch_values_internal(value_list_t *vl);
157 static const char *plugin_get_dir(void) {
158 if (plugindir == NULL)
164 static int plugin_update_internal_statistics(void) { /* {{{ */
165 gauge_t copy_write_queue_length = (gauge_t)write_queue_length;
167 /* Initialize `vl' */
168 value_list_t vl = VALUE_LIST_INIT;
169 sstrncpy(vl.plugin, "collectd", sizeof(vl.plugin));
170 vl.interval = plugin_get_interval();
173 sstrncpy(vl.plugin_instance, "write_queue", sizeof(vl.plugin_instance));
175 /* Write queue : queue length */
176 vl.values = &(value_t){.gauge = copy_write_queue_length};
178 sstrncpy(vl.type, "queue_length", sizeof(vl.type));
179 vl.type_instance[0] = 0;
180 plugin_dispatch_values(&vl);
182 /* Write queue : Values dropped (queue length > low limit) */
183 vl.values = &(value_t){.gauge = (gauge_t)stats_values_dropped};
185 sstrncpy(vl.type, "derive", sizeof(vl.type));
186 sstrncpy(vl.type_instance, "dropped", sizeof(vl.type_instance));
187 plugin_dispatch_values(&vl);
190 sstrncpy(vl.plugin_instance, "cache", sizeof(vl.plugin_instance));
192 /* Cache : Nb entry in cache tree */
193 vl.values = &(value_t){.gauge = (gauge_t)uc_get_size()};
195 sstrncpy(vl.type, "cache_size", sizeof(vl.type));
196 vl.type_instance[0] = 0;
197 plugin_dispatch_values(&vl);
200 } /* }}} int plugin_update_internal_statistics */
202 static void free_userdata(user_data_t const *ud) /* {{{ */
207 if ((ud->data != NULL) && (ud->free_func != NULL)) {
208 ud->free_func(ud->data);
210 } /* }}} void free_userdata */
212 static void destroy_callback(callback_func_t *cf) /* {{{ */
216 free_userdata(&cf->cf_udata);
218 } /* }}} void destroy_callback */
220 static void destroy_all_callbacks(llist_t **list) /* {{{ */
227 le = llist_head(*list);
234 destroy_callback(le->value);
240 llist_destroy(*list);
242 } /* }}} void destroy_all_callbacks */
244 static void destroy_read_heap(void) /* {{{ */
246 if (read_heap == NULL)
252 rf = c_heap_get_root(read_heap);
256 destroy_callback((callback_func_t *)rf);
259 c_heap_destroy(read_heap);
261 } /* }}} void destroy_read_heap */
263 static int register_callback(llist_t **list, /* {{{ */
264 const char *name, callback_func_t *cf) {
269 *list = llist_create();
271 ERROR("plugin: register_callback: "
272 "llist_create failed.");
273 destroy_callback(cf);
280 ERROR("plugin: register_callback: strdup failed.");
281 destroy_callback(cf);
285 le = llist_search(*list, name);
287 le = llentry_create(key, cf);
289 ERROR("plugin: register_callback: "
290 "llentry_create failed.");
292 destroy_callback(cf);
296 llist_append(*list, le);
298 callback_func_t *old_cf;
303 P_WARNING("register_callback: "
304 "a callback named `%s' already exists - "
305 "overwriting the old entry!",
308 destroy_callback(old_cf);
313 } /* }}} int register_callback */
315 static void log_list_callbacks(llist_t **list, /* {{{ */
316 const char *comment) {
324 n = llist_size(*list);
326 INFO("%s: [none]", comment);
330 keys = calloc(n, sizeof(char *));
333 ERROR("%s: failed to allocate memory for list of callbacks", comment);
338 for (le = llist_head(*list), i = 0, len = 0; le != NULL; le = le->next, i++) {
340 len += strlen(le->key) + 6;
342 str = malloc(len + 10);
344 ERROR("%s: failed to allocate memory for list of callbacks", comment);
347 strjoin(str, len, keys, n, "', '");
348 INFO("%s ['%s']", comment, str);
352 } /* }}} void log_list_callbacks */
354 static int create_register_callback(llist_t **list, /* {{{ */
355 const char *name, void *callback,
356 user_data_t const *ud) {
358 if (name == NULL || callback == NULL)
361 callback_func_t *cf = calloc(1, sizeof(*cf));
364 ERROR("plugin: create_register_callback: calloc failed.");
368 cf->cf_callback = callback;
370 cf->cf_udata = (user_data_t){
371 .data = NULL, .free_func = NULL,
377 cf->cf_ctx = plugin_get_ctx();
379 return register_callback(list, name, cf);
380 } /* }}} int create_register_callback */
382 static int plugin_unregister(llist_t *list, const char *name) /* {{{ */
389 e = llist_search(list, name);
393 llist_remove(list, e);
396 destroy_callback(e->value);
401 } /* }}} int plugin_unregister */
403 /* plugin_load_file loads the shared object "file" and calls its
404 * "module_register" function. Returns zero on success, non-zero otherwise. */
405 static int plugin_load_file(char const *file, bool global) {
406 int flags = RTLD_NOW;
408 flags |= RTLD_GLOBAL;
410 void *dlh = dlopen(file, flags);
412 char errbuf[1024] = "";
414 snprintf(errbuf, sizeof(errbuf),
415 "dlopen(\"%s\") failed: %s. "
416 "The most common cause for this problem is missing dependencies. "
417 "Use ldd(1) to check the dependencies of the plugin / shared "
421 /* This error is printed to STDERR unconditionally. If list_log is NULL,
422 * plugin_log() will also print to STDERR. We avoid duplicate output by
423 * checking that the list of log handlers, list_log, is not NULL. */
424 fprintf(stderr, "ERROR: %s\n", errbuf);
425 if (list_log != NULL) {
432 void (*reg_handle)(void) = dlsym(dlh, "module_register");
433 if (reg_handle == NULL) {
434 ERROR("Couldn't find symbol \"module_register\" in \"%s\": %s\n", file,
444 static void *plugin_read_thread(void __attribute__((unused)) * args) {
445 while (read_loop != 0) {
447 plugin_ctx_t old_ctx;
455 /* Get the read function that needs to be read next.
456 * We don't need to hold "read_lock" for the heap, but we need
457 * to call c_heap_get_root() and pthread_cond_wait() in the
458 * same protected block. */
459 pthread_mutex_lock(&read_lock);
460 rf = c_heap_get_root(read_heap);
462 pthread_cond_wait(&read_cond, &read_lock);
463 pthread_mutex_unlock(&read_lock);
466 pthread_mutex_unlock(&read_lock);
468 if (rf->rf_interval == 0) {
469 /* this should not happen, because the interval is set
470 * for each plugin when loading it
471 * XXX: issue a warning? */
472 rf->rf_interval = plugin_get_interval();
473 rf->rf_effective_interval = rf->rf_interval;
475 rf->rf_next_read = cdtime();
478 /* sleep until this entry is due,
479 * using pthread_cond_timedwait */
480 pthread_mutex_lock(&read_lock);
481 /* In pthread_cond_timedwait, spurious wakeups are possible
482 * (and really happen, at least on NetBSD with > 1 CPU), thus
483 * we need to re-evaluate the condition every time
484 * pthread_cond_timedwait returns. */
486 while ((read_loop != 0) && (cdtime() < rf->rf_next_read) && rc == 0) {
487 rc = pthread_cond_timedwait(&read_cond, &read_lock,
488 &CDTIME_T_TO_TIMESPEC(rf->rf_next_read));
491 /* Must hold `read_lock' when accessing `rf->rf_type'. */
492 rf_type = rf->rf_type;
493 pthread_mutex_unlock(&read_lock);
495 /* Check if we're supposed to stop.. This may have interrupted
497 if (read_loop == 0) {
498 /* Insert `rf' again, so it can be free'd correctly */
499 c_heap_insert(read_heap, rf);
503 /* The entry has been marked for deletion. The linked list
504 * entry has already been removed by `plugin_unregister_read'.
505 * All we have to do here is free the `read_func_t' and
507 if (rf_type == RF_REMOVE) {
508 DEBUG("plugin_read_thread: Destroying the `%s' "
512 destroy_callback((callback_func_t *)rf);
517 DEBUG("plugin_read_thread: Handling `%s'.", rf->rf_name);
521 old_ctx = plugin_set_ctx(rf->rf_ctx);
523 if (rf_type == RF_SIMPLE) {
524 int (*callback)(void);
526 callback = rf->rf_callback;
527 status = (*callback)();
529 plugin_read_cb callback;
531 assert(rf_type == RF_COMPLEX);
533 callback = rf->rf_callback;
534 status = (*callback)(&rf->rf_udata);
537 plugin_set_ctx(old_ctx);
539 /* If the function signals failure, we will increase the
540 * intervals in which it will be called. */
542 rf->rf_effective_interval *= 2;
543 if (rf->rf_effective_interval > max_read_interval)
544 rf->rf_effective_interval = max_read_interval;
546 NOTICE("read-function of plugin `%s' failed. "
547 "Will suspend it for %.3f seconds.",
548 rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
550 /* Success: Restore the interval, if it was changed. */
551 rf->rf_effective_interval = rf->rf_interval;
554 /* update the ``next read due'' field */
557 /* calculate the time spent in the read function */
558 elapsed = (now - start);
560 if (elapsed > rf->rf_effective_interval)
562 "plugin_read_thread: read-function of the `%s' plugin took %.3f "
563 "seconds, which is above its read interval (%.3f seconds). You might "
564 "want to adjust the `Interval' or `ReadThreads' settings.",
565 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed),
566 CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
568 DEBUG("plugin_read_thread: read-function of the `%s' plugin took "
570 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed));
572 DEBUG("plugin_read_thread: Effective interval of the "
573 "`%s' plugin is %.3f seconds.",
574 rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
576 /* Calculate the next (absolute) time at which this function
577 * should be called. */
578 rf->rf_next_read += rf->rf_effective_interval;
580 /* Check, if `rf_next_read' is in the past. */
581 if (rf->rf_next_read < now) {
582 /* `rf_next_read' is in the past. Insert `now'
583 * so this value doesn't trail off into the
585 rf->rf_next_read = now;
588 DEBUG("plugin_read_thread: Next read of the `%s' plugin at %.3f.",
589 rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_next_read));
591 /* Re-insert this read function into the heap again. */
592 c_heap_insert(read_heap, rf);
593 } /* while (read_loop) */
597 } /* void *plugin_read_thread */
599 #ifdef PTHREAD_MAX_NAMELEN_NP
600 #define THREAD_NAME_MAX PTHREAD_MAX_NAMELEN_NP
602 #define THREAD_NAME_MAX 16
605 static void set_thread_name(pthread_t tid, char const *name) {
606 #if defined(HAVE_PTHREAD_SETNAME_NP) || defined(HAVE_PTHREAD_SET_NAME_NP)
608 /* glibc limits the length of the name and fails if the passed string
609 * is too long, so we truncate it here. */
610 char n[THREAD_NAME_MAX];
611 if (strlen(name) >= THREAD_NAME_MAX)
612 WARNING("set_thread_name(\"%s\"): name too long", name);
613 sstrncpy(n, name, sizeof(n));
615 #if defined(HAVE_PTHREAD_SETNAME_NP)
616 int status = pthread_setname_np(tid, n);
618 ERROR("set_thread_name(\"%s\"): %s", n, STRERROR(status));
620 #else /* if defined(HAVE_PTHREAD_SET_NAME_NP) */
621 pthread_set_name_np(tid, n);
627 static void start_read_threads(size_t num) /* {{{ */
629 if (read_threads != NULL)
632 read_threads = (pthread_t *)calloc(num, sizeof(pthread_t));
633 if (read_threads == NULL) {
634 ERROR("plugin: start_read_threads: calloc failed.");
638 read_threads_num = 0;
639 for (size_t i = 0; i < num; i++) {
640 int status = pthread_create(read_threads + read_threads_num,
641 /* attr = */ NULL, plugin_read_thread,
644 ERROR("plugin: start_read_threads: pthread_create failed with status %i "
646 status, STRERROR(status));
650 char name[THREAD_NAME_MAX];
651 snprintf(name, sizeof(name), "reader#%" PRIu64, (uint64_t)read_threads_num);
652 set_thread_name(read_threads[read_threads_num], name);
656 } /* }}} void start_read_threads */
658 static void stop_read_threads(void) {
659 if (read_threads == NULL)
662 INFO("collectd: Stopping %" PRIsz " read threads.", read_threads_num);
664 pthread_mutex_lock(&read_lock);
666 DEBUG("plugin: stop_read_threads: Signalling `read_cond'");
667 pthread_cond_broadcast(&read_cond);
668 pthread_mutex_unlock(&read_lock);
670 for (size_t i = 0; i < read_threads_num; i++) {
671 if (pthread_join(read_threads[i], NULL) != 0) {
672 ERROR("plugin: stop_read_threads: pthread_join failed.");
674 read_threads[i] = (pthread_t)0;
677 read_threads_num = 0;
678 } /* void stop_read_threads */
680 static void plugin_value_list_free(value_list_t *vl) /* {{{ */
685 meta_data_destroy(vl->meta);
688 } /* }}} void plugin_value_list_free */
690 static value_list_t *
691 plugin_value_list_clone(value_list_t const *vl_orig) /* {{{ */
698 vl = malloc(sizeof(*vl));
701 memcpy(vl, vl_orig, sizeof(*vl));
703 if (vl->host[0] == 0)
704 sstrncpy(vl->host, hostname_g, sizeof(vl->host));
706 vl->values = calloc(vl_orig->values_len, sizeof(*vl->values));
707 if (vl->values == NULL) {
708 plugin_value_list_free(vl);
711 memcpy(vl->values, vl_orig->values,
712 vl_orig->values_len * sizeof(*vl->values));
714 vl->meta = meta_data_clone(vl->meta);
715 if ((vl_orig->meta != NULL) && (vl->meta == NULL)) {
716 plugin_value_list_free(vl);
723 /* Fill in the interval from the thread context, if it is zero. */
724 if (vl->interval == 0)
725 vl->interval = plugin_get_interval();
728 } /* }}} value_list_t *plugin_value_list_clone */
730 static int plugin_write_enqueue(value_list_t const *vl) /* {{{ */
734 q = malloc(sizeof(*q));
739 q->vl = plugin_value_list_clone(vl);
745 /* Store context of caller (read plugin); otherwise, it would not be
746 * available to the write plugins when actually dispatching the
747 * value-list later on. */
748 q->ctx = plugin_get_ctx();
750 pthread_mutex_lock(&write_lock);
752 if (write_queue_tail == NULL) {
753 write_queue_head = q;
754 write_queue_tail = q;
755 write_queue_length = 1;
757 write_queue_tail->next = q;
758 write_queue_tail = q;
759 write_queue_length += 1;
762 pthread_cond_signal(&write_cond);
763 pthread_mutex_unlock(&write_lock);
766 } /* }}} int plugin_write_enqueue */
768 static value_list_t *plugin_write_dequeue(void) /* {{{ */
773 pthread_mutex_lock(&write_lock);
775 while (write_loop && (write_queue_head == NULL))
776 pthread_cond_wait(&write_cond, &write_lock);
778 if (write_queue_head == NULL) {
779 pthread_mutex_unlock(&write_lock);
783 q = write_queue_head;
784 write_queue_head = q->next;
785 write_queue_length -= 1;
786 if (write_queue_head == NULL) {
787 write_queue_tail = NULL;
788 assert(0 == write_queue_length);
791 pthread_mutex_unlock(&write_lock);
793 (void)plugin_set_ctx(q->ctx);
798 } /* }}} value_list_t *plugin_write_dequeue */
800 static void *plugin_write_thread(void __attribute__((unused)) * args) /* {{{ */
803 value_list_t *vl = plugin_write_dequeue();
807 plugin_dispatch_values_internal(vl);
809 plugin_value_list_free(vl);
814 } /* }}} void *plugin_write_thread */
816 static void start_write_threads(size_t num) /* {{{ */
818 if (write_threads != NULL)
821 write_threads = (pthread_t *)calloc(num, sizeof(pthread_t));
822 if (write_threads == NULL) {
823 ERROR("plugin: start_write_threads: calloc failed.");
827 write_threads_num = 0;
828 for (size_t i = 0; i < num; i++) {
829 int status = pthread_create(write_threads + write_threads_num,
830 /* attr = */ NULL, plugin_write_thread,
833 ERROR("plugin: start_write_threads: pthread_create failed with status %i "
835 status, STRERROR(status));
839 char name[THREAD_NAME_MAX];
840 snprintf(name, sizeof(name), "writer#%" PRIu64,
841 (uint64_t)write_threads_num);
842 set_thread_name(write_threads[write_threads_num], name);
846 } /* }}} void start_write_threads */
848 static void stop_write_threads(void) /* {{{ */
853 if (write_threads == NULL)
856 INFO("collectd: Stopping %" PRIsz " write threads.", write_threads_num);
858 pthread_mutex_lock(&write_lock);
860 DEBUG("plugin: stop_write_threads: Signalling `write_cond'");
861 pthread_cond_broadcast(&write_cond);
862 pthread_mutex_unlock(&write_lock);
864 for (i = 0; i < write_threads_num; i++) {
865 if (pthread_join(write_threads[i], NULL) != 0) {
866 ERROR("plugin: stop_write_threads: pthread_join failed.");
868 write_threads[i] = (pthread_t)0;
870 sfree(write_threads);
871 write_threads_num = 0;
873 pthread_mutex_lock(&write_lock);
875 for (q = write_queue_head; q != NULL;) {
876 write_queue_t *q1 = q;
877 plugin_value_list_free(q->vl);
882 write_queue_head = NULL;
883 write_queue_tail = NULL;
884 write_queue_length = 0;
885 pthread_mutex_unlock(&write_lock);
888 WARNING("plugin: %" PRIsz " value list%s left after shutting down "
889 "the write threads.",
890 i, (i == 1) ? " was" : "s were");
892 } /* }}} void stop_write_threads */
897 void plugin_set_dir(const char *dir) {
905 plugindir = strdup(dir);
906 if (plugindir == NULL)
907 ERROR("plugin_set_dir: strdup(\"%s\") failed", dir);
910 static bool plugin_is_loaded(char const *name) {
913 if (plugins_loaded == NULL)
915 c_avl_create((int (*)(const void *, const void *))strcasecmp);
916 assert(plugins_loaded != NULL);
918 status = c_avl_get(plugins_loaded, name, /* ret_value = */ NULL);
922 static int plugin_mark_loaded(char const *name) {
926 name_copy = strdup(name);
927 if (name_copy == NULL)
930 status = c_avl_insert(plugins_loaded,
931 /* key = */ name_copy, /* value = */ NULL);
935 static void plugin_free_loaded(void) {
939 if (plugins_loaded == NULL)
942 while (c_avl_pick(plugins_loaded, &key, &value) == 0) {
944 assert(value == NULL);
947 c_avl_destroy(plugins_loaded);
948 plugins_loaded = NULL;
953 #define SHLIB_SUFFIX ".dll"
955 #define SHLIB_SUFFIX ".so"
957 int plugin_load(char const *plugin_name, bool global) {
960 char filename[BUFSIZE] = "";
961 char typename[BUFSIZE];
967 if (plugin_name == NULL)
970 /* Check if plugin is already loaded and don't do anything in this
972 if (plugin_is_loaded(plugin_name))
975 dir = plugin_get_dir();
979 * XXX: Magic at work:
981 * Some of the language bindings, for example the Python and Perl
982 * plugins, need to be able to export symbols to the scripts they run.
983 * For this to happen, the "Globals" flag needs to be set.
984 * Unfortunately, this technical detail is hard to explain to the
985 * average user and she shouldn't have to worry about this, ideally.
986 * So in order to save everyone's sanity use a different default for a
987 * handful of special plugins. --octo
989 if ((strcasecmp("perl", plugin_name) == 0) ||
990 (strcasecmp("python", plugin_name) == 0))
993 /* `cpu' should not match `cpufreq'. To solve this we add SHLIB_SUFFIX to the
994 * type when matching the filename */
995 status = snprintf(typename, sizeof(typename), "%s" SHLIB_SUFFIX, plugin_name);
996 if ((status < 0) || ((size_t)status >= sizeof(typename))) {
997 WARNING("plugin_load: Filename too long: \"%s" SHLIB_SUFFIX "\"",
1002 if ((dh = opendir(dir)) == NULL) {
1003 ERROR("plugin_load: opendir (%s) failed: %s", dir, STRERRNO);
1007 while ((de = readdir(dh)) != NULL) {
1008 if (strcasecmp(de->d_name, typename))
1011 status = snprintf(filename, sizeof(filename), "%s/%s", dir, de->d_name);
1012 if ((status < 0) || ((size_t)status >= sizeof(filename))) {
1013 WARNING("plugin_load: Filename too long: \"%s/%s\"", dir, de->d_name);
1017 if (lstat(filename, &statbuf) == -1) {
1018 WARNING("plugin_load: stat (\"%s\") failed: %s", filename, STRERRNO);
1020 } else if (!S_ISREG(statbuf.st_mode)) {
1021 /* don't follow symlinks */
1022 WARNING("plugin_load: %s is not a regular file.", filename);
1026 status = plugin_load_file(filename, global);
1029 plugin_mark_loaded(plugin_name);
1031 INFO("plugin_load: plugin \"%s\" successfully loaded.", plugin_name);
1034 ERROR("plugin_load: Load plugin \"%s\" failed with "
1036 plugin_name, status);
1042 if (filename[0] == 0)
1043 ERROR("plugin_load: Could not find plugin \"%s\" in %s", plugin_name, dir);
1049 * The `register_*' functions follow
1051 EXPORT int plugin_register_config(const char *name,
1052 int (*callback)(const char *key,
1054 const char **keys, int keys_num) {
1055 cf_register(name, callback, keys, keys_num);
1057 } /* int plugin_register_config */
1059 EXPORT int plugin_register_complex_config(const char *type,
1060 int (*callback)(oconfig_item_t *)) {
1061 return cf_register_complex(type, callback);
1062 } /* int plugin_register_complex_config */
1064 EXPORT int plugin_register_init(const char *name, int (*callback)(void)) {
1065 return create_register_callback(&list_init, name, (void *)callback, NULL);
1066 } /* plugin_register_init */
1068 static int plugin_compare_read_func(const void *arg0, const void *arg1) {
1069 const read_func_t *rf0;
1070 const read_func_t *rf1;
1075 if (rf0->rf_next_read < rf1->rf_next_read)
1077 else if (rf0->rf_next_read > rf1->rf_next_read)
1081 } /* int plugin_compare_read_func */
1083 /* Add a read function to both, the heap and a linked list. The linked list if
1084 * used to look-up read functions, especially for the remove function. The heap
1085 * is used to determine which plugin to read next. */
1086 static int plugin_insert_read(read_func_t *rf) {
1090 rf->rf_next_read = cdtime();
1091 rf->rf_effective_interval = rf->rf_interval;
1093 pthread_mutex_lock(&read_lock);
1095 if (read_list == NULL) {
1096 read_list = llist_create();
1097 if (read_list == NULL) {
1098 pthread_mutex_unlock(&read_lock);
1099 ERROR("plugin_insert_read: read_list failed.");
1104 if (read_heap == NULL) {
1105 read_heap = c_heap_create(plugin_compare_read_func);
1106 if (read_heap == NULL) {
1107 pthread_mutex_unlock(&read_lock);
1108 ERROR("plugin_insert_read: c_heap_create failed.");
1113 le = llist_search(read_list, rf->rf_name);
1115 pthread_mutex_unlock(&read_lock);
1116 P_WARNING("The read function \"%s\" is already registered. "
1117 "Check for duplicates in your configuration!",
1122 le = llentry_create(rf->rf_name, rf);
1124 pthread_mutex_unlock(&read_lock);
1125 ERROR("plugin_insert_read: llentry_create failed.");
1129 status = c_heap_insert(read_heap, rf);
1131 pthread_mutex_unlock(&read_lock);
1132 ERROR("plugin_insert_read: c_heap_insert failed.");
1133 llentry_destroy(le);
1137 /* This does not fail. */
1138 llist_append(read_list, le);
1140 /* Wake up all the read threads. */
1141 pthread_cond_broadcast(&read_cond);
1142 pthread_mutex_unlock(&read_lock);
1144 } /* int plugin_insert_read */
1146 EXPORT int plugin_register_read(const char *name, int (*callback)(void)) {
1150 rf = calloc(1, sizeof(*rf));
1152 ERROR("plugin_register_read: calloc failed.");
1156 rf->rf_callback = (void *)callback;
1157 rf->rf_udata.data = NULL;
1158 rf->rf_udata.free_func = NULL;
1159 rf->rf_ctx = plugin_get_ctx();
1160 rf->rf_group[0] = '\0';
1161 rf->rf_name = strdup(name);
1162 rf->rf_type = RF_SIMPLE;
1163 rf->rf_interval = plugin_get_interval();
1164 rf->rf_ctx.interval = rf->rf_interval;
1166 status = plugin_insert_read(rf);
1173 } /* int plugin_register_read */
1175 EXPORT int plugin_register_complex_read(const char *group, const char *name,
1176 plugin_read_cb callback,
1178 user_data_t const *user_data) {
1182 rf = calloc(1, sizeof(*rf));
1184 free_userdata(user_data);
1185 ERROR("plugin_register_complex_read: calloc failed.");
1189 rf->rf_callback = (void *)callback;
1191 sstrncpy(rf->rf_group, group, sizeof(rf->rf_group));
1193 rf->rf_group[0] = '\0';
1194 rf->rf_name = strdup(name);
1195 rf->rf_type = RF_COMPLEX;
1196 rf->rf_interval = (interval != 0) ? interval : plugin_get_interval();
1199 if (user_data == NULL) {
1200 rf->rf_udata.data = NULL;
1201 rf->rf_udata.free_func = NULL;
1203 rf->rf_udata = *user_data;
1206 rf->rf_ctx = plugin_get_ctx();
1207 rf->rf_ctx.interval = rf->rf_interval;
1209 status = plugin_insert_read(rf);
1211 free_userdata(&rf->rf_udata);
1217 } /* int plugin_register_complex_read */
1219 EXPORT int plugin_register_write(const char *name, plugin_write_cb callback,
1220 user_data_t const *ud) {
1221 return create_register_callback(&list_write, name, (void *)callback, ud);
1222 } /* int plugin_register_write */
1224 static int plugin_flush_timeout_callback(user_data_t *ud) {
1225 flush_callback_t *cb = ud->data;
1227 return plugin_flush(cb->name, cb->timeout, NULL);
1228 } /* static int plugin_flush_callback */
1230 static void plugin_flush_timeout_callback_free(void *data) {
1231 flush_callback_t *cb = data;
1238 } /* static void plugin_flush_callback_free */
1240 static char *plugin_flush_callback_name(const char *name) {
1241 const char *flush_prefix = "flush/";
1246 prefix_size = strlen(flush_prefix);
1247 name_size = strlen(name);
1249 flush_name = malloc(name_size + prefix_size + 1);
1250 if (flush_name == NULL) {
1251 ERROR("plugin_flush_callback_name: malloc failed.");
1255 sstrncpy(flush_name, flush_prefix, prefix_size + 1);
1256 sstrncpy(flush_name + prefix_size, name, name_size + 1);
1259 } /* static char *plugin_flush_callback_name */
1261 EXPORT int plugin_register_flush(const char *name, plugin_flush_cb callback,
1262 user_data_t const *ud) {
1264 plugin_ctx_t ctx = plugin_get_ctx();
1266 status = create_register_callback(&list_flush, name, (void *)callback, ud);
1270 if (ctx.flush_interval != 0) {
1272 flush_callback_t *cb;
1274 flush_name = plugin_flush_callback_name(name);
1275 if (flush_name == NULL)
1278 cb = malloc(sizeof(*cb));
1280 ERROR("plugin_register_flush: malloc failed.");
1285 cb->name = strdup(name);
1286 if (cb->name == NULL) {
1287 ERROR("plugin_register_flush: strdup failed.");
1292 cb->timeout = ctx.flush_timeout;
1294 status = plugin_register_complex_read(
1295 /* group = */ "flush",
1296 /* name = */ flush_name,
1297 /* callback = */ plugin_flush_timeout_callback,
1298 /* interval = */ ctx.flush_interval,
1299 /* user data = */ &(user_data_t){
1300 .data = cb, .free_func = plugin_flush_timeout_callback_free,
1308 } /* int plugin_register_flush */
1310 EXPORT int plugin_register_missing(const char *name, plugin_missing_cb callback,
1311 user_data_t const *ud) {
1312 return create_register_callback(&list_missing, name, (void *)callback, ud);
1313 } /* int plugin_register_missing */
1315 EXPORT int plugin_register_shutdown(const char *name, int (*callback)(void)) {
1316 return create_register_callback(&list_shutdown, name, (void *)callback, NULL);
1317 } /* int plugin_register_shutdown */
1319 static void plugin_free_data_sets(void) {
1323 if (data_sets == NULL)
1326 while (c_avl_pick(data_sets, &key, &value) == 0) {
1327 data_set_t *ds = value;
1328 /* key is a pointer to ds->type */
1334 c_avl_destroy(data_sets);
1336 } /* void plugin_free_data_sets */
1338 EXPORT int plugin_register_data_set(const data_set_t *ds) {
1339 data_set_t *ds_copy;
1341 if ((data_sets != NULL) && (c_avl_get(data_sets, ds->type, NULL) == 0)) {
1342 NOTICE("Replacing DS `%s' with another version.", ds->type);
1343 plugin_unregister_data_set(ds->type);
1344 } else if (data_sets == NULL) {
1345 data_sets = c_avl_create((int (*)(const void *, const void *))strcmp);
1346 if (data_sets == NULL)
1350 ds_copy = malloc(sizeof(*ds_copy));
1351 if (ds_copy == NULL)
1353 memcpy(ds_copy, ds, sizeof(data_set_t));
1355 ds_copy->ds = malloc(sizeof(*ds_copy->ds) * ds->ds_num);
1356 if (ds_copy->ds == NULL) {
1361 for (size_t i = 0; i < ds->ds_num; i++)
1362 memcpy(ds_copy->ds + i, ds->ds + i, sizeof(data_source_t));
1364 return c_avl_insert(data_sets, (void *)ds_copy->type, (void *)ds_copy);
1365 } /* int plugin_register_data_set */
1367 EXPORT int plugin_register_log(const char *name, plugin_log_cb callback,
1368 user_data_t const *ud) {
1369 return create_register_callback(&list_log, name, (void *)callback, ud);
1370 } /* int plugin_register_log */
1372 EXPORT int plugin_register_notification(const char *name,
1373 plugin_notification_cb callback,
1374 user_data_t const *ud) {
1375 return create_register_callback(&list_notification, name, (void *)callback,
1377 } /* int plugin_register_log */
1379 EXPORT int plugin_unregister_config(const char *name) {
1380 cf_unregister(name);
1382 } /* int plugin_unregister_config */
1384 EXPORT int plugin_unregister_complex_config(const char *name) {
1385 cf_unregister_complex(name);
1387 } /* int plugin_unregister_complex_config */
1389 EXPORT int plugin_unregister_init(const char *name) {
1390 return plugin_unregister(list_init, name);
1393 EXPORT int plugin_unregister_read(const char *name) /* {{{ */
1401 pthread_mutex_lock(&read_lock);
1403 if (read_list == NULL) {
1404 pthread_mutex_unlock(&read_lock);
1408 le = llist_search(read_list, name);
1410 pthread_mutex_unlock(&read_lock);
1411 WARNING("plugin_unregister_read: No such read function: %s", name);
1415 llist_remove(read_list, le);
1419 rf->rf_type = RF_REMOVE;
1421 pthread_mutex_unlock(&read_lock);
1423 llentry_destroy(le);
1425 DEBUG("plugin_unregister_read: Marked `%s' for removal.", name);
1428 } /* }}} int plugin_unregister_read */
1430 EXPORT void plugin_log_available_writers(void) {
1431 log_list_callbacks(&list_write, "Available write targets:");
1434 static int compare_read_func_group(llentry_t *e, void *ud) /* {{{ */
1436 read_func_t *rf = e->value;
1439 return strcmp(rf->rf_group, (const char *)group);
1440 } /* }}} int compare_read_func_group */
1442 EXPORT int plugin_unregister_read_group(const char *group) /* {{{ */
1452 pthread_mutex_lock(&read_lock);
1454 if (read_list == NULL) {
1455 pthread_mutex_unlock(&read_lock);
1460 le = llist_search_custom(read_list, compare_read_func_group, (void *)group);
1467 llist_remove(read_list, le);
1471 rf->rf_type = RF_REMOVE;
1473 llentry_destroy(le);
1475 DEBUG("plugin_unregister_read_group: "
1476 "Marked `%s' (group `%s') for removal.",
1477 rf->rf_name, group);
1480 pthread_mutex_unlock(&read_lock);
1483 WARNING("plugin_unregister_read_group: No such "
1484 "group of read function: %s",
1490 } /* }}} int plugin_unregister_read_group */
1492 EXPORT int plugin_unregister_write(const char *name) {
1493 return plugin_unregister(list_write, name);
1496 EXPORT int plugin_unregister_flush(const char *name) {
1497 plugin_ctx_t ctx = plugin_get_ctx();
1499 if (ctx.flush_interval != 0) {
1502 flush_name = plugin_flush_callback_name(name);
1503 if (flush_name != NULL) {
1504 plugin_unregister_read(flush_name);
1509 return plugin_unregister(list_flush, name);
1512 EXPORT int plugin_unregister_missing(const char *name) {
1513 return plugin_unregister(list_missing, name);
1516 EXPORT int plugin_unregister_shutdown(const char *name) {
1517 return plugin_unregister(list_shutdown, name);
1520 EXPORT int plugin_unregister_data_set(const char *name) {
1523 if (data_sets == NULL)
1526 if (c_avl_remove(data_sets, name, NULL, (void *)&ds) != 0)
1533 } /* int plugin_unregister_data_set */
1535 EXPORT int plugin_unregister_log(const char *name) {
1536 return plugin_unregister(list_log, name);
1539 EXPORT int plugin_unregister_notification(const char *name) {
1540 return plugin_unregister(list_notification, name);
1543 EXPORT int plugin_init_all(void) {
1544 char const *chain_name;
1549 /* Init the value cache */
1552 if (IS_TRUE(global_option_get("CollectInternalStats"))) {
1553 record_statistics = true;
1554 plugin_register_read("collectd", plugin_update_internal_statistics);
1557 chain_name = global_option_get("PreCacheChain");
1558 pre_cache_chain = fc_chain_get_by_name(chain_name);
1560 chain_name = global_option_get("PostCacheChain");
1561 post_cache_chain = fc_chain_get_by_name(chain_name);
1563 write_limit_high = global_option_get_long("WriteQueueLimitHigh",
1565 if (write_limit_high < 0) {
1566 ERROR("WriteQueueLimitHigh must be positive or zero.");
1567 write_limit_high = 0;
1571 global_option_get_long("WriteQueueLimitLow",
1572 /* default = */ write_limit_high / 2);
1573 if (write_limit_low < 0) {
1574 ERROR("WriteQueueLimitLow must be positive or zero.");
1575 write_limit_low = write_limit_high / 2;
1576 } else if (write_limit_low > write_limit_high) {
1577 ERROR("WriteQueueLimitLow must not be larger than "
1578 "WriteQueueLimitHigh.");
1579 write_limit_low = write_limit_high;
1582 write_threads_num = global_option_get_long("WriteThreads",
1584 if (write_threads_num < 1) {
1585 ERROR("WriteThreads must be positive.");
1586 write_threads_num = 5;
1589 if ((list_init == NULL) && (read_heap == NULL))
1592 /* Calling all init callbacks before checking if read callbacks
1593 * are available allows the init callbacks to register the read
1595 le = llist_head(list_init);
1596 while (le != NULL) {
1597 callback_func_t *cf;
1598 plugin_init_cb callback;
1599 plugin_ctx_t old_ctx;
1602 old_ctx = plugin_set_ctx(cf->cf_ctx);
1603 callback = cf->cf_callback;
1604 status = (*callback)();
1605 plugin_set_ctx(old_ctx);
1608 ERROR("Initialization of plugin `%s' "
1609 "failed with status %i. "
1610 "Plugin will be unloaded.",
1612 /* Plugins that register read callbacks from the init
1613 * callback should take care of appropriate error
1614 * handling themselves. */
1615 /* FIXME: Unload _all_ functions */
1616 plugin_unregister_read(le->key);
1623 start_write_threads((size_t)write_threads_num);
1626 global_option_get_time("MaxReadInterval", DEFAULT_MAX_READ_INTERVAL);
1628 /* Start read-threads */
1629 if (read_heap != NULL) {
1633 rt = global_option_get("ReadThreads");
1636 start_read_threads((num > 0) ? ((size_t)num) : 5);
1639 } /* void plugin_init_all */
1641 /* TODO: Rename this function. */
1642 EXPORT void plugin_read_all(void) {
1646 } /* void plugin_read_all */
1648 /* Read function called when the `-T' command line argument is given. */
1649 EXPORT int plugin_read_all_once(void) {
1651 int return_status = 0;
1653 if (read_heap == NULL) {
1654 NOTICE("No read-functions are registered.");
1660 plugin_ctx_t old_ctx;
1662 rf = c_heap_get_root(read_heap);
1666 old_ctx = plugin_set_ctx(rf->rf_ctx);
1668 if (rf->rf_type == RF_SIMPLE) {
1669 int (*callback)(void);
1671 callback = rf->rf_callback;
1672 status = (*callback)();
1674 plugin_read_cb callback;
1676 callback = rf->rf_callback;
1677 status = (*callback)(&rf->rf_udata);
1680 plugin_set_ctx(old_ctx);
1683 NOTICE("read-function of plugin `%s' failed.", rf->rf_name);
1688 destroy_callback((void *)rf);
1691 return return_status;
1692 } /* int plugin_read_all_once */
1694 EXPORT int plugin_write(const char *plugin, /* {{{ */
1695 const data_set_t *ds, const value_list_t *vl) {
1702 if (list_write == NULL)
1706 ds = plugin_get_ds(vl->type);
1708 ERROR("plugin_write: Unable to lookup type `%s'.", vl->type);
1713 if (plugin == NULL) {
1717 le = llist_head(list_write);
1718 while (le != NULL) {
1719 callback_func_t *cf = le->value;
1720 plugin_write_cb callback;
1722 /* Keep the read plugin's interval and flush information but update the
1724 plugin_ctx_t old_ctx = plugin_get_ctx();
1725 plugin_ctx_t ctx = old_ctx;
1726 ctx.name = cf->cf_ctx.name;
1727 plugin_set_ctx(ctx);
1729 DEBUG("plugin: plugin_write: Writing values via %s.", le->key);
1730 callback = cf->cf_callback;
1731 status = (*callback)(ds, vl, &cf->cf_udata);
1737 plugin_set_ctx(old_ctx);
1741 if ((success == 0) && (failure != 0))
1745 } else /* plugin != NULL */
1747 callback_func_t *cf;
1748 plugin_write_cb callback;
1750 le = llist_head(list_write);
1751 while (le != NULL) {
1752 if (strcasecmp(plugin, le->key) == 0)
1763 /* do not switch plugin context; rather keep the context (interval)
1764 * information of the calling read plugin */
1766 DEBUG("plugin: plugin_write: Writing values via %s.", le->key);
1767 callback = cf->cf_callback;
1768 status = (*callback)(ds, vl, &cf->cf_udata);
1772 } /* }}} int plugin_write */
1774 EXPORT int plugin_flush(const char *plugin, cdtime_t timeout,
1775 const char *identifier) {
1778 if (list_flush == NULL)
1781 le = llist_head(list_flush);
1782 while (le != NULL) {
1783 callback_func_t *cf;
1784 plugin_flush_cb callback;
1785 plugin_ctx_t old_ctx;
1787 if ((plugin != NULL) && (strcmp(plugin, le->key) != 0)) {
1793 old_ctx = plugin_set_ctx(cf->cf_ctx);
1794 callback = cf->cf_callback;
1796 (*callback)(timeout, identifier, &cf->cf_udata);
1798 plugin_set_ctx(old_ctx);
1803 } /* int plugin_flush */
1805 EXPORT int plugin_shutdown_all(void) {
1807 int ret = 0; // Assume success.
1809 destroy_all_callbacks(&list_init);
1811 stop_read_threads();
1813 pthread_mutex_lock(&read_lock);
1814 llist_destroy(read_list);
1816 pthread_mutex_unlock(&read_lock);
1818 destroy_read_heap();
1820 /* blocks until all write threads have shut down. */
1821 stop_write_threads();
1823 /* ask all plugins to write out the state they kept. */
1824 plugin_flush(/* plugin = */ NULL,
1826 /* identifier = */ NULL);
1829 if (list_shutdown != NULL)
1830 le = llist_head(list_shutdown);
1832 while (le != NULL) {
1833 callback_func_t *cf;
1834 plugin_shutdown_cb callback;
1835 plugin_ctx_t old_ctx;
1838 old_ctx = plugin_set_ctx(cf->cf_ctx);
1839 callback = cf->cf_callback;
1841 /* Advance the pointer before calling the callback allows
1842 * shutdown functions to unregister themselves. If done the
1843 * other way around the memory `le' points to will be freed
1844 * after callback returns. */
1847 if ((*callback)() != 0)
1850 plugin_set_ctx(old_ctx);
1853 /* Write plugins which use the `user_data' pointer usually need the
1854 * same data available to the flush callback. If this is the case, set
1855 * the free_function to NULL when registering the flush callback and to
1856 * the real free function when registering the write callback. This way
1857 * the data isn't freed twice. */
1858 destroy_all_callbacks(&list_flush);
1859 destroy_all_callbacks(&list_missing);
1860 destroy_all_callbacks(&list_write);
1862 destroy_all_callbacks(&list_notification);
1863 destroy_all_callbacks(&list_shutdown);
1864 destroy_all_callbacks(&list_log);
1866 plugin_free_loaded();
1867 plugin_free_data_sets();
1869 } /* void plugin_shutdown_all */
1871 EXPORT int plugin_dispatch_missing(const value_list_t *vl) /* {{{ */
1873 if (list_missing == NULL)
1876 llentry_t *le = llist_head(list_missing);
1877 while (le != NULL) {
1878 callback_func_t *cf = le->value;
1879 plugin_ctx_t old_ctx = plugin_set_ctx(cf->cf_ctx);
1880 plugin_missing_cb callback = cf->cf_callback;
1882 int status = (*callback)(vl, &cf->cf_udata);
1883 plugin_set_ctx(old_ctx);
1886 ERROR("plugin_dispatch_missing: Callback function \"%s\" "
1887 "failed with status %i.",
1898 } /* int }}} plugin_dispatch_missing */
1900 static int plugin_dispatch_values_internal(value_list_t *vl) {
1902 static c_complain_t no_write_complaint = C_COMPLAIN_INIT_STATIC;
1904 bool free_meta_data = false;
1908 /* These fields are initialized by plugin_value_list_clone() if needed: */
1909 assert(vl->host[0] != 0);
1910 assert(vl->time != 0); /* The time is determined at _enqueue_ time. */
1911 assert(vl->interval != 0);
1913 if (vl->type[0] == 0 || vl->values == NULL || vl->values_len < 1) {
1914 ERROR("plugin_dispatch_values: Invalid value list "
1920 /* Free meta data only if the calling function didn't specify any. In
1921 * this case matches and targets may add some and the calling function
1922 * may not expect (and therefore free) that data. */
1923 if (vl->meta == NULL)
1924 free_meta_data = true;
1926 if (list_write == NULL)
1927 c_complain_once(LOG_WARNING, &no_write_complaint,
1928 "plugin_dispatch_values: No write callback has been "
1929 "registered. Please load at least one output plugin, "
1930 "if you want the collected data to be stored.");
1932 if (data_sets == NULL) {
1933 ERROR("plugin_dispatch_values: No data sets registered. "
1934 "Could the types database be read? Check "
1935 "your `TypesDB' setting!");
1939 data_set_t *ds = NULL;
1940 if (c_avl_get(data_sets, vl->type, (void *)&ds) != 0) {
1941 char ident[6 * DATA_MAX_NAME_LEN];
1943 FORMAT_VL(ident, sizeof(ident), vl);
1944 INFO("plugin_dispatch_values: Dataset not found: %s "
1945 "(from \"%s\"), check your types.db!",
1950 DEBUG("plugin_dispatch_values: time = %.3f; interval = %.3f; "
1952 "plugin = %s; plugin_instance = %s; "
1953 "type = %s; type_instance = %s;",
1954 CDTIME_T_TO_DOUBLE(vl->time), CDTIME_T_TO_DOUBLE(vl->interval),
1955 vl->host, vl->plugin, vl->plugin_instance, vl->type, vl->type_instance);
1958 assert(0 == strcmp(ds->type, vl->type));
1960 if (0 != strcmp(ds->type, vl->type))
1961 WARNING("plugin_dispatch_values: (ds->type = %s) != (vl->type = %s)",
1962 ds->type, vl->type);
1966 assert(ds->ds_num == vl->values_len);
1968 if (ds->ds_num != vl->values_len) {
1969 ERROR("plugin_dispatch_values: ds->type = %s: "
1970 "(ds->ds_num = %" PRIsz ") != "
1971 "(vl->values_len = %" PRIsz ")",
1972 ds->type, ds->ds_num, vl->values_len);
1977 escape_slashes(vl->host, sizeof(vl->host));
1978 escape_slashes(vl->plugin, sizeof(vl->plugin));
1979 escape_slashes(vl->plugin_instance, sizeof(vl->plugin_instance));
1980 escape_slashes(vl->type, sizeof(vl->type));
1981 escape_slashes(vl->type_instance, sizeof(vl->type_instance));
1983 if (pre_cache_chain != NULL) {
1984 status = fc_process_chain(ds, vl, pre_cache_chain);
1986 WARNING("plugin_dispatch_values: Running the "
1987 "pre-cache chain failed with "
1990 } else if (status == FC_TARGET_STOP)
1994 /* Update the value cache */
1997 if (post_cache_chain != NULL) {
1998 status = fc_process_chain(ds, vl, post_cache_chain);
2000 WARNING("plugin_dispatch_values: Running the "
2001 "post-cache chain failed with "
2006 fc_default_action(ds, vl);
2008 if ((free_meta_data == true) && (vl->meta != NULL)) {
2009 meta_data_destroy(vl->meta);
2014 } /* int plugin_dispatch_values_internal */
2016 static double get_drop_probability(void) /* {{{ */
2022 pthread_mutex_lock(&write_lock);
2023 wql = write_queue_length;
2024 pthread_mutex_unlock(&write_lock);
2026 if (wql < write_limit_low)
2028 if (wql >= write_limit_high)
2031 pos = 1 + wql - write_limit_low;
2032 size = 1 + write_limit_high - write_limit_low;
2034 return (double)pos / (double)size;
2035 } /* }}} double get_drop_probability */
2037 static bool check_drop_value(void) /* {{{ */
2039 static cdtime_t last_message_time;
2040 static pthread_mutex_t last_message_lock = PTHREAD_MUTEX_INITIALIZER;
2046 if (write_limit_high == 0)
2049 p = get_drop_probability();
2053 status = pthread_mutex_trylock(&last_message_lock);
2058 if ((now - last_message_time) > TIME_T_TO_CDTIME_T(1)) {
2059 last_message_time = now;
2060 ERROR("plugin_dispatch_values: Low water mark "
2061 "reached. Dropping %.0f%% of metrics.",
2064 pthread_mutex_unlock(&last_message_lock);
2075 } /* }}} bool check_drop_value */
2077 EXPORT int plugin_dispatch_values(value_list_t const *vl) {
2079 static pthread_mutex_t statistics_lock = PTHREAD_MUTEX_INITIALIZER;
2081 if (check_drop_value()) {
2082 if (record_statistics) {
2083 pthread_mutex_lock(&statistics_lock);
2084 stats_values_dropped++;
2085 pthread_mutex_unlock(&statistics_lock);
2090 status = plugin_write_enqueue(vl);
2092 ERROR("plugin_dispatch_values: plugin_write_enqueue failed with status %i "
2094 status, STRERROR(status));
2101 __attribute__((sentinel)) int
2102 plugin_dispatch_multivalue(value_list_t const *template, /* {{{ */
2103 bool store_percentage, int store_type, ...) {
2109 assert(template->values_len == 1);
2111 /* Calculate sum for Gauge to calculate percent if needed */
2112 if (DS_TYPE_GAUGE == store_type) {
2113 va_start(ap, store_type);
2118 name = va_arg(ap, char const *);
2122 value = va_arg(ap, gauge_t);
2129 vl = plugin_value_list_clone(template);
2130 /* plugin_value_list_clone makes sure vl->time is set to non-zero. */
2131 if (store_percentage)
2132 sstrncpy(vl->type, "percent", sizeof(vl->type));
2134 va_start(ap, store_type);
2139 /* Set the type instance. */
2140 name = va_arg(ap, char const *);
2143 sstrncpy(vl->type_instance, name, sizeof(vl->type_instance));
2145 /* Set the value. */
2146 switch (store_type) {
2148 vl->values[0].gauge = va_arg(ap, gauge_t);
2149 if (store_percentage)
2150 vl->values[0].gauge *= sum ? (100.0 / sum) : NAN;
2152 case DS_TYPE_ABSOLUTE:
2153 vl->values[0].absolute = va_arg(ap, absolute_t);
2155 case DS_TYPE_COUNTER:
2156 vl->values[0].counter = va_arg(ap, counter_t);
2158 case DS_TYPE_DERIVE:
2159 vl->values[0].derive = va_arg(ap, derive_t);
2162 ERROR("plugin_dispatch_multivalue: given store_type is incorrect.");
2166 status = plugin_write_enqueue(vl);
2172 plugin_value_list_free(vl);
2174 } /* }}} int plugin_dispatch_multivalue */
2176 EXPORT int plugin_dispatch_notification(const notification_t *notif) {
2178 /* Possible TODO: Add flap detection here */
2180 DEBUG("plugin_dispatch_notification: severity = %i; message = %s; "
2181 "time = %.3f; host = %s;",
2182 notif->severity, notif->message, CDTIME_T_TO_DOUBLE(notif->time),
2185 /* Nobody cares for notifications */
2186 if (list_notification == NULL)
2189 le = llist_head(list_notification);
2190 while (le != NULL) {
2191 callback_func_t *cf;
2192 plugin_notification_cb callback;
2195 /* do not switch plugin context; rather keep the context
2196 * (interval) information of the calling plugin */
2199 callback = cf->cf_callback;
2200 status = (*callback)(notif, &cf->cf_udata);
2202 WARNING("plugin_dispatch_notification: Notification "
2203 "callback %s returned %i.",
2211 } /* int plugin_dispatch_notification */
2213 EXPORT void plugin_log(int level, const char *format, ...) {
2219 if (level >= LOG_DEBUG)
2223 va_start(ap, format);
2224 vsnprintf(msg, sizeof(msg), format, ap);
2225 msg[sizeof(msg) - 1] = '\0';
2228 if (list_log == NULL) {
2229 fprintf(stderr, "%s\n", msg);
2233 le = llist_head(list_log);
2234 while (le != NULL) {
2235 callback_func_t *cf;
2236 plugin_log_cb callback;
2239 callback = cf->cf_callback;
2241 /* do not switch plugin context; rather keep the context
2242 * (interval) information of the calling plugin */
2244 (*callback)(level, msg, &cf->cf_udata);
2248 } /* void plugin_log */
2250 void daemon_log(int level, const char *format, ...) {
2251 char msg[1024] = ""; // Size inherits from plugin_log()
2253 char const *name = plugin_get_ctx().name;
2258 va_start(ap, format);
2259 vsnprintf(msg, sizeof(msg), format, ap);
2262 plugin_log(level, "%s plugin: %s", name, msg);
2263 } /* void daemon_log */
2265 int parse_log_severity(const char *severity) {
2268 if ((0 == strcasecmp(severity, "emerg")) ||
2269 (0 == strcasecmp(severity, "alert")) ||
2270 (0 == strcasecmp(severity, "crit")) || (0 == strcasecmp(severity, "err")))
2271 log_level = LOG_ERR;
2272 else if (0 == strcasecmp(severity, "warning"))
2273 log_level = LOG_WARNING;
2274 else if (0 == strcasecmp(severity, "notice"))
2275 log_level = LOG_NOTICE;
2276 else if (0 == strcasecmp(severity, "info"))
2277 log_level = LOG_INFO;
2279 else if (0 == strcasecmp(severity, "debug"))
2280 log_level = LOG_DEBUG;
2281 #endif /* COLLECT_DEBUG */
2284 } /* int parse_log_severity */
2286 EXPORT int parse_notif_severity(const char *severity) {
2287 int notif_severity = -1;
2289 if (strcasecmp(severity, "FAILURE") == 0)
2290 notif_severity = NOTIF_FAILURE;
2291 else if (strcmp(severity, "OKAY") == 0)
2292 notif_severity = NOTIF_OKAY;
2293 else if ((strcmp(severity, "WARNING") == 0) ||
2294 (strcmp(severity, "WARN") == 0))
2295 notif_severity = NOTIF_WARNING;
2297 return notif_severity;
2298 } /* int parse_notif_severity */
2300 EXPORT const data_set_t *plugin_get_ds(const char *name) {
2303 if (data_sets == NULL) {
2304 P_ERROR("plugin_get_ds: No data sets are defined yet.");
2308 if (c_avl_get(data_sets, name, (void *)&ds) != 0) {
2309 DEBUG("No such dataset registered: %s", name);
2314 } /* data_set_t *plugin_get_ds */
2316 static int plugin_notification_meta_add(notification_t *n, const char *name,
2317 enum notification_meta_type_e type,
2318 const void *value) {
2319 notification_meta_t *meta;
2320 notification_meta_t *tail;
2322 if ((n == NULL) || (name == NULL) || (value == NULL)) {
2323 ERROR("plugin_notification_meta_add: A pointer is NULL!");
2327 meta = calloc(1, sizeof(*meta));
2329 ERROR("plugin_notification_meta_add: calloc failed.");
2333 sstrncpy(meta->name, name, sizeof(meta->name));
2337 case NM_TYPE_STRING: {
2338 meta->nm_value.nm_string = strdup((const char *)value);
2339 if (meta->nm_value.nm_string == NULL) {
2340 ERROR("plugin_notification_meta_add: strdup failed.");
2346 case NM_TYPE_SIGNED_INT: {
2347 meta->nm_value.nm_signed_int = *((int64_t *)value);
2350 case NM_TYPE_UNSIGNED_INT: {
2351 meta->nm_value.nm_unsigned_int = *((uint64_t *)value);
2354 case NM_TYPE_DOUBLE: {
2355 meta->nm_value.nm_double = *((double *)value);
2358 case NM_TYPE_BOOLEAN: {
2359 meta->nm_value.nm_boolean = *((bool *)value);
2363 ERROR("plugin_notification_meta_add: Unknown type: %i", type);
2367 } /* switch (type) */
2371 while ((tail != NULL) && (tail->next != NULL))
2380 } /* int plugin_notification_meta_add */
2382 int plugin_notification_meta_add_string(notification_t *n, const char *name,
2383 const char *value) {
2384 return plugin_notification_meta_add(n, name, NM_TYPE_STRING, value);
2387 int plugin_notification_meta_add_signed_int(notification_t *n, const char *name,
2389 return plugin_notification_meta_add(n, name, NM_TYPE_SIGNED_INT, &value);
2392 int plugin_notification_meta_add_unsigned_int(notification_t *n,
2395 return plugin_notification_meta_add(n, name, NM_TYPE_UNSIGNED_INT, &value);
2398 int plugin_notification_meta_add_double(notification_t *n, const char *name,
2400 return plugin_notification_meta_add(n, name, NM_TYPE_DOUBLE, &value);
2403 int plugin_notification_meta_add_boolean(notification_t *n, const char *name,
2405 return plugin_notification_meta_add(n, name, NM_TYPE_BOOLEAN, &value);
2408 int plugin_notification_meta_copy(notification_t *dst,
2409 const notification_t *src) {
2410 assert(dst != NULL);
2411 assert(src != NULL);
2413 assert((src->meta == NULL) || (src->meta != dst->meta));
2415 for (notification_meta_t *meta = src->meta; meta != NULL; meta = meta->next) {
2416 if (meta->type == NM_TYPE_STRING)
2417 plugin_notification_meta_add_string(dst, meta->name,
2418 meta->nm_value.nm_string);
2419 else if (meta->type == NM_TYPE_SIGNED_INT)
2420 plugin_notification_meta_add_signed_int(dst, meta->name,
2421 meta->nm_value.nm_signed_int);
2422 else if (meta->type == NM_TYPE_UNSIGNED_INT)
2423 plugin_notification_meta_add_unsigned_int(dst, meta->name,
2424 meta->nm_value.nm_unsigned_int);
2425 else if (meta->type == NM_TYPE_DOUBLE)
2426 plugin_notification_meta_add_double(dst, meta->name,
2427 meta->nm_value.nm_double);
2428 else if (meta->type == NM_TYPE_BOOLEAN)
2429 plugin_notification_meta_add_boolean(dst, meta->name,
2430 meta->nm_value.nm_boolean);
2434 } /* int plugin_notification_meta_copy */
2436 int plugin_notification_meta_free(notification_meta_t *n) {
2437 notification_meta_t *this;
2438 notification_meta_t *next;
2441 ERROR("plugin_notification_meta_free: n == NULL!");
2446 while (this != NULL) {
2449 if (this->type == NM_TYPE_STRING) {
2450 /* Assign to a temporary variable to work around nm_string's const
2452 void *tmp = (void *)this->nm_value.nm_string;
2455 this->nm_value.nm_string = NULL;
2463 } /* int plugin_notification_meta_free */
2465 static void plugin_ctx_destructor(void *ctx) {
2467 } /* void plugin_ctx_destructor */
2469 static plugin_ctx_t ctx_init = {/* interval = */ 0};
2471 static plugin_ctx_t *plugin_ctx_create(void) {
2474 ctx = malloc(sizeof(*ctx));
2476 ERROR("Failed to allocate plugin context: %s", STRERRNO);
2481 assert(plugin_ctx_key_initialized);
2482 pthread_setspecific(plugin_ctx_key, ctx);
2483 DEBUG("Created new plugin context.");
2485 } /* int plugin_ctx_create */
2487 EXPORT void plugin_init_ctx(void) {
2488 pthread_key_create(&plugin_ctx_key, plugin_ctx_destructor);
2489 plugin_ctx_key_initialized = true;
2490 } /* void plugin_init_ctx */
2492 EXPORT plugin_ctx_t plugin_get_ctx(void) {
2495 assert(plugin_ctx_key_initialized);
2496 ctx = pthread_getspecific(plugin_ctx_key);
2499 ctx = plugin_ctx_create();
2500 /* this must no happen -- exit() instead? */
2506 } /* plugin_ctx_t plugin_get_ctx */
2508 EXPORT plugin_ctx_t plugin_set_ctx(plugin_ctx_t ctx) {
2512 assert(plugin_ctx_key_initialized);
2513 c = pthread_getspecific(plugin_ctx_key);
2516 c = plugin_ctx_create();
2517 /* this must no happen -- exit() instead? */
2526 } /* void plugin_set_ctx */
2528 EXPORT cdtime_t plugin_get_interval(void) {
2531 interval = plugin_get_ctx().interval;
2535 P_ERROR("plugin_get_interval: Unable to determine Interval from context.");
2537 return cf_get_default_interval();
2538 } /* cdtime_t plugin_get_interval */
2542 void *(*start_routine)(void *);
2546 static void *plugin_thread_start(void *arg) {
2547 plugin_thread_t *plugin_thread = arg;
2549 void *(*start_routine)(void *) = plugin_thread->start_routine;
2550 void *plugin_arg = plugin_thread->arg;
2552 plugin_set_ctx(plugin_thread->ctx);
2554 sfree(plugin_thread);
2556 return start_routine(plugin_arg);
2557 } /* void *plugin_thread_start */
2559 int plugin_thread_create(pthread_t *thread, const pthread_attr_t *attr,
2560 void *(*start_routine)(void *), void *arg,
2562 plugin_thread_t *plugin_thread;
2564 plugin_thread = malloc(sizeof(*plugin_thread));
2565 if (plugin_thread == NULL)
2568 plugin_thread->ctx = plugin_get_ctx();
2569 plugin_thread->start_routine = start_routine;
2570 plugin_thread->arg = arg;
2572 int ret = pthread_create(thread, attr, plugin_thread_start, plugin_thread);
2574 sfree(plugin_thread);
2579 set_thread_name(*thread, name);
2582 } /* int plugin_thread_create */