2 * collectd - src/plugin.c
3 * Copyright (C) 2005-2014 Florian octo Forster
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 * and/or sell copies of the Software, and to permit persons to whom the
10 * Software is furnished to do so, subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 * DEALINGS IN THE SOFTWARE.
24 * Florian octo Forster <octo at collectd.org>
25 * Sebastian Harl <sh at tokkee.org>
28 /* _GNU_SOURCE is needed in Linux to use pthread_setname_np */
34 #include "configfile.h"
35 #include "filter_chain.h"
37 #include "utils_avltree.h"
38 #include "utils_cache.h"
39 #include "utils_complain.h"
40 #include "utils_heap.h"
41 #include "utils_llist.h"
42 #include "utils_random.h"
43 #include "utils_time.h"
46 #define EXPORT __declspec(dllexport)
54 #include <pthread_np.h> /* for pthread_set_name_np(3) */
62 struct callback_func_s {
67 typedef struct callback_func_s callback_func_t;
71 #define RF_REMOVE 65535
73 /* `read_func_t' "inherits" from `callback_func_t'.
74 * The `rf_super' member MUST be the first one in this structure! */
75 #define rf_callback rf_super.cf_callback
76 #define rf_udata rf_super.cf_udata
77 #define rf_ctx rf_super.cf_ctx
78 callback_func_t rf_super;
79 char rf_group[DATA_MAX_NAME_LEN];
83 cdtime_t rf_effective_interval;
84 cdtime_t rf_next_read;
86 typedef struct read_func_s read_func_t;
89 typedef struct write_queue_s write_queue_t;
90 struct write_queue_s {
96 struct flush_callback_s {
100 typedef struct flush_callback_s flush_callback_t;
105 static c_avl_tree_t *plugins_loaded;
107 static llist_t *list_init;
108 static llist_t *list_write;
109 static llist_t *list_flush;
110 static llist_t *list_missing;
111 static llist_t *list_shutdown;
112 static llist_t *list_log;
113 static llist_t *list_notification;
115 static fc_chain_t *pre_cache_chain;
116 static fc_chain_t *post_cache_chain;
118 static c_avl_tree_t *data_sets;
120 static char *plugindir;
122 #ifndef DEFAULT_MAX_READ_INTERVAL
123 #define DEFAULT_MAX_READ_INTERVAL TIME_T_TO_CDTIME_T_STATIC(86400)
125 static c_heap_t *read_heap;
126 static llist_t *read_list;
127 static int read_loop = 1;
128 static pthread_mutex_t read_lock = PTHREAD_MUTEX_INITIALIZER;
129 static pthread_cond_t read_cond = PTHREAD_COND_INITIALIZER;
130 static pthread_t *read_threads;
131 static size_t read_threads_num;
132 static cdtime_t max_read_interval = DEFAULT_MAX_READ_INTERVAL;
134 static write_queue_t *write_queue_head;
135 static write_queue_t *write_queue_tail;
136 static long write_queue_length;
137 static bool write_loop = true;
138 static pthread_mutex_t write_lock = PTHREAD_MUTEX_INITIALIZER;
139 static pthread_cond_t write_cond = PTHREAD_COND_INITIALIZER;
140 static pthread_t *write_threads;
141 static size_t write_threads_num;
143 static pthread_key_t plugin_ctx_key;
144 static bool plugin_ctx_key_initialized;
146 static long write_limit_high;
147 static long write_limit_low;
149 static pthread_mutex_t statistics_lock = PTHREAD_MUTEX_INITIALIZER;
150 static derive_t stats_values_dropped;
151 static bool record_statistics;
156 static int plugin_dispatch_values_internal(value_list_t *vl);
158 static const char *plugin_get_dir(void) {
159 if (plugindir == NULL)
165 static int plugin_update_internal_statistics(void) { /* {{{ */
166 gauge_t copy_write_queue_length = (gauge_t)write_queue_length;
168 /* Initialize `vl' */
169 value_list_t vl = VALUE_LIST_INIT;
170 sstrncpy(vl.plugin, "collectd", sizeof(vl.plugin));
171 vl.interval = plugin_get_interval();
174 sstrncpy(vl.plugin_instance, "write_queue", sizeof(vl.plugin_instance));
176 /* Write queue : queue length */
177 vl.values = &(value_t){.gauge = copy_write_queue_length};
179 sstrncpy(vl.type, "queue_length", sizeof(vl.type));
180 vl.type_instance[0] = 0;
181 plugin_dispatch_values(&vl);
183 /* Write queue : Values dropped (queue length > low limit) */
184 vl.values = &(value_t){.gauge = (gauge_t)stats_values_dropped};
186 sstrncpy(vl.type, "derive", sizeof(vl.type));
187 sstrncpy(vl.type_instance, "dropped", sizeof(vl.type_instance));
188 plugin_dispatch_values(&vl);
191 sstrncpy(vl.plugin_instance, "cache", sizeof(vl.plugin_instance));
193 /* Cache : Nb entry in cache tree */
194 vl.values = &(value_t){.gauge = (gauge_t)uc_get_size()};
196 sstrncpy(vl.type, "cache_size", sizeof(vl.type));
197 vl.type_instance[0] = 0;
198 plugin_dispatch_values(&vl);
201 } /* }}} int plugin_update_internal_statistics */
203 static void free_userdata(user_data_t const *ud) /* {{{ */
208 if ((ud->data != NULL) && (ud->free_func != NULL)) {
209 ud->free_func(ud->data);
211 } /* }}} void free_userdata */
213 static void destroy_callback(callback_func_t *cf) /* {{{ */
217 free_userdata(&cf->cf_udata);
219 } /* }}} void destroy_callback */
221 static void destroy_all_callbacks(llist_t **list) /* {{{ */
228 le = llist_head(*list);
235 destroy_callback(le->value);
241 llist_destroy(*list);
243 } /* }}} void destroy_all_callbacks */
245 static void destroy_read_heap(void) /* {{{ */
247 if (read_heap == NULL)
253 rf = c_heap_get_root(read_heap);
257 destroy_callback((callback_func_t *)rf);
260 c_heap_destroy(read_heap);
262 } /* }}} void destroy_read_heap */
264 static int register_callback(llist_t **list, /* {{{ */
265 const char *name, callback_func_t *cf) {
270 *list = llist_create();
272 ERROR("plugin: register_callback: "
273 "llist_create failed.");
274 destroy_callback(cf);
281 ERROR("plugin: register_callback: strdup failed.");
282 destroy_callback(cf);
286 le = llist_search(*list, name);
288 le = llentry_create(key, cf);
290 ERROR("plugin: register_callback: "
291 "llentry_create failed.");
293 destroy_callback(cf);
297 llist_append(*list, le);
299 callback_func_t *old_cf;
304 P_WARNING("register_callback: "
305 "a callback named `%s' already exists - "
306 "overwriting the old entry!",
309 destroy_callback(old_cf);
314 } /* }}} int register_callback */
316 static void log_list_callbacks(llist_t **list, /* {{{ */
317 const char *comment) {
324 n = llist_size(*list);
326 INFO("%s: [none]", comment);
330 char **keys = calloc(n, sizeof(*keys));
332 ERROR("%s: failed to allocate memory for list of callbacks", comment);
336 for (le = llist_head(*list), i = 0, len = 0; le != NULL; le = le->next, i++) {
338 len += strlen(le->key) + 6;
340 str = malloc(len + 10);
342 ERROR("%s: failed to allocate memory for list of callbacks", comment);
345 strjoin(str, len, keys, n, "', '");
346 INFO("%s ['%s']", comment, str);
350 } /* }}} void log_list_callbacks */
352 static int create_register_callback(llist_t **list, /* {{{ */
353 const char *name, void *callback,
354 user_data_t const *ud) {
356 if (name == NULL || callback == NULL)
359 callback_func_t *cf = calloc(1, sizeof(*cf));
362 ERROR("plugin: create_register_callback: calloc failed.");
366 cf->cf_callback = callback;
368 cf->cf_udata = (user_data_t){
369 .data = NULL, .free_func = NULL,
375 cf->cf_ctx = plugin_get_ctx();
377 return register_callback(list, name, cf);
378 } /* }}} int create_register_callback */
380 static int plugin_unregister(llist_t *list, const char *name) /* {{{ */
387 e = llist_search(list, name);
391 llist_remove(list, e);
394 destroy_callback(e->value);
399 } /* }}} int plugin_unregister */
401 /* plugin_load_file loads the shared object "file" and calls its
402 * "module_register" function. Returns zero on success, non-zero otherwise. */
403 static int plugin_load_file(char const *file, bool global) {
404 int flags = RTLD_NOW;
406 flags |= RTLD_GLOBAL;
408 void *dlh = dlopen(file, flags);
410 char errbuf[1024] = "";
412 snprintf(errbuf, sizeof(errbuf),
413 "dlopen(\"%s\") failed: %s. "
414 "The most common cause for this problem is missing dependencies. "
415 "Use ldd(1) to check the dependencies of the plugin / shared "
419 /* This error is printed to STDERR unconditionally. If list_log is NULL,
420 * plugin_log() will also print to STDERR. We avoid duplicate output by
421 * checking that the list of log handlers, list_log, is not NULL. */
422 fprintf(stderr, "ERROR: %s\n", errbuf);
423 if (list_log != NULL) {
430 void (*reg_handle)(void) = dlsym(dlh, "module_register");
431 if (reg_handle == NULL) {
432 ERROR("Couldn't find symbol \"module_register\" in \"%s\": %s\n", file,
442 static void *plugin_read_thread(void __attribute__((unused)) * args) {
443 while (read_loop != 0) {
445 plugin_ctx_t old_ctx;
453 /* Get the read function that needs to be read next.
454 * We don't need to hold "read_lock" for the heap, but we need
455 * to call c_heap_get_root() and pthread_cond_wait() in the
456 * same protected block. */
457 pthread_mutex_lock(&read_lock);
458 rf = c_heap_get_root(read_heap);
460 pthread_cond_wait(&read_cond, &read_lock);
461 pthread_mutex_unlock(&read_lock);
464 pthread_mutex_unlock(&read_lock);
466 if (rf->rf_interval == 0) {
467 /* this should not happen, because the interval is set
468 * for each plugin when loading it
469 * XXX: issue a warning? */
470 rf->rf_interval = plugin_get_interval();
471 rf->rf_effective_interval = rf->rf_interval;
473 rf->rf_next_read = cdtime();
476 /* sleep until this entry is due,
477 * using pthread_cond_timedwait */
478 pthread_mutex_lock(&read_lock);
479 /* In pthread_cond_timedwait, spurious wakeups are possible
480 * (and really happen, at least on NetBSD with > 1 CPU), thus
481 * we need to re-evaluate the condition every time
482 * pthread_cond_timedwait returns. */
484 while ((read_loop != 0) && (cdtime() < rf->rf_next_read) && rc == 0) {
485 rc = pthread_cond_timedwait(&read_cond, &read_lock,
486 &CDTIME_T_TO_TIMESPEC(rf->rf_next_read));
489 /* Must hold `read_lock' when accessing `rf->rf_type'. */
490 rf_type = rf->rf_type;
491 pthread_mutex_unlock(&read_lock);
493 /* Check if we're supposed to stop.. This may have interrupted
495 if (read_loop == 0) {
496 /* Insert `rf' again, so it can be free'd correctly */
497 c_heap_insert(read_heap, rf);
501 /* The entry has been marked for deletion. The linked list
502 * entry has already been removed by `plugin_unregister_read'.
503 * All we have to do here is free the `read_func_t' and
505 if (rf_type == RF_REMOVE) {
506 DEBUG("plugin_read_thread: Destroying the `%s' "
510 destroy_callback((callback_func_t *)rf);
515 DEBUG("plugin_read_thread: Handling `%s'.", rf->rf_name);
519 old_ctx = plugin_set_ctx(rf->rf_ctx);
521 if (rf_type == RF_SIMPLE) {
522 int (*callback)(void);
524 callback = rf->rf_callback;
525 status = (*callback)();
527 plugin_read_cb callback;
529 assert(rf_type == RF_COMPLEX);
531 callback = rf->rf_callback;
532 status = (*callback)(&rf->rf_udata);
535 plugin_set_ctx(old_ctx);
537 /* If the function signals failure, we will increase the
538 * intervals in which it will be called. */
540 rf->rf_effective_interval *= 2;
541 if (rf->rf_effective_interval > max_read_interval)
542 rf->rf_effective_interval = max_read_interval;
544 NOTICE("read-function of plugin `%s' failed. "
545 "Will suspend it for %.3f seconds.",
546 rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
548 /* Success: Restore the interval, if it was changed. */
549 rf->rf_effective_interval = rf->rf_interval;
552 /* update the ``next read due'' field */
555 /* calculate the time spent in the read function */
556 elapsed = (now - start);
558 if (elapsed > rf->rf_effective_interval)
560 "plugin_read_thread: read-function of the `%s' plugin took %.3f "
561 "seconds, which is above its read interval (%.3f seconds). You might "
562 "want to adjust the `Interval' or `ReadThreads' settings.",
563 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed),
564 CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
566 DEBUG("plugin_read_thread: read-function of the `%s' plugin took "
568 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed));
570 DEBUG("plugin_read_thread: Effective interval of the "
571 "`%s' plugin is %.3f seconds.",
572 rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
574 /* Calculate the next (absolute) time at which this function
575 * should be called. */
576 rf->rf_next_read += rf->rf_effective_interval;
578 /* Check, if `rf_next_read' is in the past. */
579 if (rf->rf_next_read < now) {
580 /* `rf_next_read' is in the past. Insert `now'
581 * so this value doesn't trail off into the
583 rf->rf_next_read = now;
586 DEBUG("plugin_read_thread: Next read of the `%s' plugin at %.3f.",
587 rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_next_read));
589 /* Re-insert this read function into the heap again. */
590 c_heap_insert(read_heap, rf);
591 } /* while (read_loop) */
595 } /* void *plugin_read_thread */
597 #ifdef PTHREAD_MAX_NAMELEN_NP
598 #define THREAD_NAME_MAX PTHREAD_MAX_NAMELEN_NP
600 #define THREAD_NAME_MAX 16
603 static void set_thread_name(pthread_t tid, char const *name) {
604 #if defined(HAVE_PTHREAD_SETNAME_NP) || defined(HAVE_PTHREAD_SET_NAME_NP)
606 /* glibc limits the length of the name and fails if the passed string
607 * is too long, so we truncate it here. */
608 char n[THREAD_NAME_MAX];
609 if (strlen(name) >= THREAD_NAME_MAX)
610 WARNING("set_thread_name(\"%s\"): name too long", name);
611 sstrncpy(n, name, sizeof(n));
613 #if defined(HAVE_PTHREAD_SETNAME_NP)
614 int status = pthread_setname_np(tid, n);
616 ERROR("set_thread_name(\"%s\"): %s", n, STRERROR(status));
618 #else /* if defined(HAVE_PTHREAD_SET_NAME_NP) */
619 pthread_set_name_np(tid, n);
625 static void start_read_threads(size_t num) /* {{{ */
627 if (read_threads != NULL)
630 read_threads = calloc(num, sizeof(*read_threads));
631 if (read_threads == NULL) {
632 ERROR("plugin: start_read_threads: calloc failed.");
636 read_threads_num = 0;
637 for (size_t i = 0; i < num; i++) {
638 int status = pthread_create(read_threads + read_threads_num,
639 /* attr = */ NULL, plugin_read_thread,
642 ERROR("plugin: start_read_threads: pthread_create failed with status %i "
644 status, STRERROR(status));
648 char name[THREAD_NAME_MAX];
649 snprintf(name, sizeof(name), "reader#%" PRIu64, (uint64_t)read_threads_num);
650 set_thread_name(read_threads[read_threads_num], name);
654 } /* }}} void start_read_threads */
656 static void stop_read_threads(void) {
657 if (read_threads == NULL)
660 INFO("collectd: Stopping %" PRIsz " read threads.", read_threads_num);
662 pthread_mutex_lock(&read_lock);
664 DEBUG("plugin: stop_read_threads: Signalling `read_cond'");
665 pthread_cond_broadcast(&read_cond);
666 pthread_mutex_unlock(&read_lock);
668 for (size_t i = 0; i < read_threads_num; i++) {
669 if (pthread_join(read_threads[i], NULL) != 0) {
670 ERROR("plugin: stop_read_threads: pthread_join failed.");
672 read_threads[i] = (pthread_t)0;
675 read_threads_num = 0;
676 } /* void stop_read_threads */
678 static void plugin_value_list_free(value_list_t *vl) /* {{{ */
683 meta_data_destroy(vl->meta);
686 } /* }}} void plugin_value_list_free */
688 static value_list_t *
689 plugin_value_list_clone(value_list_t const *vl_orig) /* {{{ */
696 vl = malloc(sizeof(*vl));
699 memcpy(vl, vl_orig, sizeof(*vl));
701 if (vl->host[0] == 0)
702 sstrncpy(vl->host, hostname_g, sizeof(vl->host));
704 vl->values = calloc(vl_orig->values_len, sizeof(*vl->values));
705 if (vl->values == NULL) {
706 plugin_value_list_free(vl);
709 memcpy(vl->values, vl_orig->values,
710 vl_orig->values_len * sizeof(*vl->values));
712 vl->meta = meta_data_clone(vl->meta);
713 if ((vl_orig->meta != NULL) && (vl->meta == NULL)) {
714 plugin_value_list_free(vl);
721 /* Fill in the interval from the thread context, if it is zero. */
722 if (vl->interval == 0)
723 vl->interval = plugin_get_interval();
726 } /* }}} value_list_t *plugin_value_list_clone */
728 static int plugin_write_enqueue(value_list_t const *vl) /* {{{ */
732 q = malloc(sizeof(*q));
737 q->vl = plugin_value_list_clone(vl);
743 /* Store context of caller (read plugin); otherwise, it would not be
744 * available to the write plugins when actually dispatching the
745 * value-list later on. */
746 q->ctx = plugin_get_ctx();
748 pthread_mutex_lock(&write_lock);
750 if (write_queue_tail == NULL) {
751 write_queue_head = q;
752 write_queue_tail = q;
753 write_queue_length = 1;
755 write_queue_tail->next = q;
756 write_queue_tail = q;
757 write_queue_length += 1;
760 pthread_cond_signal(&write_cond);
761 pthread_mutex_unlock(&write_lock);
764 } /* }}} int plugin_write_enqueue */
766 static value_list_t *plugin_write_dequeue(void) /* {{{ */
771 pthread_mutex_lock(&write_lock);
773 while (write_loop && (write_queue_head == NULL))
774 pthread_cond_wait(&write_cond, &write_lock);
776 if (write_queue_head == NULL) {
777 pthread_mutex_unlock(&write_lock);
781 q = write_queue_head;
782 write_queue_head = q->next;
783 write_queue_length -= 1;
784 if (write_queue_head == NULL) {
785 write_queue_tail = NULL;
786 assert(0 == write_queue_length);
789 pthread_mutex_unlock(&write_lock);
791 (void)plugin_set_ctx(q->ctx);
796 } /* }}} value_list_t *plugin_write_dequeue */
798 static void *plugin_write_thread(void __attribute__((unused)) * args) /* {{{ */
801 value_list_t *vl = plugin_write_dequeue();
805 plugin_dispatch_values_internal(vl);
807 plugin_value_list_free(vl);
812 } /* }}} void *plugin_write_thread */
814 static void start_write_threads(size_t num) /* {{{ */
816 if (write_threads != NULL)
819 write_threads = calloc(num, sizeof(*write_threads));
820 if (write_threads == NULL) {
821 ERROR("plugin: start_write_threads: calloc failed.");
825 write_threads_num = 0;
826 for (size_t i = 0; i < num; i++) {
827 int status = pthread_create(write_threads + write_threads_num,
828 /* attr = */ NULL, plugin_write_thread,
831 ERROR("plugin: start_write_threads: pthread_create failed with status %i "
833 status, STRERROR(status));
837 char name[THREAD_NAME_MAX];
838 snprintf(name, sizeof(name), "writer#%" PRIu64,
839 (uint64_t)write_threads_num);
840 set_thread_name(write_threads[write_threads_num], name);
844 } /* }}} void start_write_threads */
846 static void stop_write_threads(void) /* {{{ */
851 if (write_threads == NULL)
854 INFO("collectd: Stopping %" PRIsz " write threads.", write_threads_num);
856 pthread_mutex_lock(&write_lock);
858 DEBUG("plugin: stop_write_threads: Signalling `write_cond'");
859 pthread_cond_broadcast(&write_cond);
860 pthread_mutex_unlock(&write_lock);
862 for (i = 0; i < write_threads_num; i++) {
863 if (pthread_join(write_threads[i], NULL) != 0) {
864 ERROR("plugin: stop_write_threads: pthread_join failed.");
866 write_threads[i] = (pthread_t)0;
868 sfree(write_threads);
869 write_threads_num = 0;
871 pthread_mutex_lock(&write_lock);
873 for (q = write_queue_head; q != NULL;) {
874 write_queue_t *q1 = q;
875 plugin_value_list_free(q->vl);
880 write_queue_head = NULL;
881 write_queue_tail = NULL;
882 write_queue_length = 0;
883 pthread_mutex_unlock(&write_lock);
886 WARNING("plugin: %" PRIsz " value list%s left after shutting down "
887 "the write threads.",
888 i, (i == 1) ? " was" : "s were");
890 } /* }}} void stop_write_threads */
895 void plugin_set_dir(const char *dir) {
903 plugindir = strdup(dir);
904 if (plugindir == NULL)
905 ERROR("plugin_set_dir: strdup(\"%s\") failed", dir);
908 static bool plugin_is_loaded(char const *name) {
911 if (plugins_loaded == NULL)
913 c_avl_create((int (*)(const void *, const void *))strcasecmp);
914 assert(plugins_loaded != NULL);
916 status = c_avl_get(plugins_loaded, name, /* ret_value = */ NULL);
920 static int plugin_mark_loaded(char const *name) {
924 name_copy = strdup(name);
925 if (name_copy == NULL)
928 status = c_avl_insert(plugins_loaded,
929 /* key = */ name_copy, /* value = */ NULL);
933 static void plugin_free_loaded(void) {
937 if (plugins_loaded == NULL)
940 while (c_avl_pick(plugins_loaded, &key, &value) == 0) {
942 assert(value == NULL);
945 c_avl_destroy(plugins_loaded);
946 plugins_loaded = NULL;
951 #define SHLIB_SUFFIX ".dll"
953 #define SHLIB_SUFFIX ".so"
955 int plugin_load(char const *plugin_name, bool global) {
958 char filename[BUFSIZE] = "";
959 char typename[BUFSIZE];
965 if (plugin_name == NULL)
968 /* Check if plugin is already loaded and don't do anything in this
970 if (plugin_is_loaded(plugin_name))
973 dir = plugin_get_dir();
977 * XXX: Magic at work:
979 * Some of the language bindings, for example the Python and Perl
980 * plugins, need to be able to export symbols to the scripts they run.
981 * For this to happen, the "Globals" flag needs to be set.
982 * Unfortunately, this technical detail is hard to explain to the
983 * average user and she shouldn't have to worry about this, ideally.
984 * So in order to save everyone's sanity use a different default for a
985 * handful of special plugins. --octo
987 if ((strcasecmp("perl", plugin_name) == 0) ||
988 (strcasecmp("python", plugin_name) == 0))
991 /* `cpu' should not match `cpufreq'. To solve this we add SHLIB_SUFFIX to the
992 * type when matching the filename */
993 status = snprintf(typename, sizeof(typename), "%s" SHLIB_SUFFIX, plugin_name);
994 if ((status < 0) || ((size_t)status >= sizeof(typename))) {
995 WARNING("plugin_load: Filename too long: \"%s" SHLIB_SUFFIX "\"",
1000 if ((dh = opendir(dir)) == NULL) {
1001 ERROR("plugin_load: opendir (%s) failed: %s", dir, STRERRNO);
1005 while ((de = readdir(dh)) != NULL) {
1006 if (strcasecmp(de->d_name, typename))
1009 status = snprintf(filename, sizeof(filename), "%s/%s", dir, de->d_name);
1010 if ((status < 0) || ((size_t)status >= sizeof(filename))) {
1011 WARNING("plugin_load: Filename too long: \"%s/%s\"", dir, de->d_name);
1015 if (lstat(filename, &statbuf) == -1) {
1016 WARNING("plugin_load: stat (\"%s\") failed: %s", filename, STRERRNO);
1018 } else if (!S_ISREG(statbuf.st_mode)) {
1019 /* don't follow symlinks */
1020 WARNING("plugin_load: %s is not a regular file.", filename);
1024 status = plugin_load_file(filename, global);
1027 plugin_mark_loaded(plugin_name);
1029 INFO("plugin_load: plugin \"%s\" successfully loaded.", plugin_name);
1032 ERROR("plugin_load: Load plugin \"%s\" failed with "
1034 plugin_name, status);
1040 if (filename[0] == 0)
1041 ERROR("plugin_load: Could not find plugin \"%s\" in %s", plugin_name, dir);
1047 * The `register_*' functions follow
1049 EXPORT int plugin_register_config(const char *name,
1050 int (*callback)(const char *key,
1052 const char **keys, int keys_num) {
1053 cf_register(name, callback, keys, keys_num);
1055 } /* int plugin_register_config */
1057 EXPORT int plugin_register_complex_config(const char *type,
1058 int (*callback)(oconfig_item_t *)) {
1059 return cf_register_complex(type, callback);
1060 } /* int plugin_register_complex_config */
1062 EXPORT int plugin_register_init(const char *name, int (*callback)(void)) {
1063 return create_register_callback(&list_init, name, (void *)callback, NULL);
1064 } /* plugin_register_init */
1066 static int plugin_compare_read_func(const void *arg0, const void *arg1) {
1067 const read_func_t *rf0;
1068 const read_func_t *rf1;
1073 if (rf0->rf_next_read < rf1->rf_next_read)
1075 else if (rf0->rf_next_read > rf1->rf_next_read)
1079 } /* int plugin_compare_read_func */
1081 /* Add a read function to both, the heap and a linked list. The linked list if
1082 * used to look-up read functions, especially for the remove function. The heap
1083 * is used to determine which plugin to read next. */
1084 static int plugin_insert_read(read_func_t *rf) {
1088 rf->rf_next_read = cdtime();
1089 rf->rf_effective_interval = rf->rf_interval;
1091 pthread_mutex_lock(&read_lock);
1093 if (read_list == NULL) {
1094 read_list = llist_create();
1095 if (read_list == NULL) {
1096 pthread_mutex_unlock(&read_lock);
1097 ERROR("plugin_insert_read: read_list failed.");
1102 if (read_heap == NULL) {
1103 read_heap = c_heap_create(plugin_compare_read_func);
1104 if (read_heap == NULL) {
1105 pthread_mutex_unlock(&read_lock);
1106 ERROR("plugin_insert_read: c_heap_create failed.");
1111 le = llist_search(read_list, rf->rf_name);
1113 pthread_mutex_unlock(&read_lock);
1114 P_WARNING("The read function \"%s\" is already registered. "
1115 "Check for duplicates in your configuration!",
1120 le = llentry_create(rf->rf_name, rf);
1122 pthread_mutex_unlock(&read_lock);
1123 ERROR("plugin_insert_read: llentry_create failed.");
1127 status = c_heap_insert(read_heap, rf);
1129 pthread_mutex_unlock(&read_lock);
1130 ERROR("plugin_insert_read: c_heap_insert failed.");
1131 llentry_destroy(le);
1135 /* This does not fail. */
1136 llist_append(read_list, le);
1138 /* Wake up all the read threads. */
1139 pthread_cond_broadcast(&read_cond);
1140 pthread_mutex_unlock(&read_lock);
1142 } /* int plugin_insert_read */
1144 EXPORT int plugin_register_read(const char *name, int (*callback)(void)) {
1148 rf = calloc(1, sizeof(*rf));
1150 ERROR("plugin_register_read: calloc failed.");
1154 rf->rf_callback = (void *)callback;
1155 rf->rf_udata.data = NULL;
1156 rf->rf_udata.free_func = NULL;
1157 rf->rf_ctx = plugin_get_ctx();
1158 rf->rf_group[0] = '\0';
1159 rf->rf_name = strdup(name);
1160 rf->rf_type = RF_SIMPLE;
1161 rf->rf_interval = plugin_get_interval();
1162 rf->rf_ctx.interval = rf->rf_interval;
1164 status = plugin_insert_read(rf);
1171 } /* int plugin_register_read */
1173 EXPORT int plugin_register_complex_read(const char *group, const char *name,
1174 plugin_read_cb callback,
1176 user_data_t const *user_data) {
1180 rf = calloc(1, sizeof(*rf));
1182 free_userdata(user_data);
1183 ERROR("plugin_register_complex_read: calloc failed.");
1187 rf->rf_callback = (void *)callback;
1189 sstrncpy(rf->rf_group, group, sizeof(rf->rf_group));
1191 rf->rf_group[0] = '\0';
1192 rf->rf_name = strdup(name);
1193 rf->rf_type = RF_COMPLEX;
1194 rf->rf_interval = (interval != 0) ? interval : plugin_get_interval();
1197 if (user_data == NULL) {
1198 rf->rf_udata.data = NULL;
1199 rf->rf_udata.free_func = NULL;
1201 rf->rf_udata = *user_data;
1204 rf->rf_ctx = plugin_get_ctx();
1205 rf->rf_ctx.interval = rf->rf_interval;
1207 status = plugin_insert_read(rf);
1209 free_userdata(&rf->rf_udata);
1215 } /* int plugin_register_complex_read */
1217 EXPORT int plugin_register_write(const char *name, plugin_write_cb callback,
1218 user_data_t const *ud) {
1219 return create_register_callback(&list_write, name, (void *)callback, ud);
1220 } /* int plugin_register_write */
1222 static int plugin_flush_timeout_callback(user_data_t *ud) {
1223 flush_callback_t *cb = ud->data;
1225 return plugin_flush(cb->name, cb->timeout, NULL);
1226 } /* static int plugin_flush_callback */
1228 static void plugin_flush_timeout_callback_free(void *data) {
1229 flush_callback_t *cb = data;
1236 } /* static void plugin_flush_callback_free */
1238 static char *plugin_flush_callback_name(const char *name) {
1239 const char *flush_prefix = "flush/";
1244 prefix_size = strlen(flush_prefix);
1245 name_size = strlen(name);
1247 flush_name = malloc(name_size + prefix_size + 1);
1248 if (flush_name == NULL) {
1249 ERROR("plugin_flush_callback_name: malloc failed.");
1253 sstrncpy(flush_name, flush_prefix, prefix_size + 1);
1254 sstrncpy(flush_name + prefix_size, name, name_size + 1);
1257 } /* static char *plugin_flush_callback_name */
1259 EXPORT int plugin_register_flush(const char *name, plugin_flush_cb callback,
1260 user_data_t const *ud) {
1262 plugin_ctx_t ctx = plugin_get_ctx();
1264 status = create_register_callback(&list_flush, name, (void *)callback, ud);
1268 if (ctx.flush_interval != 0) {
1270 flush_callback_t *cb;
1272 flush_name = plugin_flush_callback_name(name);
1273 if (flush_name == NULL)
1276 cb = malloc(sizeof(*cb));
1278 ERROR("plugin_register_flush: malloc failed.");
1283 cb->name = strdup(name);
1284 if (cb->name == NULL) {
1285 ERROR("plugin_register_flush: strdup failed.");
1290 cb->timeout = ctx.flush_timeout;
1292 status = plugin_register_complex_read(
1293 /* group = */ "flush",
1294 /* name = */ flush_name,
1295 /* callback = */ plugin_flush_timeout_callback,
1296 /* interval = */ ctx.flush_interval,
1297 /* user data = */ &(user_data_t){
1298 .data = cb, .free_func = plugin_flush_timeout_callback_free,
1306 } /* int plugin_register_flush */
1308 EXPORT int plugin_register_missing(const char *name, plugin_missing_cb callback,
1309 user_data_t const *ud) {
1310 return create_register_callback(&list_missing, name, (void *)callback, ud);
1311 } /* int plugin_register_missing */
1313 EXPORT int plugin_register_shutdown(const char *name, int (*callback)(void)) {
1314 return create_register_callback(&list_shutdown, name, (void *)callback, NULL);
1315 } /* int plugin_register_shutdown */
1317 static void plugin_free_data_sets(void) {
1321 if (data_sets == NULL)
1324 while (c_avl_pick(data_sets, &key, &value) == 0) {
1325 data_set_t *ds = value;
1326 /* key is a pointer to ds->type */
1332 c_avl_destroy(data_sets);
1334 } /* void plugin_free_data_sets */
1336 EXPORT int plugin_register_data_set(const data_set_t *ds) {
1337 data_set_t *ds_copy;
1339 if ((data_sets != NULL) && (c_avl_get(data_sets, ds->type, NULL) == 0)) {
1340 NOTICE("Replacing DS `%s' with another version.", ds->type);
1341 plugin_unregister_data_set(ds->type);
1342 } else if (data_sets == NULL) {
1343 data_sets = c_avl_create((int (*)(const void *, const void *))strcmp);
1344 if (data_sets == NULL)
1348 ds_copy = malloc(sizeof(*ds_copy));
1349 if (ds_copy == NULL)
1351 memcpy(ds_copy, ds, sizeof(data_set_t));
1353 ds_copy->ds = malloc(sizeof(*ds_copy->ds) * ds->ds_num);
1354 if (ds_copy->ds == NULL) {
1359 for (size_t i = 0; i < ds->ds_num; i++)
1360 memcpy(ds_copy->ds + i, ds->ds + i, sizeof(data_source_t));
1362 return c_avl_insert(data_sets, (void *)ds_copy->type, (void *)ds_copy);
1363 } /* int plugin_register_data_set */
1365 EXPORT int plugin_register_log(const char *name, plugin_log_cb callback,
1366 user_data_t const *ud) {
1367 return create_register_callback(&list_log, name, (void *)callback, ud);
1368 } /* int plugin_register_log */
1370 EXPORT int plugin_register_notification(const char *name,
1371 plugin_notification_cb callback,
1372 user_data_t const *ud) {
1373 return create_register_callback(&list_notification, name, (void *)callback,
1375 } /* int plugin_register_log */
1377 EXPORT int plugin_unregister_config(const char *name) {
1378 cf_unregister(name);
1380 } /* int plugin_unregister_config */
1382 EXPORT int plugin_unregister_complex_config(const char *name) {
1383 cf_unregister_complex(name);
1385 } /* int plugin_unregister_complex_config */
1387 EXPORT int plugin_unregister_init(const char *name) {
1388 return plugin_unregister(list_init, name);
1391 EXPORT int plugin_unregister_read(const char *name) /* {{{ */
1399 pthread_mutex_lock(&read_lock);
1401 if (read_list == NULL) {
1402 pthread_mutex_unlock(&read_lock);
1406 le = llist_search(read_list, name);
1408 pthread_mutex_unlock(&read_lock);
1409 WARNING("plugin_unregister_read: No such read function: %s", name);
1413 llist_remove(read_list, le);
1417 rf->rf_type = RF_REMOVE;
1419 pthread_mutex_unlock(&read_lock);
1421 llentry_destroy(le);
1423 DEBUG("plugin_unregister_read: Marked `%s' for removal.", name);
1426 } /* }}} int plugin_unregister_read */
1428 EXPORT void plugin_log_available_writers(void) {
1429 log_list_callbacks(&list_write, "Available write targets:");
1432 static int compare_read_func_group(llentry_t *e, void *ud) /* {{{ */
1434 read_func_t *rf = e->value;
1437 return strcmp(rf->rf_group, (const char *)group);
1438 } /* }}} int compare_read_func_group */
1440 EXPORT int plugin_unregister_read_group(const char *group) /* {{{ */
1450 pthread_mutex_lock(&read_lock);
1452 if (read_list == NULL) {
1453 pthread_mutex_unlock(&read_lock);
1458 le = llist_search_custom(read_list, compare_read_func_group, (void *)group);
1465 llist_remove(read_list, le);
1469 rf->rf_type = RF_REMOVE;
1471 llentry_destroy(le);
1473 DEBUG("plugin_unregister_read_group: "
1474 "Marked `%s' (group `%s') for removal.",
1475 rf->rf_name, group);
1478 pthread_mutex_unlock(&read_lock);
1481 WARNING("plugin_unregister_read_group: No such "
1482 "group of read function: %s",
1488 } /* }}} int plugin_unregister_read_group */
1490 EXPORT int plugin_unregister_write(const char *name) {
1491 return plugin_unregister(list_write, name);
1494 EXPORT int plugin_unregister_flush(const char *name) {
1495 plugin_ctx_t ctx = plugin_get_ctx();
1497 if (ctx.flush_interval != 0) {
1500 flush_name = plugin_flush_callback_name(name);
1501 if (flush_name != NULL) {
1502 plugin_unregister_read(flush_name);
1507 return plugin_unregister(list_flush, name);
1510 EXPORT int plugin_unregister_missing(const char *name) {
1511 return plugin_unregister(list_missing, name);
1514 EXPORT int plugin_unregister_shutdown(const char *name) {
1515 return plugin_unregister(list_shutdown, name);
1518 EXPORT int plugin_unregister_data_set(const char *name) {
1521 if (data_sets == NULL)
1524 if (c_avl_remove(data_sets, name, NULL, (void *)&ds) != 0)
1531 } /* int plugin_unregister_data_set */
1533 EXPORT int plugin_unregister_log(const char *name) {
1534 return plugin_unregister(list_log, name);
1537 EXPORT int plugin_unregister_notification(const char *name) {
1538 return plugin_unregister(list_notification, name);
1541 EXPORT int plugin_init_all(void) {
1542 char const *chain_name;
1547 /* Init the value cache */
1550 if (IS_TRUE(global_option_get("CollectInternalStats"))) {
1551 record_statistics = true;
1552 plugin_register_read("collectd", plugin_update_internal_statistics);
1555 chain_name = global_option_get("PreCacheChain");
1556 pre_cache_chain = fc_chain_get_by_name(chain_name);
1558 chain_name = global_option_get("PostCacheChain");
1559 post_cache_chain = fc_chain_get_by_name(chain_name);
1561 write_limit_high = global_option_get_long("WriteQueueLimitHigh",
1563 if (write_limit_high < 0) {
1564 ERROR("WriteQueueLimitHigh must be positive or zero.");
1565 write_limit_high = 0;
1569 global_option_get_long("WriteQueueLimitLow",
1570 /* default = */ write_limit_high / 2);
1571 if (write_limit_low < 0) {
1572 ERROR("WriteQueueLimitLow must be positive or zero.");
1573 write_limit_low = write_limit_high / 2;
1574 } else if (write_limit_low > write_limit_high) {
1575 ERROR("WriteQueueLimitLow must not be larger than "
1576 "WriteQueueLimitHigh.");
1577 write_limit_low = write_limit_high;
1580 write_threads_num = global_option_get_long("WriteThreads",
1582 if (write_threads_num < 1) {
1583 ERROR("WriteThreads must be positive.");
1584 write_threads_num = 5;
1587 if ((list_init == NULL) && (read_heap == NULL))
1590 /* Calling all init callbacks before checking if read callbacks
1591 * are available allows the init callbacks to register the read
1593 le = llist_head(list_init);
1594 while (le != NULL) {
1595 callback_func_t *cf;
1596 plugin_init_cb callback;
1597 plugin_ctx_t old_ctx;
1600 old_ctx = plugin_set_ctx(cf->cf_ctx);
1601 callback = cf->cf_callback;
1602 status = (*callback)();
1603 plugin_set_ctx(old_ctx);
1606 ERROR("Initialization of plugin `%s' "
1607 "failed with status %i. "
1608 "Plugin will be unloaded.",
1610 /* Plugins that register read callbacks from the init
1611 * callback should take care of appropriate error
1612 * handling themselves. */
1613 /* FIXME: Unload _all_ functions */
1614 plugin_unregister_read(le->key);
1621 start_write_threads((size_t)write_threads_num);
1624 global_option_get_time("MaxReadInterval", DEFAULT_MAX_READ_INTERVAL);
1626 /* Start read-threads */
1627 if (read_heap != NULL) {
1631 rt = global_option_get("ReadThreads");
1634 start_read_threads((num > 0) ? ((size_t)num) : 5);
1637 } /* void plugin_init_all */
1639 /* TODO: Rename this function. */
1640 EXPORT void plugin_read_all(void) {
1644 } /* void plugin_read_all */
1646 /* Read function called when the `-T' command line argument is given. */
1647 EXPORT int plugin_read_all_once(void) {
1649 int return_status = 0;
1651 if (read_heap == NULL) {
1652 NOTICE("No read-functions are registered.");
1658 plugin_ctx_t old_ctx;
1660 rf = c_heap_get_root(read_heap);
1664 old_ctx = plugin_set_ctx(rf->rf_ctx);
1666 if (rf->rf_type == RF_SIMPLE) {
1667 int (*callback)(void);
1669 callback = rf->rf_callback;
1670 status = (*callback)();
1672 plugin_read_cb callback;
1674 callback = rf->rf_callback;
1675 status = (*callback)(&rf->rf_udata);
1678 plugin_set_ctx(old_ctx);
1681 NOTICE("read-function of plugin `%s' failed.", rf->rf_name);
1686 destroy_callback((void *)rf);
1689 return return_status;
1690 } /* int plugin_read_all_once */
1692 EXPORT int plugin_write(const char *plugin, /* {{{ */
1693 const data_set_t *ds, const value_list_t *vl) {
1700 if (list_write == NULL)
1704 ds = plugin_get_ds(vl->type);
1706 ERROR("plugin_write: Unable to lookup type `%s'.", vl->type);
1711 if (plugin == NULL) {
1715 le = llist_head(list_write);
1716 while (le != NULL) {
1717 callback_func_t *cf = le->value;
1718 plugin_write_cb callback;
1720 /* Keep the read plugin's interval and flush information but update the
1722 plugin_ctx_t old_ctx = plugin_get_ctx();
1723 plugin_ctx_t ctx = old_ctx;
1724 ctx.name = cf->cf_ctx.name;
1725 plugin_set_ctx(ctx);
1727 DEBUG("plugin: plugin_write: Writing values via %s.", le->key);
1728 callback = cf->cf_callback;
1729 status = (*callback)(ds, vl, &cf->cf_udata);
1735 plugin_set_ctx(old_ctx);
1739 if ((success == 0) && (failure != 0))
1743 } else /* plugin != NULL */
1745 callback_func_t *cf;
1746 plugin_write_cb callback;
1748 le = llist_head(list_write);
1749 while (le != NULL) {
1750 if (strcasecmp(plugin, le->key) == 0)
1761 /* do not switch plugin context; rather keep the context (interval)
1762 * information of the calling read plugin */
1764 DEBUG("plugin: plugin_write: Writing values via %s.", le->key);
1765 callback = cf->cf_callback;
1766 status = (*callback)(ds, vl, &cf->cf_udata);
1770 } /* }}} int plugin_write */
1772 EXPORT int plugin_flush(const char *plugin, cdtime_t timeout,
1773 const char *identifier) {
1776 if (list_flush == NULL)
1779 le = llist_head(list_flush);
1780 while (le != NULL) {
1781 callback_func_t *cf;
1782 plugin_flush_cb callback;
1783 plugin_ctx_t old_ctx;
1785 if ((plugin != NULL) && (strcmp(plugin, le->key) != 0)) {
1791 old_ctx = plugin_set_ctx(cf->cf_ctx);
1792 callback = cf->cf_callback;
1794 (*callback)(timeout, identifier, &cf->cf_udata);
1796 plugin_set_ctx(old_ctx);
1801 } /* int plugin_flush */
1803 EXPORT int plugin_shutdown_all(void) {
1805 int ret = 0; // Assume success.
1807 destroy_all_callbacks(&list_init);
1809 stop_read_threads();
1811 pthread_mutex_lock(&read_lock);
1812 llist_destroy(read_list);
1814 pthread_mutex_unlock(&read_lock);
1816 destroy_read_heap();
1818 /* blocks until all write threads have shut down. */
1819 stop_write_threads();
1821 /* ask all plugins to write out the state they kept. */
1822 plugin_flush(/* plugin = */ NULL,
1824 /* identifier = */ NULL);
1827 if (list_shutdown != NULL)
1828 le = llist_head(list_shutdown);
1830 while (le != NULL) {
1831 callback_func_t *cf;
1832 plugin_shutdown_cb callback;
1833 plugin_ctx_t old_ctx;
1836 old_ctx = plugin_set_ctx(cf->cf_ctx);
1837 callback = cf->cf_callback;
1839 /* Advance the pointer before calling the callback allows
1840 * shutdown functions to unregister themselves. If done the
1841 * other way around the memory `le' points to will be freed
1842 * after callback returns. */
1845 if ((*callback)() != 0)
1848 plugin_set_ctx(old_ctx);
1851 /* Write plugins which use the `user_data' pointer usually need the
1852 * same data available to the flush callback. If this is the case, set
1853 * the free_function to NULL when registering the flush callback and to
1854 * the real free function when registering the write callback. This way
1855 * the data isn't freed twice. */
1856 destroy_all_callbacks(&list_flush);
1857 destroy_all_callbacks(&list_missing);
1858 destroy_all_callbacks(&list_write);
1860 destroy_all_callbacks(&list_notification);
1861 destroy_all_callbacks(&list_shutdown);
1862 destroy_all_callbacks(&list_log);
1864 plugin_free_loaded();
1865 plugin_free_data_sets();
1867 } /* void plugin_shutdown_all */
1869 EXPORT int plugin_dispatch_missing(const value_list_t *vl) /* {{{ */
1871 if (list_missing == NULL)
1874 llentry_t *le = llist_head(list_missing);
1875 while (le != NULL) {
1876 callback_func_t *cf = le->value;
1877 plugin_ctx_t old_ctx = plugin_set_ctx(cf->cf_ctx);
1878 plugin_missing_cb callback = cf->cf_callback;
1880 int status = (*callback)(vl, &cf->cf_udata);
1881 plugin_set_ctx(old_ctx);
1884 ERROR("plugin_dispatch_missing: Callback function \"%s\" "
1885 "failed with status %i.",
1896 } /* int }}} plugin_dispatch_missing */
1898 static int plugin_dispatch_values_internal(value_list_t *vl) {
1900 static c_complain_t no_write_complaint = C_COMPLAIN_INIT_STATIC;
1902 bool free_meta_data = false;
1906 /* These fields are initialized by plugin_value_list_clone() if needed: */
1907 assert(vl->host[0] != 0);
1908 assert(vl->time != 0); /* The time is determined at _enqueue_ time. */
1909 assert(vl->interval != 0);
1911 if (vl->type[0] == 0 || vl->values == NULL || vl->values_len < 1) {
1912 ERROR("plugin_dispatch_values: Invalid value list "
1918 /* Free meta data only if the calling function didn't specify any. In
1919 * this case matches and targets may add some and the calling function
1920 * may not expect (and therefore free) that data. */
1921 if (vl->meta == NULL)
1922 free_meta_data = true;
1924 if (list_write == NULL)
1925 c_complain_once(LOG_WARNING, &no_write_complaint,
1926 "plugin_dispatch_values: No write callback has been "
1927 "registered. Please load at least one output plugin, "
1928 "if you want the collected data to be stored.");
1930 if (data_sets == NULL) {
1931 ERROR("plugin_dispatch_values: No data sets registered. "
1932 "Could the types database be read? Check "
1933 "your `TypesDB' setting!");
1937 data_set_t *ds = NULL;
1938 if (c_avl_get(data_sets, vl->type, (void *)&ds) != 0) {
1939 char ident[6 * DATA_MAX_NAME_LEN];
1941 FORMAT_VL(ident, sizeof(ident), vl);
1942 INFO("plugin_dispatch_values: Dataset not found: %s "
1943 "(from \"%s\"), check your types.db!",
1948 DEBUG("plugin_dispatch_values: time = %.3f; interval = %.3f; "
1950 "plugin = %s; plugin_instance = %s; "
1951 "type = %s; type_instance = %s;",
1952 CDTIME_T_TO_DOUBLE(vl->time), CDTIME_T_TO_DOUBLE(vl->interval),
1953 vl->host, vl->plugin, vl->plugin_instance, vl->type, vl->type_instance);
1956 assert(0 == strcmp(ds->type, vl->type));
1958 if (0 != strcmp(ds->type, vl->type))
1959 WARNING("plugin_dispatch_values: (ds->type = %s) != (vl->type = %s)",
1960 ds->type, vl->type);
1964 assert(ds->ds_num == vl->values_len);
1966 if (ds->ds_num != vl->values_len) {
1967 ERROR("plugin_dispatch_values: ds->type = %s: "
1968 "(ds->ds_num = %" PRIsz ") != "
1969 "(vl->values_len = %" PRIsz ")",
1970 ds->type, ds->ds_num, vl->values_len);
1975 escape_slashes(vl->host, sizeof(vl->host));
1976 escape_slashes(vl->plugin, sizeof(vl->plugin));
1977 escape_slashes(vl->plugin_instance, sizeof(vl->plugin_instance));
1978 escape_slashes(vl->type, sizeof(vl->type));
1979 escape_slashes(vl->type_instance, sizeof(vl->type_instance));
1981 if (pre_cache_chain != NULL) {
1982 status = fc_process_chain(ds, vl, pre_cache_chain);
1984 WARNING("plugin_dispatch_values: Running the "
1985 "pre-cache chain failed with "
1988 } else if (status == FC_TARGET_STOP)
1992 /* Update the value cache */
1995 if (post_cache_chain != NULL) {
1996 status = fc_process_chain(ds, vl, post_cache_chain);
1998 WARNING("plugin_dispatch_values: Running the "
1999 "post-cache chain failed with "
2004 fc_default_action(ds, vl);
2006 if ((free_meta_data == true) && (vl->meta != NULL)) {
2007 meta_data_destroy(vl->meta);
2012 } /* int plugin_dispatch_values_internal */
2014 static double get_drop_probability(void) /* {{{ */
2020 pthread_mutex_lock(&write_lock);
2021 wql = write_queue_length;
2022 pthread_mutex_unlock(&write_lock);
2024 if (wql < write_limit_low)
2026 if (wql >= write_limit_high)
2029 pos = 1 + wql - write_limit_low;
2030 size = 1 + write_limit_high - write_limit_low;
2032 return (double)pos / (double)size;
2033 } /* }}} double get_drop_probability */
2035 static bool check_drop_value(void) /* {{{ */
2037 static cdtime_t last_message_time;
2038 static pthread_mutex_t last_message_lock = PTHREAD_MUTEX_INITIALIZER;
2044 if (write_limit_high == 0)
2047 p = get_drop_probability();
2051 status = pthread_mutex_trylock(&last_message_lock);
2056 if ((now - last_message_time) > TIME_T_TO_CDTIME_T(1)) {
2057 last_message_time = now;
2058 ERROR("plugin_dispatch_values: Low water mark "
2059 "reached. Dropping %.0f%% of metrics.",
2062 pthread_mutex_unlock(&last_message_lock);
2073 } /* }}} bool check_drop_value */
2075 EXPORT int plugin_dispatch_values(value_list_t const *vl) {
2078 if (check_drop_value()) {
2079 if (record_statistics) {
2080 pthread_mutex_lock(&statistics_lock);
2081 stats_values_dropped++;
2082 pthread_mutex_unlock(&statistics_lock);
2087 status = plugin_write_enqueue(vl);
2089 ERROR("plugin_dispatch_values: plugin_write_enqueue failed with status %i "
2091 status, STRERROR(status));
2098 __attribute__((sentinel)) int
2099 plugin_dispatch_multivalue(value_list_t const *template, /* {{{ */
2100 bool store_percentage, int store_type, ...) {
2106 if (check_drop_value()) {
2107 if (record_statistics) {
2108 pthread_mutex_lock(&statistics_lock);
2109 stats_values_dropped++;
2110 pthread_mutex_unlock(&statistics_lock);
2115 assert(template->values_len == 1);
2117 /* Calculate sum for Gauge to calculate percent if needed */
2118 if (DS_TYPE_GAUGE == store_type) {
2119 va_start(ap, store_type);
2124 name = va_arg(ap, char const *);
2128 value = va_arg(ap, gauge_t);
2135 vl = plugin_value_list_clone(template);
2136 /* plugin_value_list_clone makes sure vl->time is set to non-zero. */
2137 if (store_percentage)
2138 sstrncpy(vl->type, "percent", sizeof(vl->type));
2140 va_start(ap, store_type);
2145 /* Set the type instance. */
2146 name = va_arg(ap, char const *);
2149 sstrncpy(vl->type_instance, name, sizeof(vl->type_instance));
2151 /* Set the value. */
2152 switch (store_type) {
2154 vl->values[0].gauge = va_arg(ap, gauge_t);
2155 if (store_percentage)
2156 vl->values[0].gauge *= sum ? (100.0 / sum) : NAN;
2158 case DS_TYPE_ABSOLUTE:
2159 vl->values[0].absolute = va_arg(ap, absolute_t);
2161 case DS_TYPE_COUNTER:
2162 vl->values[0].counter = va_arg(ap, counter_t);
2164 case DS_TYPE_DERIVE:
2165 vl->values[0].derive = va_arg(ap, derive_t);
2168 ERROR("plugin_dispatch_multivalue: given store_type is incorrect.");
2172 status = plugin_write_enqueue(vl);
2178 plugin_value_list_free(vl);
2180 } /* }}} int plugin_dispatch_multivalue */
2182 EXPORT int plugin_dispatch_notification(const notification_t *notif) {
2184 /* Possible TODO: Add flap detection here */
2186 DEBUG("plugin_dispatch_notification: severity = %i; message = %s; "
2187 "time = %.3f; host = %s;",
2188 notif->severity, notif->message, CDTIME_T_TO_DOUBLE(notif->time),
2191 /* Nobody cares for notifications */
2192 if (list_notification == NULL)
2195 le = llist_head(list_notification);
2196 while (le != NULL) {
2197 callback_func_t *cf;
2198 plugin_notification_cb callback;
2201 /* do not switch plugin context; rather keep the context
2202 * (interval) information of the calling plugin */
2205 callback = cf->cf_callback;
2206 status = (*callback)(notif, &cf->cf_udata);
2208 WARNING("plugin_dispatch_notification: Notification "
2209 "callback %s returned %i.",
2217 } /* int plugin_dispatch_notification */
2219 EXPORT void plugin_log(int level, const char *format, ...) {
2225 if (level >= LOG_DEBUG)
2229 va_start(ap, format);
2230 vsnprintf(msg, sizeof(msg), format, ap);
2231 msg[sizeof(msg) - 1] = '\0';
2234 if (list_log == NULL) {
2235 fprintf(stderr, "%s\n", msg);
2239 le = llist_head(list_log);
2240 while (le != NULL) {
2241 callback_func_t *cf;
2242 plugin_log_cb callback;
2245 callback = cf->cf_callback;
2247 /* do not switch plugin context; rather keep the context
2248 * (interval) information of the calling plugin */
2250 (*callback)(level, msg, &cf->cf_udata);
2254 } /* void plugin_log */
2256 void daemon_log(int level, const char *format, ...) {
2257 char msg[1024] = ""; // Size inherits from plugin_log()
2259 char const *name = plugin_get_ctx().name;
2264 va_start(ap, format);
2265 vsnprintf(msg, sizeof(msg), format, ap);
2268 plugin_log(level, "%s plugin: %s", name, msg);
2269 } /* void daemon_log */
2271 int parse_log_severity(const char *severity) {
2274 if ((0 == strcasecmp(severity, "emerg")) ||
2275 (0 == strcasecmp(severity, "alert")) ||
2276 (0 == strcasecmp(severity, "crit")) || (0 == strcasecmp(severity, "err")))
2277 log_level = LOG_ERR;
2278 else if (0 == strcasecmp(severity, "warning"))
2279 log_level = LOG_WARNING;
2280 else if (0 == strcasecmp(severity, "notice"))
2281 log_level = LOG_NOTICE;
2282 else if (0 == strcasecmp(severity, "info"))
2283 log_level = LOG_INFO;
2285 else if (0 == strcasecmp(severity, "debug"))
2286 log_level = LOG_DEBUG;
2287 #endif /* COLLECT_DEBUG */
2290 } /* int parse_log_severity */
2292 EXPORT int parse_notif_severity(const char *severity) {
2293 int notif_severity = -1;
2295 if (strcasecmp(severity, "FAILURE") == 0)
2296 notif_severity = NOTIF_FAILURE;
2297 else if (strcmp(severity, "OKAY") == 0)
2298 notif_severity = NOTIF_OKAY;
2299 else if ((strcmp(severity, "WARNING") == 0) ||
2300 (strcmp(severity, "WARN") == 0))
2301 notif_severity = NOTIF_WARNING;
2303 return notif_severity;
2304 } /* int parse_notif_severity */
2306 EXPORT const data_set_t *plugin_get_ds(const char *name) {
2309 if (data_sets == NULL) {
2310 P_ERROR("plugin_get_ds: No data sets are defined yet.");
2314 if (c_avl_get(data_sets, name, (void *)&ds) != 0) {
2315 DEBUG("No such dataset registered: %s", name);
2320 } /* data_set_t *plugin_get_ds */
2322 static int plugin_notification_meta_add(notification_t *n, const char *name,
2323 enum notification_meta_type_e type,
2324 const void *value) {
2325 notification_meta_t *meta;
2326 notification_meta_t *tail;
2328 if ((n == NULL) || (name == NULL) || (value == NULL)) {
2329 ERROR("plugin_notification_meta_add: A pointer is NULL!");
2333 meta = calloc(1, sizeof(*meta));
2335 ERROR("plugin_notification_meta_add: calloc failed.");
2339 sstrncpy(meta->name, name, sizeof(meta->name));
2343 case NM_TYPE_STRING: {
2344 meta->nm_value.nm_string = strdup((const char *)value);
2345 if (meta->nm_value.nm_string == NULL) {
2346 ERROR("plugin_notification_meta_add: strdup failed.");
2352 case NM_TYPE_SIGNED_INT: {
2353 meta->nm_value.nm_signed_int = *((int64_t *)value);
2356 case NM_TYPE_UNSIGNED_INT: {
2357 meta->nm_value.nm_unsigned_int = *((uint64_t *)value);
2360 case NM_TYPE_DOUBLE: {
2361 meta->nm_value.nm_double = *((double *)value);
2364 case NM_TYPE_BOOLEAN: {
2365 meta->nm_value.nm_boolean = *((bool *)value);
2369 ERROR("plugin_notification_meta_add: Unknown type: %i", type);
2373 } /* switch (type) */
2377 while ((tail != NULL) && (tail->next != NULL))
2386 } /* int plugin_notification_meta_add */
2388 int plugin_notification_meta_add_string(notification_t *n, const char *name,
2389 const char *value) {
2390 return plugin_notification_meta_add(n, name, NM_TYPE_STRING, value);
2393 int plugin_notification_meta_add_signed_int(notification_t *n, const char *name,
2395 return plugin_notification_meta_add(n, name, NM_TYPE_SIGNED_INT, &value);
2398 int plugin_notification_meta_add_unsigned_int(notification_t *n,
2401 return plugin_notification_meta_add(n, name, NM_TYPE_UNSIGNED_INT, &value);
2404 int plugin_notification_meta_add_double(notification_t *n, const char *name,
2406 return plugin_notification_meta_add(n, name, NM_TYPE_DOUBLE, &value);
2409 int plugin_notification_meta_add_boolean(notification_t *n, const char *name,
2411 return plugin_notification_meta_add(n, name, NM_TYPE_BOOLEAN, &value);
2414 int plugin_notification_meta_copy(notification_t *dst,
2415 const notification_t *src) {
2416 assert(dst != NULL);
2417 assert(src != NULL);
2419 assert((src->meta == NULL) || (src->meta != dst->meta));
2421 for (notification_meta_t *meta = src->meta; meta != NULL; meta = meta->next) {
2422 if (meta->type == NM_TYPE_STRING)
2423 plugin_notification_meta_add_string(dst, meta->name,
2424 meta->nm_value.nm_string);
2425 else if (meta->type == NM_TYPE_SIGNED_INT)
2426 plugin_notification_meta_add_signed_int(dst, meta->name,
2427 meta->nm_value.nm_signed_int);
2428 else if (meta->type == NM_TYPE_UNSIGNED_INT)
2429 plugin_notification_meta_add_unsigned_int(dst, meta->name,
2430 meta->nm_value.nm_unsigned_int);
2431 else if (meta->type == NM_TYPE_DOUBLE)
2432 plugin_notification_meta_add_double(dst, meta->name,
2433 meta->nm_value.nm_double);
2434 else if (meta->type == NM_TYPE_BOOLEAN)
2435 plugin_notification_meta_add_boolean(dst, meta->name,
2436 meta->nm_value.nm_boolean);
2440 } /* int plugin_notification_meta_copy */
2442 int plugin_notification_meta_free(notification_meta_t *n) {
2443 notification_meta_t *this;
2444 notification_meta_t *next;
2447 ERROR("plugin_notification_meta_free: n == NULL!");
2452 while (this != NULL) {
2455 if (this->type == NM_TYPE_STRING) {
2456 /* Assign to a temporary variable to work around nm_string's const
2458 void *tmp = (void *)this->nm_value.nm_string;
2461 this->nm_value.nm_string = NULL;
2469 } /* int plugin_notification_meta_free */
2471 static void plugin_ctx_destructor(void *ctx) {
2473 } /* void plugin_ctx_destructor */
2475 static plugin_ctx_t ctx_init = {/* interval = */ 0};
2477 static plugin_ctx_t *plugin_ctx_create(void) {
2480 ctx = malloc(sizeof(*ctx));
2482 ERROR("Failed to allocate plugin context: %s", STRERRNO);
2487 assert(plugin_ctx_key_initialized);
2488 pthread_setspecific(plugin_ctx_key, ctx);
2489 DEBUG("Created new plugin context.");
2491 } /* int plugin_ctx_create */
2493 EXPORT void plugin_init_ctx(void) {
2494 pthread_key_create(&plugin_ctx_key, plugin_ctx_destructor);
2495 plugin_ctx_key_initialized = true;
2496 } /* void plugin_init_ctx */
2498 EXPORT plugin_ctx_t plugin_get_ctx(void) {
2501 assert(plugin_ctx_key_initialized);
2502 ctx = pthread_getspecific(plugin_ctx_key);
2505 ctx = plugin_ctx_create();
2506 /* this must no happen -- exit() instead? */
2512 } /* plugin_ctx_t plugin_get_ctx */
2514 EXPORT plugin_ctx_t plugin_set_ctx(plugin_ctx_t ctx) {
2518 assert(plugin_ctx_key_initialized);
2519 c = pthread_getspecific(plugin_ctx_key);
2522 c = plugin_ctx_create();
2523 /* this must no happen -- exit() instead? */
2532 } /* void plugin_set_ctx */
2534 EXPORT cdtime_t plugin_get_interval(void) {
2537 interval = plugin_get_ctx().interval;
2541 P_ERROR("plugin_get_interval: Unable to determine Interval from context.");
2543 return cf_get_default_interval();
2544 } /* cdtime_t plugin_get_interval */
2548 void *(*start_routine)(void *);
2552 static void *plugin_thread_start(void *arg) {
2553 plugin_thread_t *plugin_thread = arg;
2555 void *(*start_routine)(void *) = plugin_thread->start_routine;
2556 void *plugin_arg = plugin_thread->arg;
2558 plugin_set_ctx(plugin_thread->ctx);
2560 sfree(plugin_thread);
2562 return start_routine(plugin_arg);
2563 } /* void *plugin_thread_start */
2565 int plugin_thread_create(pthread_t *thread, const pthread_attr_t *attr,
2566 void *(*start_routine)(void *), void *arg,
2568 plugin_thread_t *plugin_thread;
2570 plugin_thread = malloc(sizeof(*plugin_thread));
2571 if (plugin_thread == NULL)
2574 plugin_thread->ctx = plugin_get_ctx();
2575 plugin_thread->start_routine = start_routine;
2576 plugin_thread->arg = arg;
2578 int ret = pthread_create(thread, attr, plugin_thread_start, plugin_thread);
2580 sfree(plugin_thread);
2585 set_thread_name(*thread, name);
2588 } /* int plugin_thread_create */