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));
162 vl.interval = plugin_get_interval();
165 sstrncpy(vl.plugin_instance, "write_queue", sizeof(vl.plugin_instance));
167 /* Write queue : queue length */
168 vl.values = &(value_t){.gauge = copy_write_queue_length};
170 sstrncpy(vl.type, "queue_length", sizeof(vl.type));
171 vl.type_instance[0] = 0;
172 plugin_dispatch_values(&vl);
174 /* Write queue : Values dropped (queue length > low limit) */
175 vl.values = &(value_t){.gauge = (gauge_t)stats_values_dropped};
177 sstrncpy(vl.type, "derive", sizeof(vl.type));
178 sstrncpy(vl.type_instance, "dropped", sizeof(vl.type_instance));
179 plugin_dispatch_values(&vl);
182 sstrncpy(vl.plugin_instance, "cache", sizeof(vl.plugin_instance));
184 /* Cache : Nb entry in cache tree */
185 vl.values = &(value_t){.gauge = (gauge_t)uc_get_size()};
187 sstrncpy(vl.type, "cache_size", sizeof(vl.type));
188 vl.type_instance[0] = 0;
189 plugin_dispatch_values(&vl);
192 } /* }}} int plugin_update_internal_statistics */
194 static void destroy_callback(callback_func_t *cf) /* {{{ */
199 if ((cf->cf_udata.data != NULL) && (cf->cf_udata.free_func != NULL)) {
200 cf->cf_udata.free_func(cf->cf_udata.data);
201 cf->cf_udata.data = NULL;
202 cf->cf_udata.free_func = NULL;
205 } /* }}} void destroy_callback */
207 static void destroy_all_callbacks(llist_t **list) /* {{{ */
214 le = llist_head(*list);
221 destroy_callback(le->value);
227 llist_destroy(*list);
229 } /* }}} void destroy_all_callbacks */
231 static void destroy_read_heap(void) /* {{{ */
233 if (read_heap == NULL)
239 rf = c_heap_get_root(read_heap);
243 destroy_callback((callback_func_t *)rf);
246 c_heap_destroy(read_heap);
248 } /* }}} void destroy_read_heap */
250 static int register_callback(llist_t **list, /* {{{ */
251 const char *name, callback_func_t *cf) {
256 *list = llist_create();
258 ERROR("plugin: register_callback: "
259 "llist_create failed.");
260 destroy_callback(cf);
267 ERROR("plugin: register_callback: strdup failed.");
268 destroy_callback(cf);
272 le = llist_search(*list, name);
274 le = llentry_create(key, cf);
276 ERROR("plugin: register_callback: "
277 "llentry_create failed.");
279 destroy_callback(cf);
283 llist_append(*list, le);
285 callback_func_t *old_cf;
290 WARNING("plugin: register_callback: "
291 "a callback named `%s' already exists - "
292 "overwriting the old entry!",
295 destroy_callback(old_cf);
300 } /* }}} int register_callback */
302 static void log_list_callbacks(llist_t **list, /* {{{ */
303 const char *comment) {
311 n = llist_size(*list);
313 INFO("%s [none]", comment);
317 keys = calloc(n, sizeof(char *));
320 ERROR("%s: failed to allocate memory for list of callbacks", comment);
325 for (le = llist_head(*list), i = 0, len = 0; le != NULL; le = le->next, i++) {
327 len += strlen(le->key) + 6;
329 str = malloc(len + 10);
331 ERROR("%s: failed to allocate memory for list of callbacks", comment);
334 strjoin(str, len, keys, n, "', '");
335 INFO("%s ['%s']", comment, str);
339 } /* }}} void log_list_callbacks */
341 static int create_register_callback(llist_t **list, /* {{{ */
342 const char *name, void *callback,
343 user_data_t const *ud) {
346 cf = calloc(1, sizeof(*cf));
348 ERROR("plugin: create_register_callback: calloc failed.");
352 cf->cf_callback = callback;
354 cf->cf_udata.data = NULL;
355 cf->cf_udata.free_func = NULL;
360 cf->cf_ctx = plugin_get_ctx();
362 return register_callback(list, name, cf);
363 } /* }}} int create_register_callback */
365 static int plugin_unregister(llist_t *list, const char *name) /* {{{ */
372 e = llist_search(list, name);
376 llist_remove(list, e);
379 destroy_callback(e->value);
384 } /* }}} int plugin_unregister */
387 * (Try to) load the shared object `file'. Won't complain if it isn't a shared
388 * object, but it will bitch about a shared object not having a
389 * ``module_register'' symbol..
391 static int plugin_load_file(const char *file, _Bool global) {
392 void (*reg_handle)(void);
394 int flags = RTLD_NOW;
396 flags |= RTLD_GLOBAL;
398 void *dlh = dlopen(file, flags);
401 char errbuf[1024] = "";
403 snprintf(errbuf, sizeof(errbuf),
404 "dlopen (\"%s\") failed: %s. "
405 "The most common cause for this problem is "
406 "missing dependencies. Use ldd(1) to check "
407 "the dependencies of the plugin "
412 /* Make sure this is printed to STDERR in any case, but also
413 * make sure it's printed only once. */
414 if (list_log != NULL)
415 fprintf(stderr, "ERROR: %s\n", errbuf);
420 reg_handle = (void (*)(void))dlsym(dlh, "module_register");
421 if (reg_handle == NULL) {
422 WARNING("Couldn't find symbol \"module_register\" in \"%s\": %s\n", file,
433 static void *plugin_read_thread(void __attribute__((unused)) * args) {
434 while (read_loop != 0) {
436 plugin_ctx_t old_ctx;
444 /* Get the read function that needs to be read next.
445 * We don't need to hold "read_lock" for the heap, but we need
446 * to call c_heap_get_root() and pthread_cond_wait() in the
447 * same protected block. */
448 pthread_mutex_lock(&read_lock);
449 rf = c_heap_get_root(read_heap);
451 pthread_cond_wait(&read_cond, &read_lock);
452 pthread_mutex_unlock(&read_lock);
455 pthread_mutex_unlock(&read_lock);
457 if (rf->rf_interval == 0) {
458 /* this should not happen, because the interval is set
459 * for each plugin when loading it
460 * XXX: issue a warning? */
461 rf->rf_interval = plugin_get_interval();
462 rf->rf_effective_interval = rf->rf_interval;
464 rf->rf_next_read = cdtime();
467 /* sleep until this entry is due,
468 * using pthread_cond_timedwait */
469 pthread_mutex_lock(&read_lock);
470 /* In pthread_cond_timedwait, spurious wakeups are possible
471 * (and really happen, at least on NetBSD with > 1 CPU), thus
472 * we need to re-evaluate the condition every time
473 * pthread_cond_timedwait returns. */
475 while ((read_loop != 0) && (cdtime() < rf->rf_next_read) && rc == 0) {
476 rc = pthread_cond_timedwait(&read_cond, &read_lock,
477 &CDTIME_T_TO_TIMESPEC(rf->rf_next_read));
480 /* Must hold `read_lock' when accessing `rf->rf_type'. */
481 rf_type = rf->rf_type;
482 pthread_mutex_unlock(&read_lock);
484 /* Check if we're supposed to stop.. This may have interrupted
486 if (read_loop == 0) {
487 /* Insert `rf' again, so it can be free'd correctly */
488 c_heap_insert(read_heap, rf);
492 /* The entry has been marked for deletion. The linked list
493 * entry has already been removed by `plugin_unregister_read'.
494 * All we have to do here is free the `read_func_t' and
496 if (rf_type == RF_REMOVE) {
497 DEBUG("plugin_read_thread: Destroying the `%s' "
501 destroy_callback((callback_func_t *)rf);
506 DEBUG("plugin_read_thread: Handling `%s'.", rf->rf_name);
510 old_ctx = plugin_set_ctx(rf->rf_ctx);
512 if (rf_type == RF_SIMPLE) {
513 int (*callback)(void);
515 callback = rf->rf_callback;
516 status = (*callback)();
518 plugin_read_cb callback;
520 assert(rf_type == RF_COMPLEX);
522 callback = rf->rf_callback;
523 status = (*callback)(&rf->rf_udata);
526 plugin_set_ctx(old_ctx);
528 /* If the function signals failure, we will increase the
529 * intervals in which it will be called. */
531 rf->rf_effective_interval *= 2;
532 if (rf->rf_effective_interval > max_read_interval)
533 rf->rf_effective_interval = max_read_interval;
535 NOTICE("read-function of plugin `%s' failed. "
536 "Will suspend it for %.3f seconds.",
537 rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
539 /* Success: Restore the interval, if it was changed. */
540 rf->rf_effective_interval = rf->rf_interval;
543 /* update the ``next read due'' field */
546 /* calculate the time spent in the read function */
547 elapsed = (now - start);
549 if (elapsed > rf->rf_effective_interval)
551 "plugin_read_thread: read-function of the `%s' plugin took %.3f "
552 "seconds, which is above its read interval (%.3f seconds). You might "
553 "want to adjust the `Interval' or `ReadThreads' settings.",
554 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed),
555 CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
557 DEBUG("plugin_read_thread: read-function of the `%s' plugin took "
559 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed));
561 DEBUG("plugin_read_thread: Effective interval of the "
562 "`%s' plugin is %.3f seconds.",
563 rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
565 /* Calculate the next (absolute) time at which this function
566 * should be called. */
567 rf->rf_next_read += rf->rf_effective_interval;
569 /* Check, if `rf_next_read' is in the past. */
570 if (rf->rf_next_read < now) {
571 /* `rf_next_read' is in the past. Insert `now'
572 * so this value doesn't trail off into the
574 rf->rf_next_read = now;
577 DEBUG("plugin_read_thread: Next read of the `%s' plugin at %.3f.",
578 rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_next_read));
580 /* Re-insert this read function into the heap again. */
581 c_heap_insert(read_heap, rf);
582 } /* while (read_loop) */
586 } /* void *plugin_read_thread */
588 #ifdef PTHREAD_MAX_NAMELEN_NP
589 #define THREAD_NAME_MAX PTHREAD_MAX_NAMELEN_NP
591 #define THREAD_NAME_MAX 16
594 static void set_thread_name(pthread_t tid, char const *name) {
595 #if defined(HAVE_PTHREAD_SETNAME_NP) || defined(HAVE_PTHREAD_SET_NAME_NP)
597 /* glibc limits the length of the name and fails if the passed string
598 * is too long, so we truncate it here. */
599 char n[THREAD_NAME_MAX];
600 if (strlen(name) >= THREAD_NAME_MAX)
601 WARNING("set_thread_name(\"%s\"): name too long", name);
602 sstrncpy(n, name, sizeof(n));
604 #if defined(HAVE_PTHREAD_SETNAME_NP)
605 int status = pthread_setname_np(tid, n);
608 ERROR("set_thread_name(\"%s\"): %s", n,
609 sstrerror(status, errbuf, sizeof(errbuf)));
611 #else /* if defined(HAVE_PTHREAD_SET_NAME_NP) */
612 pthread_set_name_np(tid, n);
618 static void start_read_threads(size_t num) /* {{{ */
620 if (read_threads != NULL)
623 read_threads = (pthread_t *)calloc(num, sizeof(pthread_t));
624 if (read_threads == NULL) {
625 ERROR("plugin: start_read_threads: calloc failed.");
629 read_threads_num = 0;
630 for (size_t i = 0; i < num; i++) {
631 int status = pthread_create(read_threads + read_threads_num,
632 /* attr = */ NULL, plugin_read_thread,
636 ERROR("plugin: start_read_threads: pthread_create failed "
637 "with status %i (%s).",
638 status, sstrerror(status, errbuf, sizeof(errbuf)));
642 char name[THREAD_NAME_MAX];
643 snprintf(name, sizeof(name), "reader#%zu", read_threads_num);
644 set_thread_name(read_threads[read_threads_num], name);
648 } /* }}} void start_read_threads */
650 static void stop_read_threads(void) {
651 if (read_threads == NULL)
654 INFO("collectd: Stopping %zu read threads.", read_threads_num);
656 pthread_mutex_lock(&read_lock);
658 DEBUG("plugin: stop_read_threads: Signalling `read_cond'");
659 pthread_cond_broadcast(&read_cond);
660 pthread_mutex_unlock(&read_lock);
662 for (size_t i = 0; i < read_threads_num; i++) {
663 if (pthread_join(read_threads[i], NULL) != 0) {
664 ERROR("plugin: stop_read_threads: pthread_join failed.");
666 read_threads[i] = (pthread_t)0;
669 read_threads_num = 0;
670 } /* void stop_read_threads */
672 static void plugin_value_list_free(value_list_t *vl) /* {{{ */
677 meta_data_destroy(vl->meta);
680 } /* }}} void plugin_value_list_free */
682 static value_list_t *
683 plugin_value_list_clone(value_list_t const *vl_orig) /* {{{ */
690 vl = malloc(sizeof(*vl));
693 memcpy(vl, vl_orig, sizeof(*vl));
695 if (vl->host[0] == 0)
696 sstrncpy(vl->host, hostname_g, sizeof(vl->host));
698 vl->values = calloc(vl_orig->values_len, sizeof(*vl->values));
699 if (vl->values == NULL) {
700 plugin_value_list_free(vl);
703 memcpy(vl->values, vl_orig->values,
704 vl_orig->values_len * sizeof(*vl->values));
706 vl->meta = meta_data_clone(vl->meta);
707 if ((vl_orig->meta != NULL) && (vl->meta == NULL)) {
708 plugin_value_list_free(vl);
715 /* Fill in the interval from the thread context, if it is zero. */
716 if (vl->interval == 0) {
717 plugin_ctx_t ctx = plugin_get_ctx();
719 if (ctx.interval != 0)
720 vl->interval = ctx.interval;
722 char name[6 * DATA_MAX_NAME_LEN];
723 FORMAT_VL(name, sizeof(name), vl);
724 ERROR("plugin_value_list_clone: Unable to determine "
725 "interval from context for "
726 "value list \"%s\". "
727 "This indicates a broken plugin. "
728 "Please report this problem to the "
729 "collectd mailing list or at "
730 "<http://collectd.org/bugs/>.",
732 vl->interval = cf_get_default_interval();
737 } /* }}} value_list_t *plugin_value_list_clone */
739 static int plugin_write_enqueue(value_list_t const *vl) /* {{{ */
743 q = malloc(sizeof(*q));
748 q->vl = plugin_value_list_clone(vl);
754 /* Store context of caller (read plugin); otherwise, it would not be
755 * available to the write plugins when actually dispatching the
756 * value-list later on. */
757 q->ctx = plugin_get_ctx();
759 pthread_mutex_lock(&write_lock);
761 if (write_queue_tail == NULL) {
762 write_queue_head = q;
763 write_queue_tail = q;
764 write_queue_length = 1;
766 write_queue_tail->next = q;
767 write_queue_tail = q;
768 write_queue_length += 1;
771 pthread_cond_signal(&write_cond);
772 pthread_mutex_unlock(&write_lock);
775 } /* }}} int plugin_write_enqueue */
777 static value_list_t *plugin_write_dequeue(void) /* {{{ */
782 pthread_mutex_lock(&write_lock);
784 while (write_loop && (write_queue_head == NULL))
785 pthread_cond_wait(&write_cond, &write_lock);
787 if (write_queue_head == NULL) {
788 pthread_mutex_unlock(&write_lock);
792 q = write_queue_head;
793 write_queue_head = q->next;
794 write_queue_length -= 1;
795 if (write_queue_head == NULL) {
796 write_queue_tail = NULL;
797 assert(0 == write_queue_length);
800 pthread_mutex_unlock(&write_lock);
802 (void)plugin_set_ctx(q->ctx);
807 } /* }}} value_list_t *plugin_write_dequeue */
809 static void *plugin_write_thread(void __attribute__((unused)) * args) /* {{{ */
812 value_list_t *vl = plugin_write_dequeue();
816 plugin_dispatch_values_internal(vl);
818 plugin_value_list_free(vl);
823 } /* }}} void *plugin_write_thread */
825 static void start_write_threads(size_t num) /* {{{ */
827 if (write_threads != NULL)
830 write_threads = (pthread_t *)calloc(num, sizeof(pthread_t));
831 if (write_threads == NULL) {
832 ERROR("plugin: start_write_threads: calloc failed.");
836 write_threads_num = 0;
837 for (size_t i = 0; i < num; i++) {
838 int status = pthread_create(write_threads + write_threads_num,
839 /* attr = */ NULL, plugin_write_thread,
843 ERROR("plugin: start_write_threads: pthread_create failed "
844 "with status %i (%s).",
845 status, sstrerror(status, errbuf, sizeof(errbuf)));
849 char name[THREAD_NAME_MAX];
850 snprintf(name, sizeof(name), "writer#%zu", write_threads_num);
851 set_thread_name(write_threads[write_threads_num], name);
855 } /* }}} void start_write_threads */
857 static void stop_write_threads(void) /* {{{ */
862 if (write_threads == NULL)
865 INFO("collectd: Stopping %zu write threads.", write_threads_num);
867 pthread_mutex_lock(&write_lock);
869 DEBUG("plugin: stop_write_threads: Signalling `write_cond'");
870 pthread_cond_broadcast(&write_cond);
871 pthread_mutex_unlock(&write_lock);
873 for (i = 0; i < write_threads_num; i++) {
874 if (pthread_join(write_threads[i], NULL) != 0) {
875 ERROR("plugin: stop_write_threads: pthread_join failed.");
877 write_threads[i] = (pthread_t)0;
879 sfree(write_threads);
880 write_threads_num = 0;
882 pthread_mutex_lock(&write_lock);
884 for (q = write_queue_head; q != NULL;) {
885 write_queue_t *q1 = q;
886 plugin_value_list_free(q->vl);
891 write_queue_head = NULL;
892 write_queue_tail = NULL;
893 write_queue_length = 0;
894 pthread_mutex_unlock(&write_lock);
897 WARNING("plugin: %zu value list%s left after shutting down "
898 "the write threads.",
899 i, (i == 1) ? " was" : "s were");
901 } /* }}} void stop_write_threads */
906 void plugin_set_dir(const char *dir) {
914 plugindir = strdup(dir);
915 if (plugindir == NULL)
916 ERROR("plugin_set_dir: strdup(\"%s\") failed", dir);
919 static _Bool plugin_is_loaded(char const *name) {
922 if (plugins_loaded == NULL)
924 c_avl_create((int (*)(const void *, const void *))strcasecmp);
925 assert(plugins_loaded != NULL);
927 status = c_avl_get(plugins_loaded, name, /* ret_value = */ NULL);
931 static int plugin_mark_loaded(char const *name) {
935 name_copy = strdup(name);
936 if (name_copy == NULL)
939 status = c_avl_insert(plugins_loaded,
940 /* key = */ name_copy, /* value = */ NULL);
944 static void plugin_free_loaded(void) {
948 if (plugins_loaded == NULL)
951 while (c_avl_pick(plugins_loaded, &key, &value) == 0) {
953 assert(value == NULL);
956 c_avl_destroy(plugins_loaded);
957 plugins_loaded = NULL;
961 int plugin_load(char const *plugin_name, _Bool global) {
964 char filename[BUFSIZE] = "";
965 char typename[BUFSIZE];
971 if (plugin_name == NULL)
974 /* Check if plugin is already loaded and don't do anything in this
976 if (plugin_is_loaded(plugin_name))
979 dir = plugin_get_dir();
983 * XXX: Magic at work:
985 * Some of the language bindings, for example the Python and Perl
986 * plugins, need to be able to export symbols to the scripts they run.
987 * For this to happen, the "Globals" flag needs to be set.
988 * Unfortunately, this technical detail is hard to explain to the
989 * average user and she shouldn't have to worry about this, ideally.
990 * So in order to save everyone's sanity use a different default for a
991 * handful of special plugins. --octo
993 if ((strcasecmp("perl", plugin_name) == 0) ||
994 (strcasecmp("python", plugin_name) == 0))
997 /* `cpu' should not match `cpufreq'. To solve this we add `.so' to the
998 * type when matching the filename */
999 status = snprintf(typename, sizeof(typename), "%s.so", plugin_name);
1000 if ((status < 0) || ((size_t)status >= sizeof(typename))) {
1001 WARNING("plugin_load: Filename too long: \"%s.so\"", plugin_name);
1005 if ((dh = opendir(dir)) == NULL) {
1007 ERROR("plugin_load: opendir (%s) failed: %s", dir,
1008 sstrerror(errno, errbuf, sizeof(errbuf)));
1012 while ((de = readdir(dh)) != NULL) {
1013 if (strcasecmp(de->d_name, typename))
1016 status = snprintf(filename, sizeof(filename), "%s/%s", dir, de->d_name);
1017 if ((status < 0) || ((size_t)status >= sizeof(filename))) {
1018 WARNING("plugin_load: Filename too long: \"%s/%s\"", dir, de->d_name);
1022 if (lstat(filename, &statbuf) == -1) {
1024 WARNING("plugin_load: stat (\"%s\") failed: %s", filename,
1025 sstrerror(errno, errbuf, sizeof(errbuf)));
1027 } else if (!S_ISREG(statbuf.st_mode)) {
1028 /* don't follow symlinks */
1029 WARNING("plugin_load: %s is not a regular file.", filename);
1033 status = plugin_load_file(filename, global);
1036 plugin_mark_loaded(plugin_name);
1038 INFO("plugin_load: plugin \"%s\" successfully loaded.", plugin_name);
1041 ERROR("plugin_load: Load plugin \"%s\" failed with "
1043 plugin_name, status);
1049 if (filename[0] == 0)
1050 ERROR("plugin_load: Could not find plugin \"%s\" in %s", plugin_name, dir);
1056 * The `register_*' functions follow
1058 int plugin_register_config(const char *name,
1059 int (*callback)(const char *key, const char *val),
1060 const char **keys, int keys_num) {
1061 cf_register(name, callback, keys, keys_num);
1063 } /* int plugin_register_config */
1065 int plugin_register_complex_config(const char *type,
1066 int (*callback)(oconfig_item_t *)) {
1067 return cf_register_complex(type, callback);
1068 } /* int plugin_register_complex_config */
1070 int plugin_register_init(const char *name, int (*callback)(void)) {
1071 return create_register_callback(&list_init, name, (void *)callback, NULL);
1072 } /* plugin_register_init */
1074 static int plugin_compare_read_func(const void *arg0, const void *arg1) {
1075 const read_func_t *rf0;
1076 const read_func_t *rf1;
1081 if (rf0->rf_next_read < rf1->rf_next_read)
1083 else if (rf0->rf_next_read > rf1->rf_next_read)
1087 } /* int plugin_compare_read_func */
1089 /* Add a read function to both, the heap and a linked list. The linked list if
1090 * used to look-up read functions, especially for the remove function. The heap
1091 * is used to determine which plugin to read next. */
1092 static int plugin_insert_read(read_func_t *rf) {
1096 rf->rf_next_read = cdtime();
1097 rf->rf_effective_interval = rf->rf_interval;
1099 pthread_mutex_lock(&read_lock);
1101 if (read_list == NULL) {
1102 read_list = llist_create();
1103 if (read_list == NULL) {
1104 pthread_mutex_unlock(&read_lock);
1105 ERROR("plugin_insert_read: read_list failed.");
1110 if (read_heap == NULL) {
1111 read_heap = c_heap_create(plugin_compare_read_func);
1112 if (read_heap == NULL) {
1113 pthread_mutex_unlock(&read_lock);
1114 ERROR("plugin_insert_read: c_heap_create failed.");
1119 le = llist_search(read_list, rf->rf_name);
1121 pthread_mutex_unlock(&read_lock);
1122 WARNING("The read function \"%s\" is already registered. "
1123 "Check for duplicate \"LoadPlugin\" lines "
1124 "in your configuration!",
1129 le = llentry_create(rf->rf_name, rf);
1131 pthread_mutex_unlock(&read_lock);
1132 ERROR("plugin_insert_read: llentry_create failed.");
1136 status = c_heap_insert(read_heap, rf);
1138 pthread_mutex_unlock(&read_lock);
1139 ERROR("plugin_insert_read: c_heap_insert failed.");
1140 llentry_destroy(le);
1144 /* This does not fail. */
1145 llist_append(read_list, le);
1147 /* Wake up all the read threads. */
1148 pthread_cond_broadcast(&read_cond);
1149 pthread_mutex_unlock(&read_lock);
1151 } /* int plugin_insert_read */
1153 int plugin_register_read(const char *name, int (*callback)(void)) {
1157 rf = calloc(1, sizeof(*rf));
1159 ERROR("plugin_register_read: calloc failed.");
1163 rf->rf_callback = (void *)callback;
1164 rf->rf_udata.data = NULL;
1165 rf->rf_udata.free_func = NULL;
1166 rf->rf_ctx = plugin_get_ctx();
1167 rf->rf_group[0] = '\0';
1168 rf->rf_name = strdup(name);
1169 rf->rf_type = RF_SIMPLE;
1170 rf->rf_interval = plugin_get_interval();
1172 status = plugin_insert_read(rf);
1179 } /* int plugin_register_read */
1181 int plugin_register_complex_read(const char *group, const char *name,
1182 plugin_read_cb callback, cdtime_t interval,
1183 user_data_t const *user_data) {
1187 rf = calloc(1, sizeof(*rf));
1189 ERROR("plugin_register_complex_read: calloc failed.");
1193 rf->rf_callback = (void *)callback;
1195 sstrncpy(rf->rf_group, group, sizeof(rf->rf_group));
1197 rf->rf_group[0] = '\0';
1198 rf->rf_name = strdup(name);
1199 rf->rf_type = RF_COMPLEX;
1200 rf->rf_interval = (interval != 0) ? interval : plugin_get_interval();
1203 if (user_data == NULL) {
1204 rf->rf_udata.data = NULL;
1205 rf->rf_udata.free_func = NULL;
1207 rf->rf_udata = *user_data;
1210 rf->rf_ctx = plugin_get_ctx();
1212 status = plugin_insert_read(rf);
1219 } /* int plugin_register_complex_read */
1221 int plugin_register_write(const char *name, plugin_write_cb callback,
1222 user_data_t const *ud) {
1223 return create_register_callback(&list_write, name, (void *)callback, ud);
1224 } /* int plugin_register_write */
1226 static int plugin_flush_timeout_callback(user_data_t *ud) {
1227 flush_callback_t *cb = ud->data;
1229 return plugin_flush(cb->name, cb->timeout, NULL);
1230 } /* static int plugin_flush_callback */
1232 static void plugin_flush_timeout_callback_free(void *data) {
1233 flush_callback_t *cb = data;
1240 } /* static void plugin_flush_callback_free */
1242 static char *plugin_flush_callback_name(const char *name) {
1243 const char *flush_prefix = "flush/";
1248 prefix_size = strlen(flush_prefix);
1249 name_size = strlen(name);
1251 flush_name = malloc(name_size + prefix_size + 1);
1252 if (flush_name == NULL) {
1253 ERROR("plugin_flush_callback_name: malloc failed.");
1257 sstrncpy(flush_name, flush_prefix, prefix_size + 1);
1258 sstrncpy(flush_name + prefix_size, name, name_size + 1);
1261 } /* static char *plugin_flush_callback_name */
1263 int plugin_register_flush(const char *name, plugin_flush_cb callback,
1264 user_data_t const *ud) {
1266 plugin_ctx_t ctx = plugin_get_ctx();
1268 status = create_register_callback(&list_flush, name, (void *)callback, ud);
1272 if (ctx.flush_interval != 0) {
1274 flush_callback_t *cb;
1276 flush_name = plugin_flush_callback_name(name);
1277 if (flush_name == NULL)
1280 cb = malloc(sizeof(*cb));
1282 ERROR("plugin_register_flush: malloc failed.");
1287 cb->name = strdup(name);
1288 if (cb->name == NULL) {
1289 ERROR("plugin_register_flush: strdup failed.");
1294 cb->timeout = ctx.flush_timeout;
1296 status = plugin_register_complex_read(
1297 /* group = */ "flush",
1298 /* name = */ flush_name,
1299 /* callback = */ plugin_flush_timeout_callback,
1300 /* interval = */ ctx.flush_interval,
1301 /* user data = */ &(user_data_t){
1302 .data = cb, .free_func = plugin_flush_timeout_callback_free,
1314 } /* int plugin_register_flush */
1316 int plugin_register_missing(const char *name, plugin_missing_cb callback,
1317 user_data_t const *ud) {
1318 return create_register_callback(&list_missing, name, (void *)callback, ud);
1319 } /* int plugin_register_missing */
1321 int plugin_register_shutdown(const char *name, int (*callback)(void)) {
1322 return create_register_callback(&list_shutdown, name, (void *)callback,
1324 } /* int plugin_register_shutdown */
1326 static void plugin_free_data_sets(void) {
1330 if (data_sets == NULL)
1333 while (c_avl_pick(data_sets, &key, &value) == 0) {
1334 data_set_t *ds = value;
1335 /* key is a pointer to ds->type */
1341 c_avl_destroy(data_sets);
1343 } /* void plugin_free_data_sets */
1345 int plugin_register_data_set(const data_set_t *ds) {
1346 data_set_t *ds_copy;
1348 if ((data_sets != NULL) && (c_avl_get(data_sets, ds->type, NULL) == 0)) {
1349 NOTICE("Replacing DS `%s' with another version.", ds->type);
1350 plugin_unregister_data_set(ds->type);
1351 } else if (data_sets == NULL) {
1352 data_sets = c_avl_create((int (*)(const void *, const void *))strcmp);
1353 if (data_sets == NULL)
1357 ds_copy = malloc(sizeof(*ds_copy));
1358 if (ds_copy == NULL)
1360 memcpy(ds_copy, ds, sizeof(data_set_t));
1362 ds_copy->ds = malloc(sizeof(*ds_copy->ds) * ds->ds_num);
1363 if (ds_copy->ds == NULL) {
1368 for (size_t i = 0; i < ds->ds_num; i++)
1369 memcpy(ds_copy->ds + i, ds->ds + i, sizeof(data_source_t));
1371 return c_avl_insert(data_sets, (void *)ds_copy->type, (void *)ds_copy);
1372 } /* int plugin_register_data_set */
1374 int plugin_register_log(const char *name, plugin_log_cb callback,
1375 user_data_t const *ud) {
1376 return create_register_callback(&list_log, name, (void *)callback, ud);
1377 } /* int plugin_register_log */
1379 int plugin_register_notification(const char *name,
1380 plugin_notification_cb callback,
1381 user_data_t const *ud) {
1382 return create_register_callback(&list_notification, name, (void *)callback,
1384 } /* int plugin_register_log */
1386 int plugin_unregister_config(const char *name) {
1387 cf_unregister(name);
1389 } /* int plugin_unregister_config */
1391 int plugin_unregister_complex_config(const char *name) {
1392 cf_unregister_complex(name);
1394 } /* int plugin_unregister_complex_config */
1396 int plugin_unregister_init(const char *name) {
1397 return plugin_unregister(list_init, name);
1400 int plugin_unregister_read(const char *name) /* {{{ */
1408 pthread_mutex_lock(&read_lock);
1410 if (read_list == NULL) {
1411 pthread_mutex_unlock(&read_lock);
1415 le = llist_search(read_list, name);
1417 pthread_mutex_unlock(&read_lock);
1418 WARNING("plugin_unregister_read: No such read function: %s", name);
1422 llist_remove(read_list, le);
1426 rf->rf_type = RF_REMOVE;
1428 pthread_mutex_unlock(&read_lock);
1430 llentry_destroy(le);
1432 DEBUG("plugin_unregister_read: Marked `%s' for removal.", name);
1435 } /* }}} int plugin_unregister_read */
1437 void plugin_log_available_writers(void) {
1438 log_list_callbacks(&list_write, "Available write targets:");
1441 static int compare_read_func_group(llentry_t *e, void *ud) /* {{{ */
1443 read_func_t *rf = e->value;
1446 return strcmp(rf->rf_group, (const char *)group);
1447 } /* }}} int compare_read_func_group */
1449 int plugin_unregister_read_group(const char *group) /* {{{ */
1459 pthread_mutex_lock(&read_lock);
1461 if (read_list == NULL) {
1462 pthread_mutex_unlock(&read_lock);
1467 le = llist_search_custom(read_list, compare_read_func_group, (void *)group);
1474 llist_remove(read_list, le);
1478 rf->rf_type = RF_REMOVE;
1480 llentry_destroy(le);
1482 DEBUG("plugin_unregister_read_group: "
1483 "Marked `%s' (group `%s') for removal.",
1484 rf->rf_name, group);
1487 pthread_mutex_unlock(&read_lock);
1490 WARNING("plugin_unregister_read_group: No such "
1491 "group of read function: %s",
1497 } /* }}} int plugin_unregister_read_group */
1499 int plugin_unregister_write(const char *name) {
1500 return plugin_unregister(list_write, name);
1503 int plugin_unregister_flush(const char *name) {
1504 plugin_ctx_t ctx = plugin_get_ctx();
1506 if (ctx.flush_interval != 0) {
1509 flush_name = plugin_flush_callback_name(name);
1510 if (flush_name != NULL) {
1511 plugin_unregister_read(flush_name);
1516 return plugin_unregister(list_flush, name);
1519 int plugin_unregister_missing(const char *name) {
1520 return plugin_unregister(list_missing, name);
1523 int plugin_unregister_shutdown(const char *name) {
1524 return plugin_unregister(list_shutdown, name);
1527 int plugin_unregister_data_set(const char *name) {
1530 if (data_sets == NULL)
1533 if (c_avl_remove(data_sets, name, NULL, (void *)&ds) != 0)
1540 } /* int plugin_unregister_data_set */
1542 int plugin_unregister_log(const char *name) {
1543 return plugin_unregister(list_log, name);
1546 int plugin_unregister_notification(const char *name) {
1547 return plugin_unregister(list_notification, name);
1550 int plugin_init_all(void) {
1551 char const *chain_name;
1556 /* Init the value cache */
1559 if (IS_TRUE(global_option_get("CollectInternalStats"))) {
1560 record_statistics = 1;
1561 plugin_register_read("collectd", plugin_update_internal_statistics);
1564 chain_name = global_option_get("PreCacheChain");
1565 pre_cache_chain = fc_chain_get_by_name(chain_name);
1567 chain_name = global_option_get("PostCacheChain");
1568 post_cache_chain = fc_chain_get_by_name(chain_name);
1570 write_limit_high = global_option_get_long("WriteQueueLimitHigh",
1572 if (write_limit_high < 0) {
1573 ERROR("WriteQueueLimitHigh must be positive or zero.");
1574 write_limit_high = 0;
1578 global_option_get_long("WriteQueueLimitLow",
1579 /* default = */ write_limit_high / 2);
1580 if (write_limit_low < 0) {
1581 ERROR("WriteQueueLimitLow must be positive or zero.");
1582 write_limit_low = write_limit_high / 2;
1583 } else if (write_limit_low > write_limit_high) {
1584 ERROR("WriteQueueLimitLow must not be larger than "
1585 "WriteQueueLimitHigh.");
1586 write_limit_low = write_limit_high;
1589 write_threads_num = global_option_get_long("WriteThreads",
1591 if (write_threads_num < 1) {
1592 ERROR("WriteThreads must be positive.");
1593 write_threads_num = 5;
1596 if ((list_init == NULL) && (read_heap == NULL))
1599 /* Calling all init callbacks before checking if read callbacks
1600 * are available allows the init callbacks to register the read
1602 le = llist_head(list_init);
1603 while (le != NULL) {
1604 callback_func_t *cf;
1605 plugin_init_cb callback;
1606 plugin_ctx_t old_ctx;
1609 old_ctx = plugin_set_ctx(cf->cf_ctx);
1610 callback = cf->cf_callback;
1611 status = (*callback)();
1612 plugin_set_ctx(old_ctx);
1615 ERROR("Initialization of plugin `%s' "
1616 "failed with status %i. "
1617 "Plugin will be unloaded.",
1619 /* Plugins that register read callbacks from the init
1620 * callback should take care of appropriate error
1621 * handling themselves. */
1622 /* FIXME: Unload _all_ functions */
1623 plugin_unregister_read(le->key);
1630 start_write_threads((size_t)write_threads_num);
1633 global_option_get_time("MaxReadInterval", DEFAULT_MAX_READ_INTERVAL);
1635 /* Start read-threads */
1636 if (read_heap != NULL) {
1640 rt = global_option_get("ReadThreads");
1643 start_read_threads((num > 0) ? ((size_t)num) : 5);
1646 } /* void plugin_init_all */
1648 /* TODO: Rename this function. */
1649 void plugin_read_all(void) {
1653 } /* void plugin_read_all */
1655 /* Read function called when the `-T' command line argument is given. */
1656 int plugin_read_all_once(void) {
1658 int return_status = 0;
1660 if (read_heap == NULL) {
1661 NOTICE("No read-functions are registered.");
1667 plugin_ctx_t old_ctx;
1669 rf = c_heap_get_root(read_heap);
1673 old_ctx = plugin_set_ctx(rf->rf_ctx);
1675 if (rf->rf_type == RF_SIMPLE) {
1676 int (*callback)(void);
1678 callback = rf->rf_callback;
1679 status = (*callback)();
1681 plugin_read_cb callback;
1683 callback = rf->rf_callback;
1684 status = (*callback)(&rf->rf_udata);
1687 plugin_set_ctx(old_ctx);
1690 NOTICE("read-function of plugin `%s' failed.", rf->rf_name);
1695 destroy_callback((void *)rf);
1698 return return_status;
1699 } /* int plugin_read_all_once */
1701 int plugin_write(const char *plugin, /* {{{ */
1702 const data_set_t *ds, const value_list_t *vl) {
1709 if (list_write == NULL)
1713 ds = plugin_get_ds(vl->type);
1715 ERROR("plugin_write: Unable to lookup type `%s'.", vl->type);
1720 if (plugin == NULL) {
1724 le = llist_head(list_write);
1725 while (le != NULL) {
1726 callback_func_t *cf = le->value;
1727 plugin_write_cb callback;
1729 /* do not switch plugin context; rather keep the context (interval)
1730 * information of the calling read plugin */
1732 DEBUG("plugin: plugin_write: Writing values via %s.", le->key);
1733 callback = cf->cf_callback;
1734 status = (*callback)(ds, vl, &cf->cf_udata);
1743 if ((success == 0) && (failure != 0))
1747 } else /* plugin != NULL */
1749 callback_func_t *cf;
1750 plugin_write_cb callback;
1752 le = llist_head(list_write);
1753 while (le != NULL) {
1754 if (strcasecmp(plugin, le->key) == 0)
1765 /* do not switch plugin context; rather keep the context (interval)
1766 * information of the calling read plugin */
1768 DEBUG("plugin: plugin_write: Writing values via %s.", le->key);
1769 callback = cf->cf_callback;
1770 status = (*callback)(ds, vl, &cf->cf_udata);
1774 } /* }}} int plugin_write */
1776 int plugin_flush(const char *plugin, cdtime_t timeout, const char *identifier) {
1779 if (list_flush == NULL)
1782 le = llist_head(list_flush);
1783 while (le != NULL) {
1784 callback_func_t *cf;
1785 plugin_flush_cb callback;
1786 plugin_ctx_t old_ctx;
1788 if ((plugin != NULL) && (strcmp(plugin, le->key) != 0)) {
1794 old_ctx = plugin_set_ctx(cf->cf_ctx);
1795 callback = cf->cf_callback;
1797 (*callback)(timeout, identifier, &cf->cf_udata);
1799 plugin_set_ctx(old_ctx);
1804 } /* int plugin_flush */
1806 int plugin_shutdown_all(void) {
1808 int ret = 0; // Assume success.
1810 destroy_all_callbacks(&list_init);
1812 stop_read_threads();
1814 pthread_mutex_lock(&read_lock);
1815 llist_destroy(read_list);
1817 pthread_mutex_unlock(&read_lock);
1819 destroy_read_heap();
1821 /* blocks until all write threads have shut down. */
1822 stop_write_threads();
1824 /* ask all plugins to write out the state they kept. */
1825 plugin_flush(/* plugin = */ NULL,
1827 /* identifier = */ NULL);
1830 if (list_shutdown != NULL)
1831 le = llist_head(list_shutdown);
1833 while (le != NULL) {
1834 callback_func_t *cf;
1835 plugin_shutdown_cb callback;
1836 plugin_ctx_t old_ctx;
1839 old_ctx = plugin_set_ctx(cf->cf_ctx);
1840 callback = cf->cf_callback;
1842 /* Advance the pointer before calling the callback allows
1843 * shutdown functions to unregister themselves. If done the
1844 * other way around the memory `le' points to will be freed
1845 * after callback returns. */
1848 if ((*callback)() != 0)
1851 plugin_set_ctx(old_ctx);
1854 /* Write plugins which use the `user_data' pointer usually need the
1855 * same data available to the flush callback. If this is the case, set
1856 * the free_function to NULL when registering the flush callback and to
1857 * the real free function when registering the write callback. This way
1858 * the data isn't freed twice. */
1859 destroy_all_callbacks(&list_flush);
1860 destroy_all_callbacks(&list_missing);
1861 destroy_all_callbacks(&list_write);
1863 destroy_all_callbacks(&list_notification);
1864 destroy_all_callbacks(&list_shutdown);
1865 destroy_all_callbacks(&list_log);
1867 plugin_free_loaded();
1868 plugin_free_data_sets();
1870 } /* void plugin_shutdown_all */
1872 int plugin_dispatch_missing(const value_list_t *vl) /* {{{ */
1876 if (list_missing == NULL)
1879 le = llist_head(list_missing);
1880 while (le != NULL) {
1881 callback_func_t *cf;
1882 plugin_missing_cb callback;
1883 plugin_ctx_t old_ctx;
1887 old_ctx = plugin_set_ctx(cf->cf_ctx);
1888 callback = cf->cf_callback;
1890 status = (*callback)(vl, &cf->cf_udata);
1891 plugin_set_ctx(old_ctx);
1894 ERROR("plugin_dispatch_missing: Callback function \"%s\" "
1895 "failed with status %i.",
1906 } /* int }}} plugin_dispatch_missing */
1908 static int plugin_dispatch_values_internal(value_list_t *vl) {
1910 static c_complain_t no_write_complaint = C_COMPLAIN_INIT_STATIC;
1914 _Bool free_meta_data = 0;
1918 /* These fields are initialized by plugin_value_list_clone() if needed: */
1919 assert(vl->host[0] != 0);
1920 assert(vl->time != 0); /* The time is determined at _enqueue_ time. */
1921 assert(vl->interval != 0);
1923 if (vl->type[0] == 0 || vl->values == NULL || vl->values_len < 1) {
1924 ERROR("plugin_dispatch_values: Invalid value list "
1930 /* Free meta data only if the calling function didn't specify any. In
1931 * this case matches and targets may add some and the calling function
1932 * may not expect (and therefore free) that data. */
1933 if (vl->meta == NULL)
1936 if (list_write == NULL)
1937 c_complain_once(LOG_WARNING, &no_write_complaint,
1938 "plugin_dispatch_values: No write callback has been "
1939 "registered. Please load at least one output plugin, "
1940 "if you want the collected data to be stored.");
1942 if (data_sets == NULL) {
1943 ERROR("plugin_dispatch_values: No data sets registered. "
1944 "Could the types database be read? Check "
1945 "your `TypesDB' setting!");
1949 if (c_avl_get(data_sets, vl->type, (void *)&ds) != 0) {
1950 char ident[6 * DATA_MAX_NAME_LEN];
1952 FORMAT_VL(ident, sizeof(ident), vl);
1953 INFO("plugin_dispatch_values: Dataset not found: %s "
1954 "(from \"%s\"), check your types.db!",
1959 DEBUG("plugin_dispatch_values: time = %.3f; interval = %.3f; "
1961 "plugin = %s; plugin_instance = %s; "
1962 "type = %s; type_instance = %s;",
1963 CDTIME_T_TO_DOUBLE(vl->time), CDTIME_T_TO_DOUBLE(vl->interval),
1964 vl->host, vl->plugin, vl->plugin_instance, vl->type, vl->type_instance);
1967 assert(0 == strcmp(ds->type, vl->type));
1969 if (0 != strcmp(ds->type, vl->type))
1970 WARNING("plugin_dispatch_values: (ds->type = %s) != (vl->type = %s)",
1971 ds->type, vl->type);
1975 assert(ds->ds_num == vl->values_len);
1977 if (ds->ds_num != vl->values_len) {
1978 ERROR("plugin_dispatch_values: ds->type = %s: "
1979 "(ds->ds_num = %zu) != "
1980 "(vl->values_len = %zu)",
1981 ds->type, ds->ds_num, vl->values_len);
1986 escape_slashes(vl->host, sizeof(vl->host));
1987 escape_slashes(vl->plugin, sizeof(vl->plugin));
1988 escape_slashes(vl->plugin_instance, sizeof(vl->plugin_instance));
1989 escape_slashes(vl->type, sizeof(vl->type));
1990 escape_slashes(vl->type_instance, sizeof(vl->type_instance));
1992 if (pre_cache_chain != NULL) {
1993 status = fc_process_chain(ds, vl, pre_cache_chain);
1995 WARNING("plugin_dispatch_values: Running the "
1996 "pre-cache chain failed with "
1999 } else if (status == FC_TARGET_STOP)
2003 /* Update the value cache */
2006 if (post_cache_chain != NULL) {
2007 status = fc_process_chain(ds, vl, post_cache_chain);
2009 WARNING("plugin_dispatch_values: Running the "
2010 "post-cache chain failed with "
2015 fc_default_action(ds, vl);
2017 if ((free_meta_data != 0) && (vl->meta != NULL)) {
2018 meta_data_destroy(vl->meta);
2023 } /* int plugin_dispatch_values_internal */
2025 static double get_drop_probability(void) /* {{{ */
2031 pthread_mutex_lock(&write_lock);
2032 wql = write_queue_length;
2033 pthread_mutex_unlock(&write_lock);
2035 if (wql < write_limit_low)
2037 if (wql >= write_limit_high)
2040 pos = 1 + wql - write_limit_low;
2041 size = 1 + write_limit_high - write_limit_low;
2043 return (double)pos / (double)size;
2044 } /* }}} double get_drop_probability */
2046 static _Bool check_drop_value(void) /* {{{ */
2048 static cdtime_t last_message_time = 0;
2049 static pthread_mutex_t last_message_lock = PTHREAD_MUTEX_INITIALIZER;
2055 if (write_limit_high == 0)
2058 p = get_drop_probability();
2062 status = pthread_mutex_trylock(&last_message_lock);
2067 if ((now - last_message_time) > TIME_T_TO_CDTIME_T(1)) {
2068 last_message_time = now;
2069 ERROR("plugin_dispatch_values: Low water mark "
2070 "reached. Dropping %.0f%% of metrics.",
2073 pthread_mutex_unlock(&last_message_lock);
2084 } /* }}} _Bool check_drop_value */
2086 int plugin_dispatch_values(value_list_t const *vl) {
2088 static pthread_mutex_t statistics_lock = PTHREAD_MUTEX_INITIALIZER;
2090 if (check_drop_value()) {
2091 if (record_statistics) {
2092 pthread_mutex_lock(&statistics_lock);
2093 stats_values_dropped++;
2094 pthread_mutex_unlock(&statistics_lock);
2099 status = plugin_write_enqueue(vl);
2102 ERROR("plugin_dispatch_values: plugin_write_enqueue failed "
2103 "with status %i (%s).",
2104 status, sstrerror(status, errbuf, sizeof(errbuf)));
2111 __attribute__((sentinel)) int
2112 plugin_dispatch_multivalue(value_list_t const *template, /* {{{ */
2113 _Bool store_percentage, int store_type, ...) {
2119 assert(template->values_len == 1);
2121 /* Calculate sum for Gauge to calculate percent if needed */
2122 if (DS_TYPE_GAUGE == store_type) {
2123 va_start(ap, store_type);
2128 name = va_arg(ap, char const *);
2132 value = va_arg(ap, gauge_t);
2139 vl = plugin_value_list_clone(template);
2140 /* plugin_value_list_clone makes sure vl->time is set to non-zero. */
2141 if (store_percentage)
2142 sstrncpy(vl->type, "percent", sizeof(vl->type));
2144 va_start(ap, store_type);
2149 /* Set the type instance. */
2150 name = va_arg(ap, char const *);
2153 sstrncpy(vl->type_instance, name, sizeof(vl->type_instance));
2155 /* Set the value. */
2156 switch (store_type) {
2158 vl->values[0].gauge = va_arg(ap, gauge_t);
2159 if (store_percentage)
2160 vl->values[0].gauge *= sum ? (100.0 / sum) : NAN;
2162 case DS_TYPE_ABSOLUTE:
2163 vl->values[0].absolute = va_arg(ap, absolute_t);
2165 case DS_TYPE_COUNTER:
2166 vl->values[0].counter = va_arg(ap, counter_t);
2168 case DS_TYPE_DERIVE:
2169 vl->values[0].derive = va_arg(ap, derive_t);
2172 ERROR("plugin_dispatch_multivalue: given store_type is incorrect.");
2176 status = plugin_write_enqueue(vl);
2182 plugin_value_list_free(vl);
2184 } /* }}} int plugin_dispatch_multivalue */
2186 int plugin_dispatch_notification(const notification_t *notif) {
2188 /* Possible TODO: Add flap detection here */
2190 DEBUG("plugin_dispatch_notification: severity = %i; message = %s; "
2191 "time = %.3f; host = %s;",
2192 notif->severity, notif->message, CDTIME_T_TO_DOUBLE(notif->time),
2195 /* Nobody cares for notifications */
2196 if (list_notification == NULL)
2199 le = llist_head(list_notification);
2200 while (le != NULL) {
2201 callback_func_t *cf;
2202 plugin_notification_cb callback;
2205 /* do not switch plugin context; rather keep the context
2206 * (interval) information of the calling plugin */
2209 callback = cf->cf_callback;
2210 status = (*callback)(notif, &cf->cf_udata);
2212 WARNING("plugin_dispatch_notification: Notification "
2213 "callback %s returned %i.",
2221 } /* int plugin_dispatch_notification */
2223 void plugin_log(int level, const char *format, ...) {
2229 if (level >= LOG_DEBUG)
2233 va_start(ap, format);
2234 vsnprintf(msg, sizeof(msg), format, ap);
2235 msg[sizeof(msg) - 1] = '\0';
2238 if (list_log == NULL) {
2239 fprintf(stderr, "%s\n", msg);
2243 le = llist_head(list_log);
2244 while (le != NULL) {
2245 callback_func_t *cf;
2246 plugin_log_cb callback;
2249 callback = cf->cf_callback;
2251 /* do not switch plugin context; rather keep the context
2252 * (interval) information of the calling plugin */
2254 (*callback)(level, msg, &cf->cf_udata);
2258 } /* void plugin_log */
2260 int parse_log_severity(const char *severity) {
2263 if ((0 == strcasecmp(severity, "emerg")) ||
2264 (0 == strcasecmp(severity, "alert")) ||
2265 (0 == strcasecmp(severity, "crit")) || (0 == strcasecmp(severity, "err")))
2266 log_level = LOG_ERR;
2267 else if (0 == strcasecmp(severity, "warning"))
2268 log_level = LOG_WARNING;
2269 else if (0 == strcasecmp(severity, "notice"))
2270 log_level = LOG_NOTICE;
2271 else if (0 == strcasecmp(severity, "info"))
2272 log_level = LOG_INFO;
2274 else if (0 == strcasecmp(severity, "debug"))
2275 log_level = LOG_DEBUG;
2276 #endif /* COLLECT_DEBUG */
2279 } /* int parse_log_severity */
2281 int parse_notif_severity(const char *severity) {
2282 int notif_severity = -1;
2284 if (strcasecmp(severity, "FAILURE") == 0)
2285 notif_severity = NOTIF_FAILURE;
2286 else if (strcmp(severity, "OKAY") == 0)
2287 notif_severity = NOTIF_OKAY;
2288 else if ((strcmp(severity, "WARNING") == 0) ||
2289 (strcmp(severity, "WARN") == 0))
2290 notif_severity = NOTIF_WARNING;
2292 return notif_severity;
2293 } /* int parse_notif_severity */
2295 const data_set_t *plugin_get_ds(const char *name) {
2298 if (data_sets == NULL) {
2299 ERROR("plugin_get_ds: No data sets are defined yet.");
2303 if (c_avl_get(data_sets, name, (void *)&ds) != 0) {
2304 DEBUG("No such dataset registered: %s", name);
2309 } /* data_set_t *plugin_get_ds */
2311 static int plugin_notification_meta_add(notification_t *n, const char *name,
2312 enum notification_meta_type_e type,
2313 const void *value) {
2314 notification_meta_t *meta;
2315 notification_meta_t *tail;
2317 if ((n == NULL) || (name == NULL) || (value == NULL)) {
2318 ERROR("plugin_notification_meta_add: A pointer is NULL!");
2322 meta = calloc(1, sizeof(*meta));
2324 ERROR("plugin_notification_meta_add: calloc failed.");
2328 sstrncpy(meta->name, name, sizeof(meta->name));
2332 case NM_TYPE_STRING: {
2333 meta->nm_value.nm_string = strdup((const char *)value);
2334 if (meta->nm_value.nm_string == NULL) {
2335 ERROR("plugin_notification_meta_add: strdup failed.");
2341 case NM_TYPE_SIGNED_INT: {
2342 meta->nm_value.nm_signed_int = *((int64_t *)value);
2345 case NM_TYPE_UNSIGNED_INT: {
2346 meta->nm_value.nm_unsigned_int = *((uint64_t *)value);
2349 case NM_TYPE_DOUBLE: {
2350 meta->nm_value.nm_double = *((double *)value);
2353 case NM_TYPE_BOOLEAN: {
2354 meta->nm_value.nm_boolean = *((_Bool *)value);
2358 ERROR("plugin_notification_meta_add: Unknown type: %i", type);
2362 } /* switch (type) */
2366 while ((tail != NULL) && (tail->next != NULL))
2375 } /* int plugin_notification_meta_add */
2377 int plugin_notification_meta_add_string(notification_t *n, const char *name,
2378 const char *value) {
2379 return plugin_notification_meta_add(n, name, NM_TYPE_STRING, value);
2382 int plugin_notification_meta_add_signed_int(notification_t *n, const char *name,
2384 return plugin_notification_meta_add(n, name, NM_TYPE_SIGNED_INT, &value);
2387 int plugin_notification_meta_add_unsigned_int(notification_t *n,
2390 return plugin_notification_meta_add(n, name, NM_TYPE_UNSIGNED_INT, &value);
2393 int plugin_notification_meta_add_double(notification_t *n, const char *name,
2395 return plugin_notification_meta_add(n, name, NM_TYPE_DOUBLE, &value);
2398 int plugin_notification_meta_add_boolean(notification_t *n, const char *name,
2400 return plugin_notification_meta_add(n, name, NM_TYPE_BOOLEAN, &value);
2403 int plugin_notification_meta_copy(notification_t *dst,
2404 const notification_t *src) {
2405 assert(dst != NULL);
2406 assert(src != NULL);
2408 assert((src->meta == NULL) || (src->meta != dst->meta));
2410 for (notification_meta_t *meta = src->meta; meta != NULL; meta = meta->next) {
2411 if (meta->type == NM_TYPE_STRING)
2412 plugin_notification_meta_add_string(dst, meta->name,
2413 meta->nm_value.nm_string);
2414 else if (meta->type == NM_TYPE_SIGNED_INT)
2415 plugin_notification_meta_add_signed_int(dst, meta->name,
2416 meta->nm_value.nm_signed_int);
2417 else if (meta->type == NM_TYPE_UNSIGNED_INT)
2418 plugin_notification_meta_add_unsigned_int(dst, meta->name,
2419 meta->nm_value.nm_unsigned_int);
2420 else if (meta->type == NM_TYPE_DOUBLE)
2421 plugin_notification_meta_add_double(dst, meta->name,
2422 meta->nm_value.nm_double);
2423 else if (meta->type == NM_TYPE_BOOLEAN)
2424 plugin_notification_meta_add_boolean(dst, meta->name,
2425 meta->nm_value.nm_boolean);
2429 } /* int plugin_notification_meta_copy */
2431 int plugin_notification_meta_free(notification_meta_t *n) {
2432 notification_meta_t *this;
2433 notification_meta_t *next;
2436 ERROR("plugin_notification_meta_free: n == NULL!");
2441 while (this != NULL) {
2444 if (this->type == NM_TYPE_STRING) {
2445 /* Assign to a temporary variable to work around nm_string's const
2447 void *tmp = (void *)this->nm_value.nm_string;
2450 this->nm_value.nm_string = NULL;
2458 } /* int plugin_notification_meta_free */
2460 static void plugin_ctx_destructor(void *ctx) {
2462 } /* void plugin_ctx_destructor */
2464 static plugin_ctx_t ctx_init = {/* interval = */ 0};
2466 static plugin_ctx_t *plugin_ctx_create(void) {
2469 ctx = malloc(sizeof(*ctx));
2472 ERROR("Failed to allocate plugin context: %s",
2473 sstrerror(errno, errbuf, sizeof(errbuf)));
2478 assert(plugin_ctx_key_initialized);
2479 pthread_setspecific(plugin_ctx_key, ctx);
2480 DEBUG("Created new plugin context.");
2482 } /* int plugin_ctx_create */
2484 void plugin_init_ctx(void) {
2485 pthread_key_create(&plugin_ctx_key, plugin_ctx_destructor);
2486 plugin_ctx_key_initialized = 1;
2487 } /* void plugin_init_ctx */
2489 plugin_ctx_t plugin_get_ctx(void) {
2492 assert(plugin_ctx_key_initialized);
2493 ctx = pthread_getspecific(plugin_ctx_key);
2496 ctx = plugin_ctx_create();
2497 /* this must no happen -- exit() instead? */
2503 } /* plugin_ctx_t plugin_get_ctx */
2505 plugin_ctx_t plugin_set_ctx(plugin_ctx_t ctx) {
2509 assert(plugin_ctx_key_initialized);
2510 c = pthread_getspecific(plugin_ctx_key);
2513 c = plugin_ctx_create();
2514 /* this must no happen -- exit() instead? */
2523 } /* void plugin_set_ctx */
2525 cdtime_t plugin_get_interval(void) {
2528 interval = plugin_get_ctx().interval;
2532 return cf_get_default_interval();
2533 } /* cdtime_t plugin_get_interval */
2537 void *(*start_routine)(void *);
2541 static void *plugin_thread_start(void *arg) {
2542 plugin_thread_t *plugin_thread = arg;
2544 void *(*start_routine)(void *) = plugin_thread->start_routine;
2545 void *plugin_arg = plugin_thread->arg;
2547 plugin_set_ctx(plugin_thread->ctx);
2549 sfree(plugin_thread);
2551 return start_routine(plugin_arg);
2552 } /* void *plugin_thread_start */
2554 int plugin_thread_create(pthread_t *thread, const pthread_attr_t *attr,
2555 void *(*start_routine)(void *), void *arg,
2557 plugin_thread_t *plugin_thread;
2559 plugin_thread = malloc(sizeof(*plugin_thread));
2560 if (plugin_thread == NULL)
2563 plugin_thread->ctx = plugin_get_ctx();
2564 plugin_thread->start_routine = start_routine;
2565 plugin_thread->arg = arg;
2567 int ret = pthread_create(thread, attr, plugin_thread_start, plugin_thread);
2569 sfree(plugin_thread);
2574 set_thread_name(*thread, name);
2577 } /* int plugin_thread_create */