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 #include <pthread_np.h> /* for pthread_set_name_np(3) */
54 struct callback_func_s {
59 typedef struct callback_func_s callback_func_t;
63 #define RF_REMOVE 65535
65 /* `read_func_t' "inherits" from `callback_func_t'.
66 * The `rf_super' member MUST be the first one in this structure! */
67 #define rf_callback rf_super.cf_callback
68 #define rf_udata rf_super.cf_udata
69 #define rf_ctx rf_super.cf_ctx
70 callback_func_t rf_super;
71 char rf_group[DATA_MAX_NAME_LEN];
75 cdtime_t rf_effective_interval;
76 cdtime_t rf_next_read;
78 typedef struct read_func_s read_func_t;
81 typedef struct write_queue_s write_queue_t;
82 struct write_queue_s {
88 struct flush_callback_s {
92 typedef struct flush_callback_s flush_callback_t;
97 static c_avl_tree_t *plugins_loaded = NULL;
99 static llist_t *list_init;
100 static llist_t *list_write;
101 static llist_t *list_flush;
102 static llist_t *list_missing;
103 static llist_t *list_shutdown;
104 static llist_t *list_log;
105 static llist_t *list_notification;
107 static fc_chain_t *pre_cache_chain = NULL;
108 static fc_chain_t *post_cache_chain = NULL;
110 static c_avl_tree_t *data_sets;
112 static char *plugindir = NULL;
114 #ifndef DEFAULT_MAX_READ_INTERVAL
115 #define DEFAULT_MAX_READ_INTERVAL TIME_T_TO_CDTIME_T_STATIC(86400)
117 static c_heap_t *read_heap = NULL;
118 static llist_t *read_list;
119 static int read_loop = 1;
120 static pthread_mutex_t read_lock = PTHREAD_MUTEX_INITIALIZER;
121 static pthread_cond_t read_cond = PTHREAD_COND_INITIALIZER;
122 static pthread_t *read_threads = NULL;
123 static size_t read_threads_num = 0;
124 static cdtime_t max_read_interval = DEFAULT_MAX_READ_INTERVAL;
126 static write_queue_t *write_queue_head;
127 static write_queue_t *write_queue_tail;
128 static long write_queue_length = 0;
129 static _Bool write_loop = 1;
130 static pthread_mutex_t write_lock = PTHREAD_MUTEX_INITIALIZER;
131 static pthread_cond_t write_cond = PTHREAD_COND_INITIALIZER;
132 static pthread_t *write_threads = NULL;
133 static size_t write_threads_num = 0;
135 static pthread_key_t plugin_ctx_key;
136 static _Bool plugin_ctx_key_initialized = 0;
138 static long write_limit_high = 0;
139 static long write_limit_low = 0;
141 static derive_t stats_values_dropped = 0;
142 static _Bool record_statistics = 0;
147 static int plugin_dispatch_values_internal(value_list_t *vl);
149 static const char *plugin_get_dir(void) {
150 if (plugindir == NULL)
156 static int plugin_update_internal_statistics(void) { /* {{{ */
157 gauge_t copy_write_queue_length = (gauge_t)write_queue_length;
159 /* Initialize `vl' */
160 value_list_t vl = VALUE_LIST_INIT;
161 sstrncpy(vl.plugin, "collectd", sizeof(vl.plugin));
164 sstrncpy(vl.plugin_instance, "write_queue", sizeof(vl.plugin_instance));
166 /* Write queue : queue length */
167 vl.values = &(value_t){.gauge = copy_write_queue_length};
169 sstrncpy(vl.type, "queue_length", sizeof(vl.type));
170 vl.type_instance[0] = 0;
171 plugin_dispatch_values(&vl);
173 /* Write queue : Values dropped (queue length > low limit) */
174 vl.values = &(value_t){.gauge = (gauge_t)stats_values_dropped};
176 sstrncpy(vl.type, "derive", sizeof(vl.type));
177 sstrncpy(vl.type_instance, "dropped", sizeof(vl.type_instance));
178 plugin_dispatch_values(&vl);
181 sstrncpy(vl.plugin_instance, "cache", sizeof(vl.plugin_instance));
183 /* Cache : Nb entry in cache tree */
184 vl.values = &(value_t){.gauge = (gauge_t)uc_get_size()};
186 sstrncpy(vl.type, "cache_size", sizeof(vl.type));
187 vl.type_instance[0] = 0;
188 plugin_dispatch_values(&vl);
191 } /* }}} int plugin_update_internal_statistics */
193 static void destroy_callback(callback_func_t *cf) /* {{{ */
198 if ((cf->cf_udata.data != NULL) && (cf->cf_udata.free_func != NULL)) {
199 cf->cf_udata.free_func(cf->cf_udata.data);
200 cf->cf_udata.data = NULL;
201 cf->cf_udata.free_func = NULL;
204 } /* }}} void destroy_callback */
206 static void destroy_all_callbacks(llist_t **list) /* {{{ */
213 le = llist_head(*list);
220 destroy_callback(le->value);
226 llist_destroy(*list);
228 } /* }}} void destroy_all_callbacks */
230 static void destroy_read_heap(void) /* {{{ */
232 if (read_heap == NULL)
238 rf = c_heap_get_root(read_heap);
242 destroy_callback((callback_func_t *)rf);
245 c_heap_destroy(read_heap);
247 } /* }}} void destroy_read_heap */
249 static int register_callback(llist_t **list, /* {{{ */
250 const char *name, callback_func_t *cf) {
255 *list = llist_create();
257 ERROR("plugin: register_callback: "
258 "llist_create failed.");
259 destroy_callback(cf);
266 ERROR("plugin: register_callback: strdup failed.");
267 destroy_callback(cf);
271 le = llist_search(*list, name);
273 le = llentry_create(key, cf);
275 ERROR("plugin: register_callback: "
276 "llentry_create failed.");
278 destroy_callback(cf);
282 llist_append(*list, le);
284 callback_func_t *old_cf;
289 WARNING("plugin: register_callback: "
290 "a callback named `%s' already exists - "
291 "overwriting the old entry!",
294 destroy_callback(old_cf);
299 } /* }}} int register_callback */
301 static void log_list_callbacks(llist_t **list, /* {{{ */
302 const char *comment) {
310 n = llist_size(*list);
312 INFO("%s [none]", comment);
316 keys = calloc(n, sizeof(char *));
319 ERROR("%s: failed to allocate memory for list of callbacks", comment);
324 for (le = llist_head(*list), i = 0, len = 0; le != NULL; le = le->next, i++) {
326 len += strlen(le->key) + 6;
328 str = malloc(len + 10);
330 ERROR("%s: failed to allocate memory for list of callbacks", comment);
333 strjoin(str, len, keys, n, "', '");
334 INFO("%s ['%s']", comment, str);
338 } /* }}} void log_list_callbacks */
340 static int create_register_callback(llist_t **list, /* {{{ */
341 const char *name, void *callback,
342 user_data_t const *ud) {
345 cf = calloc(1, sizeof(*cf));
347 ERROR("plugin: create_register_callback: calloc failed.");
351 cf->cf_callback = callback;
353 cf->cf_udata.data = NULL;
354 cf->cf_udata.free_func = NULL;
359 cf->cf_ctx = plugin_get_ctx();
361 return (register_callback(list, name, cf));
362 } /* }}} int create_register_callback */
364 static int plugin_unregister(llist_t *list, const char *name) /* {{{ */
371 e = llist_search(list, name);
375 llist_remove(list, e);
378 destroy_callback(e->value);
383 } /* }}} int plugin_unregister */
386 * (Try to) load the shared object `file'. Won't complain if it isn't a shared
387 * object, but it will bitch about a shared object not having a
388 * ``module_register'' symbol..
390 static int plugin_load_file(char *file, uint32_t flags) {
392 void (*reg_handle)(void);
395 lt_dlerror(); /* clear errors */
397 #if LIBTOOL_VERSION == 2
398 if (flags & PLUGIN_FLAGS_GLOBAL) {
400 lt_dladvise_init(&advise);
401 lt_dladvise_global(&advise);
402 dlh = lt_dlopenadvise(file, advise);
403 lt_dladvise_destroy(&advise);
405 dlh = lt_dlopen(file);
407 #else /* if LIBTOOL_VERSION == 1 */
408 if (flags & PLUGIN_FLAGS_GLOBAL)
409 WARNING("plugin_load_file: The global flag is not supported, "
410 "libtool 2 is required for this.");
411 dlh = lt_dlopen(file);
415 char errbuf[1024] = "";
417 ssnprintf(errbuf, sizeof(errbuf),
418 "lt_dlopen (\"%s\") failed: %s. "
419 "The most common cause for this problem is "
420 "missing dependencies. Use ldd(1) to check "
421 "the dependencies of the plugin "
426 /* Make sure this is printed to STDERR in any case, but also
427 * make sure it's printed only once. */
428 if (list_log != NULL)
429 fprintf(stderr, "ERROR: %s\n", errbuf);
434 if ((reg_handle = (void (*)(void))lt_dlsym(dlh, "module_register")) == NULL) {
435 WARNING("Couldn't find symbol \"module_register\" in \"%s\": %s\n", file,
446 static void *plugin_read_thread(void __attribute__((unused)) * args) {
447 while (read_loop != 0) {
449 plugin_ctx_t old_ctx;
457 /* Get the read function that needs to be read next.
458 * We don't need to hold "read_lock" for the heap, but we need
459 * to call c_heap_get_root() and pthread_cond_wait() in the
460 * same protected block. */
461 pthread_mutex_lock(&read_lock);
462 rf = c_heap_get_root(read_heap);
464 pthread_cond_wait(&read_cond, &read_lock);
465 pthread_mutex_unlock(&read_lock);
468 pthread_mutex_unlock(&read_lock);
470 if (rf->rf_interval == 0) {
471 /* this should not happen, because the interval is set
472 * for each plugin when loading it
473 * XXX: issue a warning? */
474 rf->rf_interval = plugin_get_interval();
475 rf->rf_effective_interval = rf->rf_interval;
477 rf->rf_next_read = cdtime();
480 /* sleep until this entry is due,
481 * using pthread_cond_timedwait */
482 pthread_mutex_lock(&read_lock);
483 /* In pthread_cond_timedwait, spurious wakeups are possible
484 * (and really happen, at least on NetBSD with > 1 CPU), thus
485 * we need to re-evaluate the condition every time
486 * pthread_cond_timedwait returns. */
488 while ((read_loop != 0) && (cdtime() < rf->rf_next_read) && rc == 0) {
489 rc = pthread_cond_timedwait(&read_cond, &read_lock,
490 &CDTIME_T_TO_TIMESPEC(rf->rf_next_read));
493 /* Must hold `read_lock' when accessing `rf->rf_type'. */
494 rf_type = rf->rf_type;
495 pthread_mutex_unlock(&read_lock);
497 /* Check if we're supposed to stop.. This may have interrupted
499 if (read_loop == 0) {
500 /* Insert `rf' again, so it can be free'd correctly */
501 c_heap_insert(read_heap, rf);
505 /* The entry has been marked for deletion. The linked list
506 * entry has already been removed by `plugin_unregister_read'.
507 * All we have to do here is free the `read_func_t' and
509 if (rf_type == RF_REMOVE) {
510 DEBUG("plugin_read_thread: Destroying the `%s' "
514 destroy_callback((callback_func_t *)rf);
519 DEBUG("plugin_read_thread: Handling `%s'.", rf->rf_name);
523 old_ctx = plugin_set_ctx(rf->rf_ctx);
525 if (rf_type == RF_SIMPLE) {
526 int (*callback)(void);
528 callback = rf->rf_callback;
529 status = (*callback)();
531 plugin_read_cb callback;
533 assert(rf_type == RF_COMPLEX);
535 callback = rf->rf_callback;
536 status = (*callback)(&rf->rf_udata);
539 plugin_set_ctx(old_ctx);
541 /* If the function signals failure, we will increase the
542 * intervals in which it will be called. */
544 rf->rf_effective_interval *= 2;
545 if (rf->rf_effective_interval > max_read_interval)
546 rf->rf_effective_interval = max_read_interval;
548 NOTICE("read-function of plugin `%s' failed. "
549 "Will suspend it for %.3f seconds.",
550 rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
552 /* Success: Restore the interval, if it was changed. */
553 rf->rf_effective_interval = rf->rf_interval;
556 /* update the ``next read due'' field */
559 /* calculate the time spent in the read function */
560 elapsed = (now - start);
562 if (elapsed > rf->rf_effective_interval)
564 "plugin_read_thread: read-function of the `%s' plugin took %.3f "
565 "seconds, which is above its read interval (%.3f seconds). You might "
566 "want to adjust the `Interval' or `ReadThreads' settings.",
567 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed),
568 CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
570 DEBUG("plugin_read_thread: read-function of the `%s' plugin took "
572 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed));
574 DEBUG("plugin_read_thread: Effective interval of the "
575 "`%s' plugin is %.3f seconds.",
576 rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
578 /* Calculate the next (absolute) time at which this function
579 * should be called. */
580 rf->rf_next_read += rf->rf_effective_interval;
582 /* Check, if `rf_next_read' is in the past. */
583 if (rf->rf_next_read < now) {
584 /* `rf_next_read' is in the past. Insert `now'
585 * so this value doesn't trail off into the
587 rf->rf_next_read = now;
590 DEBUG("plugin_read_thread: Next read of the `%s' plugin at %.3f.",
591 rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_next_read));
593 /* Re-insert this read function into the heap again. */
594 c_heap_insert(read_heap, rf);
595 } /* while (read_loop) */
599 } /* void *plugin_read_thread */
601 #ifdef PTHREAD_MAX_NAMELEN_NP
602 #define THREAD_NAME_MAX PTHREAD_MAX_NAMELEN_NP
604 #define THREAD_NAME_MAX 16
607 static void set_thread_name(pthread_t tid, char const *name) {
608 #if defined(HAVE_PTHREAD_SETNAME_NP) || defined(HAVE_PTHREAD_SET_NAME_NP)
610 /* glibc limits the length of the name and fails if the passed string
611 * is too long, so we truncate it here. */
612 char n[THREAD_NAME_MAX];
613 if (strlen(name) >= THREAD_NAME_MAX)
614 WARNING("set_thread_name(\"%s\"): name too long", name);
615 sstrncpy(n, name, sizeof(n));
617 #if defined(HAVE_PTHREAD_SETNAME_NP)
618 int status = pthread_setname_np(tid, n);
621 ERROR("set_thread_name(\"%s\"): %s", n,
622 sstrerror(status, errbuf, sizeof(errbuf)));
624 #else /* if defined(HAVE_PTHREAD_SET_NAME_NP) */
625 pthread_set_name_np(tid, n);
631 static void start_read_threads(size_t num) /* {{{ */
633 if (read_threads != NULL)
636 read_threads = (pthread_t *)calloc(num, sizeof(pthread_t));
637 if (read_threads == NULL) {
638 ERROR("plugin: start_read_threads: calloc failed.");
642 read_threads_num = 0;
643 for (size_t i = 0; i < num; i++) {
644 int status = pthread_create(read_threads + read_threads_num,
645 /* attr = */ NULL, plugin_read_thread,
649 ERROR("plugin: start_read_threads: pthread_create failed "
650 "with status %i (%s).",
651 status, sstrerror(status, errbuf, sizeof(errbuf)));
655 char name[THREAD_NAME_MAX];
656 ssnprintf(name, sizeof(name), "reader#%zu", 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 %zu 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 plugin_ctx_t ctx = plugin_get_ctx();
732 if (ctx.interval != 0)
733 vl->interval = ctx.interval;
735 char name[6 * DATA_MAX_NAME_LEN];
736 FORMAT_VL(name, sizeof(name), vl);
737 ERROR("plugin_value_list_clone: Unable to determine "
738 "interval from context for "
739 "value list \"%s\". "
740 "This indicates a broken plugin. "
741 "Please report this problem to the "
742 "collectd mailing list or at "
743 "<http://collectd.org/bugs/>.",
745 vl->interval = cf_get_default_interval();
750 } /* }}} value_list_t *plugin_value_list_clone */
752 static int plugin_write_enqueue(value_list_t const *vl) /* {{{ */
756 q = malloc(sizeof(*q));
761 q->vl = plugin_value_list_clone(vl);
767 /* Store context of caller (read plugin); otherwise, it would not be
768 * available to the write plugins when actually dispatching the
769 * value-list later on. */
770 q->ctx = plugin_get_ctx();
772 pthread_mutex_lock(&write_lock);
774 if (write_queue_tail == NULL) {
775 write_queue_head = q;
776 write_queue_tail = q;
777 write_queue_length = 1;
779 write_queue_tail->next = q;
780 write_queue_tail = q;
781 write_queue_length += 1;
784 pthread_cond_signal(&write_cond);
785 pthread_mutex_unlock(&write_lock);
788 } /* }}} int plugin_write_enqueue */
790 static value_list_t *plugin_write_dequeue(void) /* {{{ */
795 pthread_mutex_lock(&write_lock);
797 while (write_loop && (write_queue_head == NULL))
798 pthread_cond_wait(&write_cond, &write_lock);
800 if (write_queue_head == NULL) {
801 pthread_mutex_unlock(&write_lock);
805 q = write_queue_head;
806 write_queue_head = q->next;
807 write_queue_length -= 1;
808 if (write_queue_head == NULL) {
809 write_queue_tail = NULL;
810 assert(0 == write_queue_length);
813 pthread_mutex_unlock(&write_lock);
815 (void)plugin_set_ctx(q->ctx);
820 } /* }}} value_list_t *plugin_write_dequeue */
822 static void *plugin_write_thread(void __attribute__((unused)) * args) /* {{{ */
825 value_list_t *vl = plugin_write_dequeue();
829 plugin_dispatch_values_internal(vl);
831 plugin_value_list_free(vl);
836 } /* }}} void *plugin_write_thread */
838 static void start_write_threads(size_t num) /* {{{ */
840 if (write_threads != NULL)
843 write_threads = (pthread_t *)calloc(num, sizeof(pthread_t));
844 if (write_threads == NULL) {
845 ERROR("plugin: start_write_threads: calloc failed.");
849 write_threads_num = 0;
850 for (size_t i = 0; i < num; i++) {
851 int status = pthread_create(write_threads + write_threads_num,
852 /* attr = */ NULL, plugin_write_thread,
856 ERROR("plugin: start_write_threads: pthread_create failed "
857 "with status %i (%s).",
858 status, sstrerror(status, errbuf, sizeof(errbuf)));
862 char name[THREAD_NAME_MAX];
863 ssnprintf(name, sizeof(name), "writer#%zu", write_threads_num);
864 set_thread_name(write_threads[write_threads_num], name);
868 } /* }}} void start_write_threads */
870 static void stop_write_threads(void) /* {{{ */
875 if (write_threads == NULL)
878 INFO("collectd: Stopping %zu write threads.", write_threads_num);
880 pthread_mutex_lock(&write_lock);
882 DEBUG("plugin: stop_write_threads: Signalling `write_cond'");
883 pthread_cond_broadcast(&write_cond);
884 pthread_mutex_unlock(&write_lock);
886 for (i = 0; i < write_threads_num; i++) {
887 if (pthread_join(write_threads[i], NULL) != 0) {
888 ERROR("plugin: stop_write_threads: pthread_join failed.");
890 write_threads[i] = (pthread_t)0;
892 sfree(write_threads);
893 write_threads_num = 0;
895 pthread_mutex_lock(&write_lock);
897 for (q = write_queue_head; q != NULL;) {
898 write_queue_t *q1 = q;
899 plugin_value_list_free(q->vl);
904 write_queue_head = NULL;
905 write_queue_tail = NULL;
906 write_queue_length = 0;
907 pthread_mutex_unlock(&write_lock);
910 WARNING("plugin: %zu value list%s left after shutting down "
911 "the write threads.",
912 i, (i == 1) ? " was" : "s were");
914 } /* }}} void stop_write_threads */
919 void plugin_set_dir(const char *dir) {
927 plugindir = strdup(dir);
928 if (plugindir == NULL)
929 ERROR("plugin_set_dir: strdup(\"%s\") failed", dir);
932 static _Bool plugin_is_loaded(char const *name) {
935 if (plugins_loaded == NULL)
937 c_avl_create((int (*)(const void *, const void *))strcasecmp);
938 assert(plugins_loaded != NULL);
940 status = c_avl_get(plugins_loaded, name, /* ret_value = */ NULL);
941 return (status == 0);
944 static int plugin_mark_loaded(char const *name) {
948 name_copy = strdup(name);
949 if (name_copy == NULL)
952 status = c_avl_insert(plugins_loaded,
953 /* key = */ name_copy, /* value = */ NULL);
957 static void plugin_free_loaded(void) {
961 if (plugins_loaded == NULL)
964 while (c_avl_pick(plugins_loaded, &key, &value) == 0) {
966 assert(value == NULL);
969 c_avl_destroy(plugins_loaded);
970 plugins_loaded = NULL;
974 int plugin_load(char const *plugin_name, uint32_t flags) {
977 char filename[BUFSIZE] = "";
978 char typename[BUFSIZE];
984 if (plugin_name == NULL)
987 /* Check if plugin is already loaded and don't do anything in this
989 if (plugin_is_loaded(plugin_name))
992 dir = plugin_get_dir();
996 * XXX: Magic at work:
998 * Some of the language bindings, for example the Python and Perl
999 * plugins, need to be able to export symbols to the scripts they run.
1000 * For this to happen, the "Globals" flag needs to be set.
1001 * Unfortunately, this technical detail is hard to explain to the
1002 * average user and she shouldn't have to worry about this, ideally.
1003 * So in order to save everyone's sanity use a different default for a
1004 * handful of special plugins. --octo
1006 if ((strcasecmp("perl", plugin_name) == 0) ||
1007 (strcasecmp("python", plugin_name) == 0))
1008 flags |= PLUGIN_FLAGS_GLOBAL;
1010 /* `cpu' should not match `cpufreq'. To solve this we add `.so' to the
1011 * type when matching the filename */
1012 status = ssnprintf(typename, sizeof(typename), "%s.so", plugin_name);
1013 if ((status < 0) || ((size_t)status >= sizeof(typename))) {
1014 WARNING("plugin_load: Filename too long: \"%s.so\"", plugin_name);
1018 if ((dh = opendir(dir)) == NULL) {
1020 ERROR("plugin_load: opendir (%s) failed: %s", dir,
1021 sstrerror(errno, errbuf, sizeof(errbuf)));
1025 while ((de = readdir(dh)) != NULL) {
1026 if (strcasecmp(de->d_name, typename))
1029 status = ssnprintf(filename, sizeof(filename), "%s/%s", dir, de->d_name);
1030 if ((status < 0) || ((size_t)status >= sizeof(filename))) {
1031 WARNING("plugin_load: Filename too long: \"%s/%s\"", dir, de->d_name);
1035 if (lstat(filename, &statbuf) == -1) {
1037 WARNING("plugin_load: stat (\"%s\") failed: %s", filename,
1038 sstrerror(errno, errbuf, sizeof(errbuf)));
1040 } else if (!S_ISREG(statbuf.st_mode)) {
1041 /* don't follow symlinks */
1042 WARNING("plugin_load: %s is not a regular file.", filename);
1046 status = plugin_load_file(filename, flags);
1049 plugin_mark_loaded(plugin_name);
1051 INFO("plugin_load: plugin \"%s\" successfully loaded.", plugin_name);
1054 ERROR("plugin_load: Load plugin \"%s\" failed with "
1056 plugin_name, status);
1062 if (filename[0] == 0)
1063 ERROR("plugin_load: Could not find plugin \"%s\" in %s", plugin_name, dir);
1069 * The `register_*' functions follow
1071 int plugin_register_config(const char *name,
1072 int (*callback)(const char *key, const char *val),
1073 const char **keys, int keys_num) {
1074 cf_register(name, callback, keys, keys_num);
1076 } /* int plugin_register_config */
1078 int plugin_register_complex_config(const char *type,
1079 int (*callback)(oconfig_item_t *)) {
1080 return (cf_register_complex(type, callback));
1081 } /* int plugin_register_complex_config */
1083 int plugin_register_init(const char *name, int (*callback)(void)) {
1084 return (create_register_callback(&list_init, name, (void *)callback,
1085 /* user_data = */ NULL));
1086 } /* plugin_register_init */
1088 static int plugin_compare_read_func(const void *arg0, const void *arg1) {
1089 const read_func_t *rf0;
1090 const read_func_t *rf1;
1095 if (rf0->rf_next_read < rf1->rf_next_read)
1097 else if (rf0->rf_next_read > rf1->rf_next_read)
1101 } /* int plugin_compare_read_func */
1103 /* Add a read function to both, the heap and a linked list. The linked list if
1104 * used to look-up read functions, especially for the remove function. The heap
1105 * is used to determine which plugin to read next. */
1106 static int plugin_insert_read(read_func_t *rf) {
1110 rf->rf_next_read = cdtime();
1111 rf->rf_effective_interval = rf->rf_interval;
1113 pthread_mutex_lock(&read_lock);
1115 if (read_list == NULL) {
1116 read_list = llist_create();
1117 if (read_list == NULL) {
1118 pthread_mutex_unlock(&read_lock);
1119 ERROR("plugin_insert_read: read_list failed.");
1124 if (read_heap == NULL) {
1125 read_heap = c_heap_create(plugin_compare_read_func);
1126 if (read_heap == NULL) {
1127 pthread_mutex_unlock(&read_lock);
1128 ERROR("plugin_insert_read: c_heap_create failed.");
1133 le = llist_search(read_list, rf->rf_name);
1135 pthread_mutex_unlock(&read_lock);
1136 WARNING("The read function \"%s\" is already registered. "
1137 "Check for duplicate \"LoadPlugin\" lines "
1138 "in your configuration!",
1143 le = llentry_create(rf->rf_name, rf);
1145 pthread_mutex_unlock(&read_lock);
1146 ERROR("plugin_insert_read: llentry_create failed.");
1150 status = c_heap_insert(read_heap, rf);
1152 pthread_mutex_unlock(&read_lock);
1153 ERROR("plugin_insert_read: c_heap_insert failed.");
1154 llentry_destroy(le);
1158 /* This does not fail. */
1159 llist_append(read_list, le);
1161 /* Wake up all the read threads. */
1162 pthread_cond_broadcast(&read_cond);
1163 pthread_mutex_unlock(&read_lock);
1165 } /* int plugin_insert_read */
1167 int plugin_register_read(const char *name, int (*callback)(void)) {
1171 rf = calloc(1, sizeof(*rf));
1173 ERROR("plugin_register_read: calloc failed.");
1177 rf->rf_callback = (void *)callback;
1178 rf->rf_udata.data = NULL;
1179 rf->rf_udata.free_func = NULL;
1180 rf->rf_ctx = plugin_get_ctx();
1181 rf->rf_group[0] = '\0';
1182 rf->rf_name = strdup(name);
1183 rf->rf_type = RF_SIMPLE;
1184 rf->rf_interval = plugin_get_interval();
1186 status = plugin_insert_read(rf);
1193 } /* int plugin_register_read */
1195 int plugin_register_complex_read(const char *group, const char *name,
1196 plugin_read_cb callback, cdtime_t interval,
1197 user_data_t const *user_data) {
1201 rf = calloc(1, sizeof(*rf));
1203 ERROR("plugin_register_complex_read: calloc failed.");
1207 rf->rf_callback = (void *)callback;
1209 sstrncpy(rf->rf_group, group, sizeof(rf->rf_group));
1211 rf->rf_group[0] = '\0';
1212 rf->rf_name = strdup(name);
1213 rf->rf_type = RF_COMPLEX;
1214 rf->rf_interval = (interval != 0) ? interval : plugin_get_interval();
1217 if (user_data == NULL) {
1218 rf->rf_udata.data = NULL;
1219 rf->rf_udata.free_func = NULL;
1221 rf->rf_udata = *user_data;
1224 rf->rf_ctx = plugin_get_ctx();
1226 status = plugin_insert_read(rf);
1233 } /* int plugin_register_complex_read */
1235 int plugin_register_write(const char *name, plugin_write_cb callback,
1236 user_data_t const *ud) {
1237 return (create_register_callback(&list_write, name, (void *)callback, ud));
1238 } /* int plugin_register_write */
1240 static int plugin_flush_timeout_callback(user_data_t *ud) {
1241 flush_callback_t *cb = ud->data;
1243 return plugin_flush(cb->name, cb->timeout, /* identifier = */ NULL);
1244 } /* static int plugin_flush_callback */
1246 static void plugin_flush_timeout_callback_free(void *data) {
1247 flush_callback_t *cb = data;
1254 } /* static void plugin_flush_callback_free */
1256 static char *plugin_flush_callback_name(const char *name) {
1257 const char *flush_prefix = "flush/";
1262 prefix_size = strlen(flush_prefix);
1263 name_size = strlen(name);
1265 flush_name = malloc(name_size + prefix_size + 1);
1266 if (flush_name == NULL) {
1267 ERROR("plugin_flush_callback_name: malloc failed.");
1271 sstrncpy(flush_name, flush_prefix, prefix_size + 1);
1272 sstrncpy(flush_name + prefix_size, name, name_size + 1);
1275 } /* static char *plugin_flush_callback_name */
1277 int plugin_register_flush(const char *name, plugin_flush_cb callback,
1278 user_data_t const *ud) {
1280 plugin_ctx_t ctx = plugin_get_ctx();
1282 status = create_register_callback(&list_flush, name, (void *)callback, ud);
1286 if (ctx.flush_interval != 0) {
1288 flush_callback_t *cb;
1290 flush_name = plugin_flush_callback_name(name);
1291 if (flush_name == NULL)
1294 cb = malloc(sizeof(*cb));
1296 ERROR("plugin_register_flush: malloc failed.");
1301 cb->name = strdup(name);
1302 if (cb->name == NULL) {
1303 ERROR("plugin_register_flush: strdup failed.");
1308 cb->timeout = ctx.flush_timeout;
1310 status = plugin_register_complex_read(
1311 /* group = */ "flush",
1312 /* name = */ flush_name,
1313 /* callback = */ plugin_flush_timeout_callback,
1314 /* interval = */ ctx.flush_interval,
1315 /* user data = */ &(user_data_t){
1316 .data = cb, .free_func = plugin_flush_timeout_callback_free,
1328 } /* int plugin_register_flush */
1330 int plugin_register_missing(const char *name, plugin_missing_cb callback,
1331 user_data_t const *ud) {
1332 return (create_register_callback(&list_missing, name, (void *)callback, ud));
1333 } /* int plugin_register_missing */
1335 int plugin_register_shutdown(const char *name, int (*callback)(void)) {
1336 return (create_register_callback(&list_shutdown, name, (void *)callback,
1337 /* user_data = */ NULL));
1338 } /* int plugin_register_shutdown */
1340 static void plugin_free_data_sets(void) {
1344 if (data_sets == NULL)
1347 while (c_avl_pick(data_sets, &key, &value) == 0) {
1348 data_set_t *ds = value;
1349 /* key is a pointer to ds->type */
1355 c_avl_destroy(data_sets);
1357 } /* void plugin_free_data_sets */
1359 int plugin_register_data_set(const data_set_t *ds) {
1360 data_set_t *ds_copy;
1362 if ((data_sets != NULL) && (c_avl_get(data_sets, ds->type, NULL) == 0)) {
1363 NOTICE("Replacing DS `%s' with another version.", ds->type);
1364 plugin_unregister_data_set(ds->type);
1365 } else if (data_sets == NULL) {
1366 data_sets = c_avl_create((int (*)(const void *, const void *))strcmp);
1367 if (data_sets == NULL)
1371 ds_copy = malloc(sizeof(*ds_copy));
1372 if (ds_copy == NULL)
1374 memcpy(ds_copy, ds, sizeof(data_set_t));
1376 ds_copy->ds = malloc(sizeof(*ds_copy->ds) * ds->ds_num);
1377 if (ds_copy->ds == NULL) {
1382 for (size_t i = 0; i < ds->ds_num; i++)
1383 memcpy(ds_copy->ds + i, ds->ds + i, sizeof(data_source_t));
1385 return (c_avl_insert(data_sets, (void *)ds_copy->type, (void *)ds_copy));
1386 } /* int plugin_register_data_set */
1388 int plugin_register_log(const char *name, plugin_log_cb callback,
1389 user_data_t const *ud) {
1390 return (create_register_callback(&list_log, name, (void *)callback, ud));
1391 } /* int plugin_register_log */
1393 int plugin_register_notification(const char *name,
1394 plugin_notification_cb callback,
1395 user_data_t const *ud) {
1397 create_register_callback(&list_notification, name, (void *)callback, ud));
1398 } /* int plugin_register_log */
1400 int plugin_unregister_config(const char *name) {
1401 cf_unregister(name);
1403 } /* int plugin_unregister_config */
1405 int plugin_unregister_complex_config(const char *name) {
1406 cf_unregister_complex(name);
1408 } /* int plugin_unregister_complex_config */
1410 int plugin_unregister_init(const char *name) {
1411 return (plugin_unregister(list_init, name));
1414 int plugin_unregister_read(const char *name) /* {{{ */
1422 pthread_mutex_lock(&read_lock);
1424 if (read_list == NULL) {
1425 pthread_mutex_unlock(&read_lock);
1429 le = llist_search(read_list, name);
1431 pthread_mutex_unlock(&read_lock);
1432 WARNING("plugin_unregister_read: No such read function: %s", name);
1436 llist_remove(read_list, le);
1440 rf->rf_type = RF_REMOVE;
1442 pthread_mutex_unlock(&read_lock);
1444 llentry_destroy(le);
1446 DEBUG("plugin_unregister_read: Marked `%s' for removal.", name);
1449 } /* }}} int plugin_unregister_read */
1451 void plugin_log_available_writers(void) {
1452 log_list_callbacks(&list_write, "Available write targets:");
1455 static int compare_read_func_group(llentry_t *e, void *ud) /* {{{ */
1457 read_func_t *rf = e->value;
1460 return strcmp(rf->rf_group, (const char *)group);
1461 } /* }}} int compare_read_func_group */
1463 int plugin_unregister_read_group(const char *group) /* {{{ */
1473 pthread_mutex_lock(&read_lock);
1475 if (read_list == NULL) {
1476 pthread_mutex_unlock(&read_lock);
1481 le = llist_search_custom(read_list, compare_read_func_group, (void *)group);
1488 llist_remove(read_list, le);
1492 rf->rf_type = RF_REMOVE;
1494 llentry_destroy(le);
1496 DEBUG("plugin_unregister_read_group: "
1497 "Marked `%s' (group `%s') for removal.",
1498 rf->rf_name, group);
1501 pthread_mutex_unlock(&read_lock);
1504 WARNING("plugin_unregister_read_group: No such "
1505 "group of read function: %s",
1511 } /* }}} int plugin_unregister_read_group */
1513 int plugin_unregister_write(const char *name) {
1514 return (plugin_unregister(list_write, name));
1517 int plugin_unregister_flush(const char *name) {
1518 plugin_ctx_t ctx = plugin_get_ctx();
1520 if (ctx.flush_interval != 0) {
1523 flush_name = plugin_flush_callback_name(name);
1524 if (flush_name != NULL) {
1525 plugin_unregister_read(flush_name);
1530 return plugin_unregister(list_flush, name);
1533 int plugin_unregister_missing(const char *name) {
1534 return (plugin_unregister(list_missing, name));
1537 int plugin_unregister_shutdown(const char *name) {
1538 return (plugin_unregister(list_shutdown, name));
1541 int plugin_unregister_data_set(const char *name) {
1544 if (data_sets == NULL)
1547 if (c_avl_remove(data_sets, name, NULL, (void *)&ds) != 0)
1554 } /* int plugin_unregister_data_set */
1556 int plugin_unregister_log(const char *name) {
1557 return (plugin_unregister(list_log, name));
1560 int plugin_unregister_notification(const char *name) {
1561 return (plugin_unregister(list_notification, name));
1564 int plugin_init_all(void) {
1565 char const *chain_name;
1570 /* Init the value cache */
1573 if (IS_TRUE(global_option_get("CollectInternalStats"))) {
1574 record_statistics = 1;
1575 plugin_register_read("collectd", plugin_update_internal_statistics);
1578 chain_name = global_option_get("PreCacheChain");
1579 pre_cache_chain = fc_chain_get_by_name(chain_name);
1581 chain_name = global_option_get("PostCacheChain");
1582 post_cache_chain = fc_chain_get_by_name(chain_name);
1584 write_limit_high = global_option_get_long("WriteQueueLimitHigh",
1586 if (write_limit_high < 0) {
1587 ERROR("WriteQueueLimitHigh must be positive or zero.");
1588 write_limit_high = 0;
1592 global_option_get_long("WriteQueueLimitLow",
1593 /* default = */ write_limit_high / 2);
1594 if (write_limit_low < 0) {
1595 ERROR("WriteQueueLimitLow must be positive or zero.");
1596 write_limit_low = write_limit_high / 2;
1597 } else if (write_limit_low > write_limit_high) {
1598 ERROR("WriteQueueLimitLow must not be larger than "
1599 "WriteQueueLimitHigh.");
1600 write_limit_low = write_limit_high;
1603 write_threads_num = global_option_get_long("WriteThreads",
1605 if (write_threads_num < 1) {
1606 ERROR("WriteThreads must be positive.");
1607 write_threads_num = 5;
1610 if ((list_init == NULL) && (read_heap == NULL))
1613 /* Calling all init callbacks before checking if read callbacks
1614 * are available allows the init callbacks to register the read
1616 le = llist_head(list_init);
1617 while (le != NULL) {
1618 callback_func_t *cf;
1619 plugin_init_cb callback;
1620 plugin_ctx_t old_ctx;
1623 old_ctx = plugin_set_ctx(cf->cf_ctx);
1624 callback = cf->cf_callback;
1625 status = (*callback)();
1626 plugin_set_ctx(old_ctx);
1629 ERROR("Initialization of plugin `%s' "
1630 "failed with status %i. "
1631 "Plugin will be unloaded.",
1633 /* Plugins that register read callbacks from the init
1634 * callback should take care of appropriate error
1635 * handling themselves. */
1636 /* FIXME: Unload _all_ functions */
1637 plugin_unregister_read(le->key);
1644 start_write_threads((size_t)write_threads_num);
1647 global_option_get_time("MaxReadInterval", DEFAULT_MAX_READ_INTERVAL);
1649 /* Start read-threads */
1650 if (read_heap != NULL) {
1654 rt = global_option_get("ReadThreads");
1657 start_read_threads((num > 0) ? ((size_t)num) : 5);
1660 } /* void plugin_init_all */
1662 /* TODO: Rename this function. */
1663 void plugin_read_all(void) {
1667 } /* void plugin_read_all */
1669 /* Read function called when the `-T' command line argument is given. */
1670 int plugin_read_all_once(void) {
1672 int return_status = 0;
1674 if (read_heap == NULL) {
1675 NOTICE("No read-functions are registered.");
1681 plugin_ctx_t old_ctx;
1683 rf = c_heap_get_root(read_heap);
1687 old_ctx = plugin_set_ctx(rf->rf_ctx);
1689 if (rf->rf_type == RF_SIMPLE) {
1690 int (*callback)(void);
1692 callback = rf->rf_callback;
1693 status = (*callback)();
1695 plugin_read_cb callback;
1697 callback = rf->rf_callback;
1698 status = (*callback)(&rf->rf_udata);
1701 plugin_set_ctx(old_ctx);
1704 NOTICE("read-function of plugin `%s' failed.", rf->rf_name);
1709 destroy_callback((void *)rf);
1712 return (return_status);
1713 } /* int plugin_read_all_once */
1715 int plugin_write(const char *plugin, /* {{{ */
1716 const data_set_t *ds, const value_list_t *vl) {
1723 if (list_write == NULL)
1727 ds = plugin_get_ds(vl->type);
1729 ERROR("plugin_write: Unable to lookup type `%s'.", vl->type);
1734 if (plugin == NULL) {
1738 le = llist_head(list_write);
1739 while (le != NULL) {
1740 callback_func_t *cf = le->value;
1741 plugin_write_cb callback;
1743 /* do not switch plugin context; rather keep the context (interval)
1744 * information of the calling read plugin */
1746 DEBUG("plugin: plugin_write: Writing values via %s.", le->key);
1747 callback = cf->cf_callback;
1748 status = (*callback)(ds, vl, &cf->cf_udata);
1757 if ((success == 0) && (failure != 0))
1761 } else /* plugin != NULL */
1763 callback_func_t *cf;
1764 plugin_write_cb callback;
1766 le = llist_head(list_write);
1767 while (le != NULL) {
1768 if (strcasecmp(plugin, le->key) == 0)
1779 /* do not switch plugin context; rather keep the context (interval)
1780 * information of the calling read plugin */
1782 DEBUG("plugin: plugin_write: Writing values via %s.", le->key);
1783 callback = cf->cf_callback;
1784 status = (*callback)(ds, vl, &cf->cf_udata);
1788 } /* }}} int plugin_write */
1790 int plugin_flush(const char *plugin, cdtime_t timeout, const char *identifier) {
1793 if (list_flush == NULL)
1796 le = llist_head(list_flush);
1797 while (le != NULL) {
1798 callback_func_t *cf;
1799 plugin_flush_cb callback;
1800 plugin_ctx_t old_ctx;
1802 if ((plugin != NULL) && (strcmp(plugin, le->key) != 0)) {
1808 old_ctx = plugin_set_ctx(cf->cf_ctx);
1809 callback = cf->cf_callback;
1811 (*callback)(timeout, identifier, &cf->cf_udata);
1813 plugin_set_ctx(old_ctx);
1818 } /* int plugin_flush */
1820 int plugin_shutdown_all(void) {
1822 int ret = 0; // Assume success.
1824 destroy_all_callbacks(&list_init);
1826 stop_read_threads();
1828 pthread_mutex_lock(&read_lock);
1829 llist_destroy(read_list);
1831 pthread_mutex_unlock(&read_lock);
1833 destroy_read_heap();
1835 /* blocks until all write threads have shut down. */
1836 stop_write_threads();
1838 /* ask all plugins to write out the state they kept. */
1839 plugin_flush(/* plugin = */ NULL,
1841 /* identifier = */ NULL);
1844 if (list_shutdown != NULL)
1845 le = llist_head(list_shutdown);
1847 while (le != NULL) {
1848 callback_func_t *cf;
1849 plugin_shutdown_cb callback;
1850 plugin_ctx_t old_ctx;
1853 old_ctx = plugin_set_ctx(cf->cf_ctx);
1854 callback = cf->cf_callback;
1856 /* Advance the pointer before calling the callback allows
1857 * shutdown functions to unregister themselves. If done the
1858 * other way around the memory `le' points to will be freed
1859 * after callback returns. */
1862 if ((*callback)() != 0)
1865 plugin_set_ctx(old_ctx);
1868 /* Write plugins which use the `user_data' pointer usually need the
1869 * same data available to the flush callback. If this is the case, set
1870 * the free_function to NULL when registering the flush callback and to
1871 * the real free function when registering the write callback. This way
1872 * the data isn't freed twice. */
1873 destroy_all_callbacks(&list_flush);
1874 destroy_all_callbacks(&list_missing);
1875 destroy_all_callbacks(&list_write);
1877 destroy_all_callbacks(&list_notification);
1878 destroy_all_callbacks(&list_shutdown);
1879 destroy_all_callbacks(&list_log);
1881 plugin_free_loaded();
1882 plugin_free_data_sets();
1884 } /* void plugin_shutdown_all */
1886 int plugin_dispatch_missing(const value_list_t *vl) /* {{{ */
1890 if (list_missing == NULL)
1893 le = llist_head(list_missing);
1894 while (le != NULL) {
1895 callback_func_t *cf;
1896 plugin_missing_cb callback;
1897 plugin_ctx_t old_ctx;
1901 old_ctx = plugin_set_ctx(cf->cf_ctx);
1902 callback = cf->cf_callback;
1904 status = (*callback)(vl, &cf->cf_udata);
1905 plugin_set_ctx(old_ctx);
1908 ERROR("plugin_dispatch_missing: Callback function \"%s\" "
1909 "failed with status %i.",
1920 } /* int }}} plugin_dispatch_missing */
1922 static int plugin_dispatch_values_internal(value_list_t *vl) {
1924 static c_complain_t no_write_complaint = C_COMPLAIN_INIT_STATIC;
1928 _Bool free_meta_data = 0;
1932 /* These fields are initialized by plugin_value_list_clone() if needed: */
1933 assert(vl->host[0] != 0);
1934 assert(vl->time != 0); /* The time is determined at _enqueue_ time. */
1935 assert(vl->interval != 0);
1937 if (vl->type[0] == 0 || vl->values == NULL || vl->values_len < 1) {
1938 ERROR("plugin_dispatch_values: Invalid value list "
1944 /* Free meta data only if the calling function didn't specify any. In
1945 * this case matches and targets may add some and the calling function
1946 * may not expect (and therefore free) that data. */
1947 if (vl->meta == NULL)
1950 if (list_write == NULL)
1951 c_complain_once(LOG_WARNING, &no_write_complaint,
1952 "plugin_dispatch_values: No write callback has been "
1953 "registered. Please load at least one output plugin, "
1954 "if you want the collected data to be stored.");
1956 if (data_sets == NULL) {
1957 ERROR("plugin_dispatch_values: No data sets registered. "
1958 "Could the types database be read? Check "
1959 "your `TypesDB' setting!");
1963 if (c_avl_get(data_sets, vl->type, (void *)&ds) != 0) {
1964 char ident[6 * DATA_MAX_NAME_LEN];
1966 FORMAT_VL(ident, sizeof(ident), vl);
1967 INFO("plugin_dispatch_values: Dataset not found: %s "
1968 "(from \"%s\"), check your types.db!",
1973 DEBUG("plugin_dispatch_values: time = %.3f; interval = %.3f; "
1975 "plugin = %s; plugin_instance = %s; "
1976 "type = %s; type_instance = %s;",
1977 CDTIME_T_TO_DOUBLE(vl->time), CDTIME_T_TO_DOUBLE(vl->interval),
1978 vl->host, vl->plugin, vl->plugin_instance, vl->type, vl->type_instance);
1981 assert(0 == strcmp(ds->type, vl->type));
1983 if (0 != strcmp(ds->type, vl->type))
1984 WARNING("plugin_dispatch_values: (ds->type = %s) != (vl->type = %s)",
1985 ds->type, vl->type);
1989 assert(ds->ds_num == vl->values_len);
1991 if (ds->ds_num != vl->values_len) {
1992 ERROR("plugin_dispatch_values: ds->type = %s: "
1993 "(ds->ds_num = %zu) != "
1994 "(vl->values_len = %zu)",
1995 ds->type, ds->ds_num, vl->values_len);
2000 escape_slashes(vl->host, sizeof(vl->host));
2001 escape_slashes(vl->plugin, sizeof(vl->plugin));
2002 escape_slashes(vl->plugin_instance, sizeof(vl->plugin_instance));
2003 escape_slashes(vl->type, sizeof(vl->type));
2004 escape_slashes(vl->type_instance, sizeof(vl->type_instance));
2006 if (pre_cache_chain != NULL) {
2007 status = fc_process_chain(ds, vl, pre_cache_chain);
2009 WARNING("plugin_dispatch_values: Running the "
2010 "pre-cache chain failed with "
2013 } else if (status == FC_TARGET_STOP)
2017 /* Update the value cache */
2020 if (post_cache_chain != NULL) {
2021 status = fc_process_chain(ds, vl, post_cache_chain);
2023 WARNING("plugin_dispatch_values: Running the "
2024 "post-cache chain failed with "
2029 fc_default_action(ds, vl);
2031 if ((free_meta_data != 0) && (vl->meta != NULL)) {
2032 meta_data_destroy(vl->meta);
2037 } /* int plugin_dispatch_values_internal */
2039 static double get_drop_probability(void) /* {{{ */
2045 pthread_mutex_lock(&write_lock);
2046 wql = write_queue_length;
2047 pthread_mutex_unlock(&write_lock);
2049 if (wql < write_limit_low)
2051 if (wql >= write_limit_high)
2054 pos = 1 + wql - write_limit_low;
2055 size = 1 + write_limit_high - write_limit_low;
2057 return (((double)pos) / ((double)size));
2058 } /* }}} double get_drop_probability */
2060 static _Bool check_drop_value(void) /* {{{ */
2062 static cdtime_t last_message_time = 0;
2063 static pthread_mutex_t last_message_lock = PTHREAD_MUTEX_INITIALIZER;
2069 if (write_limit_high == 0)
2072 p = get_drop_probability();
2076 status = pthread_mutex_trylock(&last_message_lock);
2081 if ((now - last_message_time) > TIME_T_TO_CDTIME_T(1)) {
2082 last_message_time = now;
2083 ERROR("plugin_dispatch_values: Low water mark "
2084 "reached. Dropping %.0f%% of metrics.",
2087 pthread_mutex_unlock(&last_message_lock);
2098 } /* }}} _Bool check_drop_value */
2100 int plugin_dispatch_values(value_list_t const *vl) {
2102 static pthread_mutex_t statistics_lock = PTHREAD_MUTEX_INITIALIZER;
2104 if (check_drop_value()) {
2105 if (record_statistics) {
2106 pthread_mutex_lock(&statistics_lock);
2107 stats_values_dropped++;
2108 pthread_mutex_unlock(&statistics_lock);
2113 status = plugin_write_enqueue(vl);
2116 ERROR("plugin_dispatch_values: plugin_write_enqueue failed "
2117 "with status %i (%s).",
2118 status, sstrerror(status, errbuf, sizeof(errbuf)));
2125 __attribute__((sentinel)) int
2126 plugin_dispatch_multivalue(value_list_t const *template, /* {{{ */
2127 _Bool store_percentage, int store_type, ...) {
2133 assert(template->values_len == 1);
2135 /* Calculate sum for Gauge to calculate percent if needed */
2136 if (DS_TYPE_GAUGE == store_type) {
2137 va_start(ap, store_type);
2142 name = va_arg(ap, char const *);
2146 value = va_arg(ap, gauge_t);
2153 vl = plugin_value_list_clone(template);
2154 /* plugin_value_list_clone makes sure vl->time is set to non-zero. */
2155 if (store_percentage)
2156 sstrncpy(vl->type, "percent", sizeof(vl->type));
2158 va_start(ap, store_type);
2163 /* Set the type instance. */
2164 name = va_arg(ap, char const *);
2167 sstrncpy(vl->type_instance, name, sizeof(vl->type_instance));
2169 /* Set the value. */
2170 switch (store_type) {
2172 vl->values[0].gauge = va_arg(ap, gauge_t);
2173 if (store_percentage)
2174 vl->values[0].gauge *= sum ? (100.0 / sum) : NAN;
2176 case DS_TYPE_ABSOLUTE:
2177 vl->values[0].absolute = va_arg(ap, absolute_t);
2179 case DS_TYPE_COUNTER:
2180 vl->values[0].counter = va_arg(ap, counter_t);
2182 case DS_TYPE_DERIVE:
2183 vl->values[0].derive = va_arg(ap, derive_t);
2186 ERROR("plugin_dispatch_multivalue: given store_type is incorrect.");
2190 status = plugin_write_enqueue(vl);
2196 plugin_value_list_free(vl);
2198 } /* }}} int plugin_dispatch_multivalue */
2200 int plugin_dispatch_notification(const notification_t *notif) {
2202 /* Possible TODO: Add flap detection here */
2204 DEBUG("plugin_dispatch_notification: severity = %i; message = %s; "
2205 "time = %.3f; host = %s;",
2206 notif->severity, notif->message, CDTIME_T_TO_DOUBLE(notif->time),
2209 /* Nobody cares for notifications */
2210 if (list_notification == NULL)
2213 le = llist_head(list_notification);
2214 while (le != NULL) {
2215 callback_func_t *cf;
2216 plugin_notification_cb callback;
2219 /* do not switch plugin context; rather keep the context
2220 * (interval) information of the calling plugin */
2223 callback = cf->cf_callback;
2224 status = (*callback)(notif, &cf->cf_udata);
2226 WARNING("plugin_dispatch_notification: Notification "
2227 "callback %s returned %i.",
2235 } /* int plugin_dispatch_notification */
2237 void plugin_log(int level, const char *format, ...) {
2243 if (level >= LOG_DEBUG)
2247 va_start(ap, format);
2248 vsnprintf(msg, sizeof(msg), format, ap);
2249 msg[sizeof(msg) - 1] = '\0';
2252 if (list_log == NULL) {
2253 fprintf(stderr, "%s\n", msg);
2257 le = llist_head(list_log);
2258 while (le != NULL) {
2259 callback_func_t *cf;
2260 plugin_log_cb callback;
2263 callback = cf->cf_callback;
2265 /* do not switch plugin context; rather keep the context
2266 * (interval) information of the calling plugin */
2268 (*callback)(level, msg, &cf->cf_udata);
2272 } /* void plugin_log */
2274 int parse_log_severity(const char *severity) {
2277 if ((0 == strcasecmp(severity, "emerg")) ||
2278 (0 == strcasecmp(severity, "alert")) ||
2279 (0 == strcasecmp(severity, "crit")) || (0 == strcasecmp(severity, "err")))
2280 log_level = LOG_ERR;
2281 else if (0 == strcasecmp(severity, "warning"))
2282 log_level = LOG_WARNING;
2283 else if (0 == strcasecmp(severity, "notice"))
2284 log_level = LOG_NOTICE;
2285 else if (0 == strcasecmp(severity, "info"))
2286 log_level = LOG_INFO;
2288 else if (0 == strcasecmp(severity, "debug"))
2289 log_level = LOG_DEBUG;
2290 #endif /* COLLECT_DEBUG */
2293 } /* int parse_log_severity */
2295 int parse_notif_severity(const char *severity) {
2296 int notif_severity = -1;
2298 if (strcasecmp(severity, "FAILURE") == 0)
2299 notif_severity = NOTIF_FAILURE;
2300 else if (strcmp(severity, "OKAY") == 0)
2301 notif_severity = NOTIF_OKAY;
2302 else if ((strcmp(severity, "WARNING") == 0) ||
2303 (strcmp(severity, "WARN") == 0))
2304 notif_severity = NOTIF_WARNING;
2306 return (notif_severity);
2307 } /* int parse_notif_severity */
2309 const data_set_t *plugin_get_ds(const char *name) {
2312 if (data_sets == NULL) {
2313 ERROR("plugin_get_ds: No data sets are defined yet.");
2317 if (c_avl_get(data_sets, name, (void *)&ds) != 0) {
2318 DEBUG("No such dataset registered: %s", name);
2323 } /* data_set_t *plugin_get_ds */
2325 static int plugin_notification_meta_add(notification_t *n, const char *name,
2326 enum notification_meta_type_e type,
2327 const void *value) {
2328 notification_meta_t *meta;
2329 notification_meta_t *tail;
2331 if ((n == NULL) || (name == NULL) || (value == NULL)) {
2332 ERROR("plugin_notification_meta_add: A pointer is NULL!");
2336 meta = calloc(1, sizeof(*meta));
2338 ERROR("plugin_notification_meta_add: calloc failed.");
2342 sstrncpy(meta->name, name, sizeof(meta->name));
2346 case NM_TYPE_STRING: {
2347 meta->nm_value.nm_string = strdup((const char *)value);
2348 if (meta->nm_value.nm_string == NULL) {
2349 ERROR("plugin_notification_meta_add: strdup failed.");
2355 case NM_TYPE_SIGNED_INT: {
2356 meta->nm_value.nm_signed_int = *((int64_t *)value);
2359 case NM_TYPE_UNSIGNED_INT: {
2360 meta->nm_value.nm_unsigned_int = *((uint64_t *)value);
2363 case NM_TYPE_DOUBLE: {
2364 meta->nm_value.nm_double = *((double *)value);
2367 case NM_TYPE_BOOLEAN: {
2368 meta->nm_value.nm_boolean = *((_Bool *)value);
2372 ERROR("plugin_notification_meta_add: Unknown type: %i", type);
2376 } /* switch (type) */
2380 while ((tail != NULL) && (tail->next != NULL))
2389 } /* int plugin_notification_meta_add */
2391 int plugin_notification_meta_add_string(notification_t *n, const char *name,
2392 const char *value) {
2393 return (plugin_notification_meta_add(n, name, NM_TYPE_STRING, value));
2396 int plugin_notification_meta_add_signed_int(notification_t *n, const char *name,
2398 return (plugin_notification_meta_add(n, name, NM_TYPE_SIGNED_INT, &value));
2401 int plugin_notification_meta_add_unsigned_int(notification_t *n,
2404 return (plugin_notification_meta_add(n, name, NM_TYPE_UNSIGNED_INT, &value));
2407 int plugin_notification_meta_add_double(notification_t *n, const char *name,
2409 return (plugin_notification_meta_add(n, name, NM_TYPE_DOUBLE, &value));
2412 int plugin_notification_meta_add_boolean(notification_t *n, const char *name,
2414 return (plugin_notification_meta_add(n, name, NM_TYPE_BOOLEAN, &value));
2417 int plugin_notification_meta_copy(notification_t *dst,
2418 const notification_t *src) {
2419 assert(dst != NULL);
2420 assert(src != NULL);
2422 assert((src->meta == NULL) || (src->meta != dst->meta));
2424 for (notification_meta_t *meta = src->meta; meta != NULL; meta = meta->next) {
2425 if (meta->type == NM_TYPE_STRING)
2426 plugin_notification_meta_add_string(dst, meta->name,
2427 meta->nm_value.nm_string);
2428 else if (meta->type == NM_TYPE_SIGNED_INT)
2429 plugin_notification_meta_add_signed_int(dst, meta->name,
2430 meta->nm_value.nm_signed_int);
2431 else if (meta->type == NM_TYPE_UNSIGNED_INT)
2432 plugin_notification_meta_add_unsigned_int(dst, meta->name,
2433 meta->nm_value.nm_unsigned_int);
2434 else if (meta->type == NM_TYPE_DOUBLE)
2435 plugin_notification_meta_add_double(dst, meta->name,
2436 meta->nm_value.nm_double);
2437 else if (meta->type == NM_TYPE_BOOLEAN)
2438 plugin_notification_meta_add_boolean(dst, meta->name,
2439 meta->nm_value.nm_boolean);
2443 } /* int plugin_notification_meta_copy */
2445 int plugin_notification_meta_free(notification_meta_t *n) {
2446 notification_meta_t *this;
2447 notification_meta_t *next;
2450 ERROR("plugin_notification_meta_free: n == NULL!");
2455 while (this != NULL) {
2458 if (this->type == NM_TYPE_STRING) {
2459 /* Assign to a temporary variable to work around nm_string's const
2461 void *tmp = (void *)this->nm_value.nm_string;
2464 this->nm_value.nm_string = NULL;
2472 } /* int plugin_notification_meta_free */
2474 static void plugin_ctx_destructor(void *ctx) {
2476 } /* void plugin_ctx_destructor */
2478 static plugin_ctx_t ctx_init = {/* interval = */ 0};
2480 static plugin_ctx_t *plugin_ctx_create(void) {
2483 ctx = malloc(sizeof(*ctx));
2486 ERROR("Failed to allocate plugin context: %s",
2487 sstrerror(errno, errbuf, sizeof(errbuf)));
2492 assert(plugin_ctx_key_initialized);
2493 pthread_setspecific(plugin_ctx_key, ctx);
2494 DEBUG("Created new plugin context.");
2496 } /* int plugin_ctx_create */
2498 void plugin_init_ctx(void) {
2499 pthread_key_create(&plugin_ctx_key, plugin_ctx_destructor);
2500 plugin_ctx_key_initialized = 1;
2501 } /* void plugin_init_ctx */
2503 plugin_ctx_t plugin_get_ctx(void) {
2506 assert(plugin_ctx_key_initialized);
2507 ctx = pthread_getspecific(plugin_ctx_key);
2510 ctx = plugin_ctx_create();
2511 /* this must no happen -- exit() instead? */
2517 } /* plugin_ctx_t plugin_get_ctx */
2519 plugin_ctx_t plugin_set_ctx(plugin_ctx_t ctx) {
2523 assert(plugin_ctx_key_initialized);
2524 c = pthread_getspecific(plugin_ctx_key);
2527 c = plugin_ctx_create();
2528 /* this must no happen -- exit() instead? */
2537 } /* void plugin_set_ctx */
2539 cdtime_t plugin_get_interval(void) {
2542 interval = plugin_get_ctx().interval;
2546 return cf_get_default_interval();
2547 } /* cdtime_t plugin_get_interval */
2551 void *(*start_routine)(void *);
2555 static void *plugin_thread_start(void *arg) {
2556 plugin_thread_t *plugin_thread = arg;
2558 void *(*start_routine)(void *) = plugin_thread->start_routine;
2559 void *plugin_arg = plugin_thread->arg;
2561 plugin_set_ctx(plugin_thread->ctx);
2563 sfree(plugin_thread);
2565 return start_routine(plugin_arg);
2566 } /* void *plugin_thread_start */
2568 int plugin_thread_create(pthread_t *thread, const pthread_attr_t *attr,
2569 void *(*start_routine)(void *), void *arg,
2571 plugin_thread_t *plugin_thread;
2573 plugin_thread = malloc(sizeof(*plugin_thread));
2574 if (plugin_thread == NULL)
2577 plugin_thread->ctx = plugin_get_ctx();
2578 plugin_thread->start_routine = start_routine;
2579 plugin_thread->arg = arg;
2581 int ret = pthread_create(thread, attr, plugin_thread_start, plugin_thread);
2583 sfree(plugin_thread);
2588 set_thread_name(*thread, name);
2591 } /* int plugin_thread_create */
2593 /* vim: set sw=8 ts=8 noet fdm=marker : */