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 */
35 #include "configfile.h"
36 #include "filter_chain.h"
37 #include "utils_avltree.h"
38 #include "utils_cache.h"
39 #include "utils_complain.h"
40 #include "utils_llist.h"
41 #include "utils_heap.h"
42 #include "utils_time.h"
43 #include "utils_random.h"
50 struct callback_func_s
56 typedef struct callback_func_s callback_func_t;
60 #define RF_REMOVE 65535
63 /* `read_func_t' "inherits" from `callback_func_t'.
64 * The `rf_super' member MUST be the first one in this structure! */
65 #define rf_callback rf_super.cf_callback
66 #define rf_udata rf_super.cf_udata
67 #define rf_ctx rf_super.cf_ctx
68 callback_func_t rf_super;
69 char rf_group[DATA_MAX_NAME_LEN];
73 cdtime_t rf_effective_interval;
74 cdtime_t rf_next_read;
76 typedef struct read_func_s read_func_t;
79 typedef struct write_queue_s write_queue_t;
87 struct flush_callback_s {
91 typedef struct flush_callback_s flush_callback_t;
96 static c_avl_tree_t *plugins_loaded = NULL;
98 static llist_t *list_init;
99 static llist_t *list_write;
100 static llist_t *list_flush;
101 static llist_t *list_missing;
102 static llist_t *list_shutdown;
103 static llist_t *list_log;
104 static llist_t *list_notification;
106 static fc_chain_t *pre_cache_chain = NULL;
107 static fc_chain_t *post_cache_chain = NULL;
109 static c_avl_tree_t *data_sets;
111 static char *plugindir = NULL;
113 #ifndef DEFAULT_MAX_READ_INTERVAL
114 # define DEFAULT_MAX_READ_INTERVAL TIME_T_TO_CDTIME_T_STATIC (86400)
116 static c_heap_t *read_heap = NULL;
117 static llist_t *read_list;
118 static int read_loop = 1;
119 static pthread_mutex_t read_lock = PTHREAD_MUTEX_INITIALIZER;
120 static pthread_cond_t read_cond = PTHREAD_COND_INITIALIZER;
121 static pthread_t *read_threads = NULL;
122 static int read_threads_num = 0;
123 static cdtime_t max_read_interval = DEFAULT_MAX_READ_INTERVAL;
125 static write_queue_t *write_queue_head;
126 static write_queue_t *write_queue_tail;
127 static long write_queue_length = 0;
128 static _Bool write_loop = 1;
129 static pthread_mutex_t write_lock = PTHREAD_MUTEX_INITIALIZER;
130 static pthread_cond_t write_cond = PTHREAD_COND_INITIALIZER;
131 static pthread_t *write_threads = NULL;
132 static size_t write_threads_num = 0;
134 static pthread_key_t plugin_ctx_key;
135 static _Bool plugin_ctx_key_initialized = 0;
137 static long write_limit_high = 0;
138 static long write_limit_low = 0;
140 static derive_t stats_values_dropped = 0;
141 static _Bool record_statistics = 0;
146 static int plugin_dispatch_values_internal (value_list_t *vl);
148 static const char *plugin_get_dir (void)
150 if (plugindir == NULL)
156 static void plugin_update_internal_statistics (void) { /* {{{ */
158 gauge_t copy_write_queue_length = (gauge_t) write_queue_length;
160 /* Initialize `vl' */
161 value_list_t vl = VALUE_LIST_INIT;
162 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
163 sstrncpy (vl.plugin, "collectd", sizeof (vl.plugin));
166 sstrncpy (vl.plugin_instance, "write_queue",
167 sizeof (vl.plugin_instance));
169 /* Write queue : queue length */
170 vl.values = &(value_t) { .gauge = copy_write_queue_length };
172 sstrncpy (vl.type, "queue_length", sizeof (vl.type));
173 vl.type_instance[0] = 0;
174 plugin_dispatch_values (&vl);
176 /* Write queue : Values dropped (queue length > low limit) */
177 vl.values = &(value_t) { .gauge = (gauge_t) stats_values_dropped };
179 sstrncpy (vl.type, "derive", sizeof (vl.type));
180 sstrncpy (vl.type_instance, "dropped", sizeof (vl.type_instance));
181 plugin_dispatch_values (&vl);
184 sstrncpy (vl.plugin_instance, "cache",
185 sizeof (vl.plugin_instance));
187 /* Cache : Nb entry in cache tree */
188 vl.values = &(value_t) { .gauge = (gauge_t) uc_get_size() };
190 sstrncpy (vl.type, "cache_size", sizeof (vl.type));
191 vl.type_instance[0] = 0;
192 plugin_dispatch_values (&vl);
195 } /* }}} void plugin_update_internal_statistics */
197 static void destroy_callback (callback_func_t *cf) /* {{{ */
202 if ((cf->cf_udata.data != NULL) && (cf->cf_udata.free_func != NULL))
204 cf->cf_udata.free_func (cf->cf_udata.data);
205 cf->cf_udata.data = NULL;
206 cf->cf_udata.free_func = NULL;
209 } /* }}} void destroy_callback */
211 static void destroy_all_callbacks (llist_t **list) /* {{{ */
218 le = llist_head (*list);
226 destroy_callback (le->value);
232 llist_destroy (*list);
234 } /* }}} void destroy_all_callbacks */
236 static void destroy_read_heap (void) /* {{{ */
238 if (read_heap == NULL)
245 rf = c_heap_get_root (read_heap);
249 destroy_callback ((callback_func_t *) rf);
252 c_heap_destroy (read_heap);
254 } /* }}} void destroy_read_heap */
256 static int register_callback (llist_t **list, /* {{{ */
257 const char *name, callback_func_t *cf)
264 *list = llist_create ();
267 ERROR ("plugin: register_callback: "
268 "llist_create failed.");
269 destroy_callback (cf);
277 ERROR ("plugin: register_callback: strdup failed.");
278 destroy_callback (cf);
282 le = llist_search (*list, name);
285 le = llentry_create (key, cf);
288 ERROR ("plugin: register_callback: "
289 "llentry_create failed.");
291 destroy_callback (cf);
295 llist_append (*list, le);
299 callback_func_t *old_cf;
304 WARNING ("plugin: register_callback: "
305 "a callback named `%s' already exists - "
306 "overwriting the old entry!", name);
308 destroy_callback (old_cf);
313 } /* }}} int register_callback */
315 static void log_list_callbacks (llist_t **list, /* {{{ */
325 n = llist_size(*list);
328 INFO("%s [none]", comment);
332 keys = calloc(n, sizeof(char*));
336 ERROR("%s: failed to allocate memory for list of callbacks",
342 for (le = llist_head (*list), i = 0, len = 0;
347 len += strlen(le->key) + 6;
349 str = malloc(len + 10);
352 ERROR("%s: failed to allocate memory for list of callbacks",
358 strjoin(str, len, keys, n, "', '");
359 INFO("%s ['%s']", comment, str);
363 } /* }}} void log_list_callbacks */
365 static int create_register_callback (llist_t **list, /* {{{ */
366 const char *name, void *callback, user_data_t const *ud)
370 cf = calloc (1, sizeof (*cf));
373 ERROR ("plugin: create_register_callback: calloc failed.");
377 cf->cf_callback = callback;
380 cf->cf_udata.data = NULL;
381 cf->cf_udata.free_func = NULL;
388 cf->cf_ctx = plugin_get_ctx ();
390 return (register_callback (list, name, cf));
391 } /* }}} int create_register_callback */
393 static int plugin_unregister (llist_t *list, const char *name) /* {{{ */
400 e = llist_search (list, name);
404 llist_remove (list, e);
407 destroy_callback (e->value);
412 } /* }}} int plugin_unregister */
415 * (Try to) load the shared object `file'. Won't complain if it isn't a shared
416 * object, but it will bitch about a shared object not having a
417 * ``module_register'' symbol..
419 static int plugin_load_file (char *file, uint32_t flags)
422 void (*reg_handle) (void);
425 lt_dlerror (); /* clear errors */
427 #if LIBTOOL_VERSION == 2
428 if (flags & PLUGIN_FLAGS_GLOBAL) {
430 lt_dladvise_init(&advise);
431 lt_dladvise_global(&advise);
432 dlh = lt_dlopenadvise(file, advise);
433 lt_dladvise_destroy(&advise);
435 dlh = lt_dlopen (file);
437 #else /* if LIBTOOL_VERSION == 1 */
438 if (flags & PLUGIN_FLAGS_GLOBAL)
439 WARNING ("plugin_load_file: The global flag is not supported, "
440 "libtool 2 is required for this.");
441 dlh = lt_dlopen (file);
446 char errbuf[1024] = "";
448 ssnprintf (errbuf, sizeof (errbuf),
449 "lt_dlopen (\"%s\") failed: %s. "
450 "The most common cause for this problem is "
451 "missing dependencies. Use ldd(1) to check "
452 "the dependencies of the plugin "
454 file, lt_dlerror ());
456 ERROR ("%s", errbuf);
457 /* Make sure this is printed to STDERR in any case, but also
458 * make sure it's printed only once. */
459 if (list_log != NULL)
460 fprintf (stderr, "ERROR: %s\n", errbuf);
465 if ((reg_handle = (void (*) (void)) lt_dlsym (dlh, "module_register")) == NULL)
467 WARNING ("Couldn't find symbol \"module_register\" in \"%s\": %s\n",
468 file, lt_dlerror ());
478 static void *plugin_read_thread (void __attribute__((unused)) *args)
480 while (read_loop != 0)
483 plugin_ctx_t old_ctx;
491 /* Get the read function that needs to be read next.
492 * We don't need to hold "read_lock" for the heap, but we need
493 * to call c_heap_get_root() and pthread_cond_wait() in the
494 * same protected block. */
495 pthread_mutex_lock (&read_lock);
496 rf = c_heap_get_root (read_heap);
499 pthread_cond_wait (&read_cond, &read_lock);
500 pthread_mutex_unlock (&read_lock);
503 pthread_mutex_unlock (&read_lock);
505 if (rf->rf_interval == 0)
507 /* this should not happen, because the interval is set
508 * for each plugin when loading it
509 * XXX: issue a warning? */
510 rf->rf_interval = plugin_get_interval ();
511 rf->rf_effective_interval = rf->rf_interval;
513 rf->rf_next_read = cdtime ();
516 /* sleep until this entry is due,
517 * using pthread_cond_timedwait */
518 pthread_mutex_lock (&read_lock);
519 /* In pthread_cond_timedwait, spurious wakeups are possible
520 * (and really happen, at least on NetBSD with > 1 CPU), thus
521 * we need to re-evaluate the condition every time
522 * pthread_cond_timedwait returns. */
524 while ((read_loop != 0)
525 && (cdtime () < rf->rf_next_read)
528 rc = pthread_cond_timedwait (&read_cond, &read_lock,
529 &CDTIME_T_TO_TIMESPEC (rf->rf_next_read));
532 /* Must hold `read_lock' when accessing `rf->rf_type'. */
533 rf_type = rf->rf_type;
534 pthread_mutex_unlock (&read_lock);
536 /* Check if we're supposed to stop.. This may have interrupted
540 /* Insert `rf' again, so it can be free'd correctly */
541 c_heap_insert (read_heap, rf);
545 /* The entry has been marked for deletion. The linked list
546 * entry has already been removed by `plugin_unregister_read'.
547 * All we have to do here is free the `read_func_t' and
549 if (rf_type == RF_REMOVE)
551 DEBUG ("plugin_read_thread: Destroying the `%s' "
552 "callback.", rf->rf_name);
554 destroy_callback ((callback_func_t *) rf);
559 DEBUG ("plugin_read_thread: Handling `%s'.", rf->rf_name);
563 old_ctx = plugin_set_ctx (rf->rf_ctx);
565 if (rf_type == RF_SIMPLE)
567 int (*callback) (void);
569 callback = rf->rf_callback;
570 status = (*callback) ();
574 plugin_read_cb callback;
576 assert (rf_type == RF_COMPLEX);
578 callback = rf->rf_callback;
579 status = (*callback) (&rf->rf_udata);
582 plugin_set_ctx (old_ctx);
584 /* If the function signals failure, we will increase the
585 * intervals in which it will be called. */
588 rf->rf_effective_interval *= 2;
589 if (rf->rf_effective_interval > max_read_interval)
590 rf->rf_effective_interval = max_read_interval;
592 NOTICE ("read-function of plugin `%s' failed. "
593 "Will suspend it for %.3f seconds.",
595 CDTIME_T_TO_DOUBLE (rf->rf_effective_interval));
599 /* Success: Restore the interval, if it was changed. */
600 rf->rf_effective_interval = rf->rf_interval;
603 /* update the ``next read due'' field */
606 /* calculate the time spent in the read function */
607 elapsed = (now - start);
609 if (elapsed > rf->rf_effective_interval)
610 WARNING ("plugin_read_thread: read-function of the `%s' plugin took %.3f "
611 "seconds, which is above its read interval (%.3f seconds). You might "
612 "want to adjust the `Interval' or `ReadThreads' settings.",
613 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed),
614 CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
616 DEBUG ("plugin_read_thread: read-function of the `%s' plugin took "
618 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed));
620 DEBUG ("plugin_read_thread: Effective interval of the "
621 "`%s' plugin is %.3f seconds.",
623 CDTIME_T_TO_DOUBLE (rf->rf_effective_interval));
625 /* Calculate the next (absolute) time at which this function
626 * should be called. */
627 rf->rf_next_read += rf->rf_effective_interval;
629 /* Check, if `rf_next_read' is in the past. */
630 if (rf->rf_next_read < now)
632 /* `rf_next_read' is in the past. Insert `now'
633 * so this value doesn't trail off into the
635 rf->rf_next_read = now;
638 DEBUG ("plugin_read_thread: Next read of the `%s' plugin at %.3f.",
640 CDTIME_T_TO_DOUBLE (rf->rf_next_read));
642 /* Re-insert this read function into the heap again. */
643 c_heap_insert (read_heap, rf);
644 } /* while (read_loop) */
648 } /* void *plugin_read_thread */
650 static void start_read_threads (int num)
652 if (read_threads != NULL)
655 read_threads = (pthread_t *) calloc (num, sizeof (pthread_t));
656 if (read_threads == NULL)
658 ERROR ("plugin: start_read_threads: calloc failed.");
662 read_threads_num = 0;
663 for (int i = 0; i < num; i++)
665 if (pthread_create (read_threads + read_threads_num, NULL,
666 plugin_read_thread, NULL) == 0)
668 #if defined(HAVE_PTHREAD_SETNAME_NP) || defined(HAVE_PTHREAD_SET_NAME_NP)
669 char thread_name[16];
670 sstrncpy (thread_name, "plugin reader", sizeof(thread_name));
671 # if defined(HAVE_PTHREAD_SETNAME_NP)
672 pthread_setname_np (*(read_threads + read_threads_num),
674 # elif defined(HAVE_PTHREAD_SET_NAME_NP)
675 pthread_set_name_np (*(read_threads + read_threads_num),
683 ERROR ("plugin: start_read_threads: pthread_create failed.");
687 } /* void start_read_threads */
689 static void stop_read_threads (void)
691 if (read_threads == NULL)
694 INFO ("collectd: Stopping %i read threads.", read_threads_num);
696 pthread_mutex_lock (&read_lock);
698 DEBUG ("plugin: stop_read_threads: Signalling `read_cond'");
699 pthread_cond_broadcast (&read_cond);
700 pthread_mutex_unlock (&read_lock);
702 for (int i = 0; i < read_threads_num; i++)
704 if (pthread_join (read_threads[i], NULL) != 0)
706 ERROR ("plugin: stop_read_threads: pthread_join failed.");
708 read_threads[i] = (pthread_t) 0;
710 sfree (read_threads);
711 read_threads_num = 0;
712 } /* void stop_read_threads */
714 static void plugin_value_list_free (value_list_t *vl) /* {{{ */
719 meta_data_destroy (vl->meta);
722 } /* }}} void plugin_value_list_free */
724 static value_list_t *plugin_value_list_clone (value_list_t const *vl_orig) /* {{{ */
731 vl = malloc (sizeof (*vl));
734 memcpy (vl, vl_orig, sizeof (*vl));
736 if (vl->host[0] == 0)
737 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
739 vl->values = calloc (vl_orig->values_len, sizeof (*vl->values));
740 if (vl->values == NULL)
742 plugin_value_list_free (vl);
745 memcpy (vl->values, vl_orig->values,
746 vl_orig->values_len * sizeof (*vl->values));
748 vl->meta = meta_data_clone (vl->meta);
749 if ((vl_orig->meta != NULL) && (vl->meta == NULL))
751 plugin_value_list_free (vl);
756 vl->time = cdtime ();
758 /* Fill in the interval from the thread context, if it is zero. */
759 if (vl->interval == 0)
761 plugin_ctx_t ctx = plugin_get_ctx ();
763 if (ctx.interval != 0)
764 vl->interval = ctx.interval;
767 char name[6 * DATA_MAX_NAME_LEN];
768 FORMAT_VL (name, sizeof (name), vl);
769 ERROR ("plugin_value_list_clone: Unable to determine "
770 "interval from context for "
771 "value list \"%s\". "
772 "This indicates a broken plugin. "
773 "Please report this problem to the "
774 "collectd mailing list or at "
775 "<http://collectd.org/bugs/>.", name);
776 vl->interval = cf_get_default_interval ();
781 } /* }}} value_list_t *plugin_value_list_clone */
783 static int plugin_write_enqueue (value_list_t const *vl) /* {{{ */
787 q = malloc (sizeof (*q));
792 q->vl = plugin_value_list_clone (vl);
799 /* Store context of caller (read plugin); otherwise, it would not be
800 * available to the write plugins when actually dispatching the
801 * value-list later on. */
802 q->ctx = plugin_get_ctx ();
804 pthread_mutex_lock (&write_lock);
806 if (write_queue_tail == NULL)
808 write_queue_head = q;
809 write_queue_tail = q;
810 write_queue_length = 1;
814 write_queue_tail->next = q;
815 write_queue_tail = q;
816 write_queue_length += 1;
819 pthread_cond_signal (&write_cond);
820 pthread_mutex_unlock (&write_lock);
823 } /* }}} int plugin_write_enqueue */
825 static value_list_t *plugin_write_dequeue (void) /* {{{ */
830 pthread_mutex_lock (&write_lock);
832 while (write_loop && (write_queue_head == NULL))
833 pthread_cond_wait (&write_cond, &write_lock);
835 if (write_queue_head == NULL)
837 pthread_mutex_unlock (&write_lock);
841 q = write_queue_head;
842 write_queue_head = q->next;
843 write_queue_length -= 1;
844 if (write_queue_head == NULL) {
845 write_queue_tail = NULL;
846 assert(0 == write_queue_length);
849 pthread_mutex_unlock (&write_lock);
851 (void) plugin_set_ctx (q->ctx);
856 } /* }}} value_list_t *plugin_write_dequeue */
858 static void *plugin_write_thread (void __attribute__((unused)) *args) /* {{{ */
862 value_list_t *vl = plugin_write_dequeue ();
866 plugin_dispatch_values_internal (vl);
868 plugin_value_list_free (vl);
873 } /* }}} void *plugin_write_thread */
875 static void start_write_threads (size_t num) /* {{{ */
877 if (write_threads != NULL)
880 write_threads = (pthread_t *) calloc (num, sizeof (pthread_t));
881 if (write_threads == NULL)
883 ERROR ("plugin: start_write_threads: calloc failed.");
887 write_threads_num = 0;
888 for (size_t i = 0; i < num; i++)
892 status = pthread_create (write_threads + write_threads_num,
899 ERROR ("plugin: start_write_threads: pthread_create failed "
900 "with status %i (%s).", status,
901 sstrerror (status, errbuf, sizeof (errbuf)));
904 #if defined(HAVE_PTHREAD_SETNAME_NP) || defined(HAVE_PTHREAD_SET_NAME_NP)
905 char thread_name[16];
906 sstrncpy (thread_name, "plugin writer", sizeof(thread_name));
907 # if defined(HAVE_PTHREAD_SETNAME_NP)
908 pthread_setname_np (*(write_threads + write_threads_num),
910 # elif defined(HAVE_PTHREAD_SET_NAME_NP)
911 pthread_set_name_np (*(write_threads + write_threads_num),
918 } /* }}} void start_write_threads */
920 static void stop_write_threads (void) /* {{{ */
925 if (write_threads == NULL)
928 INFO ("collectd: Stopping %zu write threads.", write_threads_num);
930 pthread_mutex_lock (&write_lock);
932 DEBUG ("plugin: stop_write_threads: Signalling `write_cond'");
933 pthread_cond_broadcast (&write_cond);
934 pthread_mutex_unlock (&write_lock);
936 for (i = 0; i < write_threads_num; i++)
938 if (pthread_join (write_threads[i], NULL) != 0)
940 ERROR ("plugin: stop_write_threads: pthread_join failed.");
942 write_threads[i] = (pthread_t) 0;
944 sfree (write_threads);
945 write_threads_num = 0;
947 pthread_mutex_lock (&write_lock);
949 for (q = write_queue_head; q != NULL; )
951 write_queue_t *q1 = q;
952 plugin_value_list_free (q->vl);
957 write_queue_head = NULL;
958 write_queue_tail = NULL;
959 write_queue_length = 0;
960 pthread_mutex_unlock (&write_lock);
964 WARNING ("plugin: %zu value list%s left after shutting down "
965 "the write threads.",
966 i, (i == 1) ? " was" : "s were");
968 } /* }}} void stop_write_threads */
973 void plugin_set_dir (const char *dir)
983 plugindir = strdup (dir);
984 if (plugindir == NULL)
985 ERROR ("plugin_set_dir: strdup(\"%s\") failed", dir);
988 static _Bool plugin_is_loaded (char const *name)
992 if (plugins_loaded == NULL)
993 plugins_loaded = c_avl_create ((int (*) (const void *, const void *)) strcasecmp);
994 assert (plugins_loaded != NULL);
996 status = c_avl_get (plugins_loaded, name, /* ret_value = */ NULL);
997 return (status == 0);
1000 static int plugin_mark_loaded (char const *name)
1005 name_copy = strdup (name);
1006 if (name_copy == NULL)
1009 status = c_avl_insert (plugins_loaded,
1010 /* key = */ name_copy, /* value = */ NULL);
1014 static void plugin_free_loaded (void)
1019 if (plugins_loaded == NULL)
1022 while (c_avl_pick (plugins_loaded, &key, &value) == 0)
1025 assert (value == NULL);
1028 c_avl_destroy (plugins_loaded);
1029 plugins_loaded = NULL;
1033 int plugin_load (char const *plugin_name, uint32_t flags)
1037 char filename[BUFSIZE] = "";
1038 char typename[BUFSIZE];
1040 struct stat statbuf;
1044 if (plugin_name == NULL)
1047 /* Check if plugin is already loaded and don't do anything in this
1049 if (plugin_is_loaded (plugin_name))
1052 dir = plugin_get_dir ();
1056 * XXX: Magic at work:
1058 * Some of the language bindings, for example the Python and Perl
1059 * plugins, need to be able to export symbols to the scripts they run.
1060 * For this to happen, the "Globals" flag needs to be set.
1061 * Unfortunately, this technical detail is hard to explain to the
1062 * average user and she shouldn't have to worry about this, ideally.
1063 * So in order to save everyone's sanity use a different default for a
1064 * handful of special plugins. --octo
1066 if ((strcasecmp ("perl", plugin_name) == 0)
1067 || (strcasecmp ("python", plugin_name) == 0))
1068 flags |= PLUGIN_FLAGS_GLOBAL;
1070 /* `cpu' should not match `cpufreq'. To solve this we add `.so' to the
1071 * type when matching the filename */
1072 status = ssnprintf (typename, sizeof (typename), "%s.so", plugin_name);
1073 if ((status < 0) || ((size_t) status >= sizeof (typename)))
1075 WARNING ("plugin_load: Filename too long: \"%s.so\"", plugin_name);
1079 if ((dh = opendir (dir)) == NULL)
1082 ERROR ("plugin_load: opendir (%s) failed: %s", dir,
1083 sstrerror (errno, errbuf, sizeof (errbuf)));
1087 while ((de = readdir (dh)) != NULL)
1089 if (strcasecmp (de->d_name, typename))
1092 status = ssnprintf (filename, sizeof (filename),
1093 "%s/%s", dir, de->d_name);
1094 if ((status < 0) || ((size_t) status >= sizeof (filename)))
1096 WARNING ("plugin_load: Filename too long: \"%s/%s\"",
1101 if (lstat (filename, &statbuf) == -1)
1104 WARNING ("plugin_load: stat (\"%s\") failed: %s",
1106 sstrerror (errno, errbuf, sizeof (errbuf)));
1109 else if (!S_ISREG (statbuf.st_mode))
1111 /* don't follow symlinks */
1112 WARNING ("plugin_load: %s is not a regular file.",
1117 status = plugin_load_file (filename, flags);
1121 plugin_mark_loaded (plugin_name);
1123 INFO ("plugin_load: plugin \"%s\" successfully loaded.", plugin_name);
1128 ERROR ("plugin_load: Load plugin \"%s\" failed with "
1129 "status %i.", plugin_name, status);
1135 if (filename[0] == 0)
1136 ERROR ("plugin_load: Could not find plugin \"%s\" in %s",
1143 * The `register_*' functions follow
1145 int plugin_register_config (const char *name,
1146 int (*callback) (const char *key, const char *val),
1147 const char **keys, int keys_num)
1149 cf_register (name, callback, keys, keys_num);
1151 } /* int plugin_register_config */
1153 int plugin_register_complex_config (const char *type,
1154 int (*callback) (oconfig_item_t *))
1156 return (cf_register_complex (type, callback));
1157 } /* int plugin_register_complex_config */
1159 int plugin_register_init (const char *name,
1160 int (*callback) (void))
1162 return (create_register_callback (&list_init, name, (void *) callback,
1163 /* user_data = */ NULL));
1164 } /* plugin_register_init */
1166 static int plugin_compare_read_func (const void *arg0, const void *arg1)
1168 const read_func_t *rf0;
1169 const read_func_t *rf1;
1174 if (rf0->rf_next_read < rf1->rf_next_read)
1176 else if (rf0->rf_next_read > rf1->rf_next_read)
1180 } /* int plugin_compare_read_func */
1182 /* Add a read function to both, the heap and a linked list. The linked list if
1183 * used to look-up read functions, especially for the remove function. The heap
1184 * is used to determine which plugin to read next. */
1185 static int plugin_insert_read (read_func_t *rf)
1190 rf->rf_next_read = cdtime ();
1191 rf->rf_effective_interval = rf->rf_interval;
1193 pthread_mutex_lock (&read_lock);
1195 if (read_list == NULL)
1197 read_list = llist_create ();
1198 if (read_list == NULL)
1200 pthread_mutex_unlock (&read_lock);
1201 ERROR ("plugin_insert_read: read_list failed.");
1206 if (read_heap == NULL)
1208 read_heap = c_heap_create (plugin_compare_read_func);
1209 if (read_heap == NULL)
1211 pthread_mutex_unlock (&read_lock);
1212 ERROR ("plugin_insert_read: c_heap_create failed.");
1217 le = llist_search (read_list, rf->rf_name);
1220 pthread_mutex_unlock (&read_lock);
1221 WARNING ("The read function \"%s\" is already registered. "
1222 "Check for duplicate \"LoadPlugin\" lines "
1223 "in your configuration!",
1228 le = llentry_create (rf->rf_name, rf);
1231 pthread_mutex_unlock (&read_lock);
1232 ERROR ("plugin_insert_read: llentry_create failed.");
1236 status = c_heap_insert (read_heap, rf);
1239 pthread_mutex_unlock (&read_lock);
1240 ERROR ("plugin_insert_read: c_heap_insert failed.");
1241 llentry_destroy (le);
1245 /* This does not fail. */
1246 llist_append (read_list, le);
1248 /* Wake up all the read threads. */
1249 pthread_cond_broadcast (&read_cond);
1250 pthread_mutex_unlock (&read_lock);
1252 } /* int plugin_insert_read */
1254 int plugin_register_read (const char *name,
1255 int (*callback) (void))
1260 rf = calloc (1, sizeof (*rf));
1263 ERROR ("plugin_register_read: calloc failed.");
1267 rf->rf_callback = (void *) callback;
1268 rf->rf_udata.data = NULL;
1269 rf->rf_udata.free_func = NULL;
1270 rf->rf_ctx = plugin_get_ctx ();
1271 rf->rf_group[0] = '\0';
1272 rf->rf_name = strdup (name);
1273 rf->rf_type = RF_SIMPLE;
1274 rf->rf_interval = plugin_get_interval ();
1276 status = plugin_insert_read (rf);
1278 sfree (rf->rf_name);
1283 } /* int plugin_register_read */
1285 int plugin_register_complex_read (const char *group, const char *name,
1286 plugin_read_cb callback,
1288 user_data_t const *user_data)
1293 rf = calloc (1,sizeof (*rf));
1296 ERROR ("plugin_register_complex_read: calloc failed.");
1300 rf->rf_callback = (void *) callback;
1302 sstrncpy (rf->rf_group, group, sizeof (rf->rf_group));
1304 rf->rf_group[0] = '\0';
1305 rf->rf_name = strdup (name);
1306 rf->rf_type = RF_COMPLEX;
1307 rf->rf_interval = (interval != 0) ? interval : plugin_get_interval ();
1310 if (user_data == NULL)
1312 rf->rf_udata.data = NULL;
1313 rf->rf_udata.free_func = NULL;
1317 rf->rf_udata = *user_data;
1320 rf->rf_ctx = plugin_get_ctx ();
1322 status = plugin_insert_read (rf);
1324 sfree (rf->rf_name);
1329 } /* int plugin_register_complex_read */
1331 int plugin_register_write (const char *name,
1332 plugin_write_cb callback, user_data_t const *ud)
1334 return (create_register_callback (&list_write, name,
1335 (void *) callback, ud));
1336 } /* int plugin_register_write */
1338 static int plugin_flush_timeout_callback (user_data_t *ud)
1340 flush_callback_t *cb = ud->data;
1342 return plugin_flush (cb->name, cb->timeout, /* identifier = */ NULL);
1343 } /* static int plugin_flush_callback */
1345 static void plugin_flush_timeout_callback_free (void *data)
1347 flush_callback_t *cb = data;
1349 if (cb == NULL) return;
1353 } /* static void plugin_flush_callback_free */
1355 static char *plugin_flush_callback_name (const char *name)
1357 const char *flush_prefix = "flush/";
1362 prefix_size = strlen(flush_prefix);
1363 name_size = strlen(name);
1365 flush_name = malloc (name_size + prefix_size + 1);
1366 if (flush_name == NULL)
1368 ERROR ("plugin_flush_callback_name: malloc failed.");
1372 sstrncpy (flush_name, flush_prefix, prefix_size + 1);
1373 sstrncpy (flush_name + prefix_size, name, name_size + 1);
1376 } /* static char *plugin_flush_callback_name */
1378 int plugin_register_flush (const char *name,
1379 plugin_flush_cb callback, user_data_t const *ud)
1382 plugin_ctx_t ctx = plugin_get_ctx ();
1384 status = create_register_callback (&list_flush, name,
1385 (void *) callback, ud);
1389 if (ctx.flush_interval != 0)
1392 flush_callback_t *cb;
1394 flush_name = plugin_flush_callback_name (name);
1395 if (flush_name == NULL)
1398 cb = malloc(sizeof (*cb));
1401 ERROR ("plugin_register_flush: malloc failed.");
1406 cb->name = strdup (name);
1407 if (cb->name == NULL)
1409 ERROR ("plugin_register_flush: strdup failed.");
1414 cb->timeout = ctx.flush_timeout;
1416 status = plugin_register_complex_read (
1417 /* group = */ "flush",
1418 /* name = */ flush_name,
1419 /* callback = */ plugin_flush_timeout_callback,
1420 /* interval = */ ctx.flush_interval,
1421 /* user data = */ &(user_data_t) {
1423 .free_func = plugin_flush_timeout_callback_free,
1436 } /* int plugin_register_flush */
1438 int plugin_register_missing (const char *name,
1439 plugin_missing_cb callback, user_data_t const *ud)
1441 return (create_register_callback (&list_missing, name,
1442 (void *) callback, ud));
1443 } /* int plugin_register_missing */
1445 int plugin_register_shutdown (const char *name,
1446 int (*callback) (void))
1448 return (create_register_callback (&list_shutdown, name,
1449 (void *) callback, /* user_data = */ NULL));
1450 } /* int plugin_register_shutdown */
1452 static void plugin_free_data_sets (void)
1457 if (data_sets == NULL)
1460 while (c_avl_pick (data_sets, &key, &value) == 0)
1462 data_set_t *ds = value;
1463 /* key is a pointer to ds->type */
1469 c_avl_destroy (data_sets);
1471 } /* void plugin_free_data_sets */
1473 int plugin_register_data_set (const data_set_t *ds)
1475 data_set_t *ds_copy;
1477 if ((data_sets != NULL)
1478 && (c_avl_get (data_sets, ds->type, NULL) == 0))
1480 NOTICE ("Replacing DS `%s' with another version.", ds->type);
1481 plugin_unregister_data_set (ds->type);
1483 else if (data_sets == NULL)
1485 data_sets = c_avl_create ((int (*) (const void *, const void *)) strcmp);
1486 if (data_sets == NULL)
1490 ds_copy = malloc (sizeof (*ds_copy));
1491 if (ds_copy == NULL)
1493 memcpy(ds_copy, ds, sizeof (data_set_t));
1495 ds_copy->ds = malloc (sizeof (*ds_copy->ds)
1497 if (ds_copy->ds == NULL)
1503 for (size_t i = 0; i < ds->ds_num; i++)
1504 memcpy (ds_copy->ds + i, ds->ds + i, sizeof (data_source_t));
1506 return (c_avl_insert (data_sets, (void *) ds_copy->type, (void *) ds_copy));
1507 } /* int plugin_register_data_set */
1509 int plugin_register_log (const char *name,
1510 plugin_log_cb callback, user_data_t const *ud)
1512 return (create_register_callback (&list_log, name,
1513 (void *) callback, ud));
1514 } /* int plugin_register_log */
1516 int plugin_register_notification (const char *name,
1517 plugin_notification_cb callback, user_data_t const *ud)
1519 return (create_register_callback (&list_notification, name,
1520 (void *) callback, ud));
1521 } /* int plugin_register_log */
1523 int plugin_unregister_config (const char *name)
1525 cf_unregister (name);
1527 } /* int plugin_unregister_config */
1529 int plugin_unregister_complex_config (const char *name)
1531 cf_unregister_complex (name);
1533 } /* int plugin_unregister_complex_config */
1535 int plugin_unregister_init (const char *name)
1537 return (plugin_unregister (list_init, name));
1540 int plugin_unregister_read (const char *name) /* {{{ */
1548 pthread_mutex_lock (&read_lock);
1550 if (read_list == NULL)
1552 pthread_mutex_unlock (&read_lock);
1556 le = llist_search (read_list, name);
1559 pthread_mutex_unlock (&read_lock);
1560 WARNING ("plugin_unregister_read: No such read function: %s",
1565 llist_remove (read_list, le);
1568 assert (rf != NULL);
1569 rf->rf_type = RF_REMOVE;
1571 pthread_mutex_unlock (&read_lock);
1573 llentry_destroy (le);
1575 DEBUG ("plugin_unregister_read: Marked `%s' for removal.", name);
1578 } /* }}} int plugin_unregister_read */
1580 void plugin_log_available_writers (void)
1582 log_list_callbacks (&list_write, "Available write targets:");
1585 static int compare_read_func_group (llentry_t *e, void *ud) /* {{{ */
1587 read_func_t *rf = e->value;
1590 return strcmp (rf->rf_group, (const char *)group);
1591 } /* }}} int compare_read_func_group */
1593 int plugin_unregister_read_group (const char *group) /* {{{ */
1603 pthread_mutex_lock (&read_lock);
1605 if (read_list == NULL)
1607 pthread_mutex_unlock (&read_lock);
1613 le = llist_search_custom (read_list,
1614 compare_read_func_group, (void *)group);
1621 llist_remove (read_list, le);
1624 assert (rf != NULL);
1625 rf->rf_type = RF_REMOVE;
1627 llentry_destroy (le);
1629 DEBUG ("plugin_unregister_read_group: "
1630 "Marked `%s' (group `%s') for removal.",
1631 rf->rf_name, group);
1634 pthread_mutex_unlock (&read_lock);
1638 WARNING ("plugin_unregister_read_group: No such "
1639 "group of read function: %s", group);
1644 } /* }}} int plugin_unregister_read_group */
1646 int plugin_unregister_write (const char *name)
1648 return (plugin_unregister (list_write, name));
1651 int plugin_unregister_flush (const char *name)
1653 plugin_ctx_t ctx = plugin_get_ctx ();
1655 if (ctx.flush_interval != 0)
1659 flush_name = plugin_flush_callback_name (name);
1660 if (flush_name != NULL)
1662 plugin_unregister_read(flush_name);
1667 return plugin_unregister (list_flush, name);
1670 int plugin_unregister_missing (const char *name)
1672 return (plugin_unregister (list_missing, name));
1675 int plugin_unregister_shutdown (const char *name)
1677 return (plugin_unregister (list_shutdown, name));
1680 int plugin_unregister_data_set (const char *name)
1684 if (data_sets == NULL)
1687 if (c_avl_remove (data_sets, name, NULL, (void *) &ds) != 0)
1694 } /* int plugin_unregister_data_set */
1696 int plugin_unregister_log (const char *name)
1698 return (plugin_unregister (list_log, name));
1701 int plugin_unregister_notification (const char *name)
1703 return (plugin_unregister (list_notification, name));
1706 int plugin_init_all (void)
1708 char const *chain_name;
1713 /* Init the value cache */
1716 if (IS_TRUE (global_option_get ("CollectInternalStats")))
1717 record_statistics = 1;
1719 chain_name = global_option_get ("PreCacheChain");
1720 pre_cache_chain = fc_chain_get_by_name (chain_name);
1722 chain_name = global_option_get ("PostCacheChain");
1723 post_cache_chain = fc_chain_get_by_name (chain_name);
1725 write_limit_high = global_option_get_long ("WriteQueueLimitHigh",
1727 if (write_limit_high < 0)
1729 ERROR ("WriteQueueLimitHigh must be positive or zero.");
1730 write_limit_high = 0;
1733 write_limit_low = global_option_get_long ("WriteQueueLimitLow",
1734 /* default = */ write_limit_high / 2);
1735 if (write_limit_low < 0)
1737 ERROR ("WriteQueueLimitLow must be positive or zero.");
1738 write_limit_low = write_limit_high / 2;
1740 else if (write_limit_low > write_limit_high)
1742 ERROR ("WriteQueueLimitLow must not be larger than "
1743 "WriteQueueLimitHigh.");
1744 write_limit_low = write_limit_high;
1747 write_threads_num = global_option_get_long ("WriteThreads",
1749 if (write_threads_num < 1)
1751 ERROR ("WriteThreads must be positive.");
1752 write_threads_num = 5;
1755 if ((list_init == NULL) && (read_heap == NULL))
1758 /* Calling all init callbacks before checking if read callbacks
1759 * are available allows the init callbacks to register the read
1761 le = llist_head (list_init);
1764 callback_func_t *cf;
1765 plugin_init_cb callback;
1766 plugin_ctx_t old_ctx;
1769 old_ctx = plugin_set_ctx (cf->cf_ctx);
1770 callback = cf->cf_callback;
1771 status = (*callback) ();
1772 plugin_set_ctx (old_ctx);
1776 ERROR ("Initialization of plugin `%s' "
1777 "failed with status %i. "
1778 "Plugin will be unloaded.",
1780 /* Plugins that register read callbacks from the init
1781 * callback should take care of appropriate error
1782 * handling themselves. */
1783 /* FIXME: Unload _all_ functions */
1784 plugin_unregister_read (le->key);
1791 start_write_threads ((size_t) write_threads_num);
1793 max_read_interval = global_option_get_time ("MaxReadInterval",
1794 DEFAULT_MAX_READ_INTERVAL);
1796 /* Start read-threads */
1797 if (read_heap != NULL)
1802 rt = global_option_get ("ReadThreads");
1805 start_read_threads ((num > 0) ? num : 5);
1808 } /* void plugin_init_all */
1810 /* TODO: Rename this function. */
1811 void plugin_read_all (void)
1813 if(record_statistics) {
1814 plugin_update_internal_statistics ();
1816 uc_check_timeout ();
1819 } /* void plugin_read_all */
1821 /* Read function called when the `-T' command line argument is given. */
1822 int plugin_read_all_once (void)
1825 int return_status = 0;
1827 if (read_heap == NULL)
1829 NOTICE ("No read-functions are registered.");
1836 plugin_ctx_t old_ctx;
1838 rf = c_heap_get_root (read_heap);
1842 old_ctx = plugin_set_ctx (rf->rf_ctx);
1844 if (rf->rf_type == RF_SIMPLE)
1846 int (*callback) (void);
1848 callback = rf->rf_callback;
1849 status = (*callback) ();
1853 plugin_read_cb callback;
1855 callback = rf->rf_callback;
1856 status = (*callback) (&rf->rf_udata);
1859 plugin_set_ctx (old_ctx);
1863 NOTICE ("read-function of plugin `%s' failed.",
1868 sfree (rf->rf_name);
1869 destroy_callback ((void *) rf);
1872 return (return_status);
1873 } /* int plugin_read_all_once */
1875 int plugin_write (const char *plugin, /* {{{ */
1876 const data_set_t *ds, const value_list_t *vl)
1884 if (list_write == NULL)
1889 ds = plugin_get_ds (vl->type);
1892 ERROR ("plugin_write: Unable to lookup type `%s'.", vl->type);
1902 le = llist_head (list_write);
1905 callback_func_t *cf = le->value;
1906 plugin_write_cb callback;
1908 /* do not switch plugin context; rather keep the context (interval)
1909 * information of the calling read plugin */
1911 DEBUG ("plugin: plugin_write: Writing values via %s.", le->key);
1912 callback = cf->cf_callback;
1913 status = (*callback) (ds, vl, &cf->cf_udata);
1922 if ((success == 0) && (failure != 0))
1927 else /* plugin != NULL */
1929 callback_func_t *cf;
1930 plugin_write_cb callback;
1932 le = llist_head (list_write);
1935 if (strcasecmp (plugin, le->key) == 0)
1946 /* do not switch plugin context; rather keep the context (interval)
1947 * information of the calling read plugin */
1949 DEBUG ("plugin: plugin_write: Writing values via %s.", le->key);
1950 callback = cf->cf_callback;
1951 status = (*callback) (ds, vl, &cf->cf_udata);
1955 } /* }}} int plugin_write */
1957 int plugin_flush (const char *plugin, cdtime_t timeout, const char *identifier)
1961 if (list_flush == NULL)
1964 le = llist_head (list_flush);
1967 callback_func_t *cf;
1968 plugin_flush_cb callback;
1969 plugin_ctx_t old_ctx;
1971 if ((plugin != NULL)
1972 && (strcmp (plugin, le->key) != 0))
1979 old_ctx = plugin_set_ctx (cf->cf_ctx);
1980 callback = cf->cf_callback;
1982 (*callback) (timeout, identifier, &cf->cf_udata);
1984 plugin_set_ctx (old_ctx);
1989 } /* int plugin_flush */
1991 int plugin_shutdown_all (void)
1994 int ret = 0; // Assume success.
1996 destroy_all_callbacks (&list_init);
1998 stop_read_threads ();
2000 pthread_mutex_lock (&read_lock);
2001 llist_destroy (read_list);
2003 pthread_mutex_unlock (&read_lock);
2005 destroy_read_heap ();
2007 /* blocks until all write threads have shut down. */
2008 stop_write_threads ();
2010 /* ask all plugins to write out the state they kept. */
2011 plugin_flush (/* plugin = */ NULL,
2013 /* identifier = */ NULL);
2016 if (list_shutdown != NULL)
2017 le = llist_head (list_shutdown);
2021 callback_func_t *cf;
2022 plugin_shutdown_cb callback;
2023 plugin_ctx_t old_ctx;
2026 old_ctx = plugin_set_ctx (cf->cf_ctx);
2027 callback = cf->cf_callback;
2029 /* Advance the pointer before calling the callback allows
2030 * shutdown functions to unregister themselves. If done the
2031 * other way around the memory `le' points to will be freed
2032 * after callback returns. */
2035 if ((*callback) () != 0)
2038 plugin_set_ctx (old_ctx);
2041 /* Write plugins which use the `user_data' pointer usually need the
2042 * same data available to the flush callback. If this is the case, set
2043 * the free_function to NULL when registering the flush callback and to
2044 * the real free function when registering the write callback. This way
2045 * the data isn't freed twice. */
2046 destroy_all_callbacks (&list_flush);
2047 destroy_all_callbacks (&list_missing);
2048 destroy_all_callbacks (&list_write);
2050 destroy_all_callbacks (&list_notification);
2051 destroy_all_callbacks (&list_shutdown);
2052 destroy_all_callbacks (&list_log);
2054 plugin_free_loaded ();
2055 plugin_free_data_sets ();
2057 } /* void plugin_shutdown_all */
2059 int plugin_dispatch_missing (const value_list_t *vl) /* {{{ */
2063 if (list_missing == NULL)
2066 le = llist_head (list_missing);
2069 callback_func_t *cf;
2070 plugin_missing_cb callback;
2071 plugin_ctx_t old_ctx;
2075 old_ctx = plugin_set_ctx (cf->cf_ctx);
2076 callback = cf->cf_callback;
2078 status = (*callback) (vl, &cf->cf_udata);
2079 plugin_set_ctx (old_ctx);
2084 ERROR ("plugin_dispatch_missing: Callback function \"%s\" "
2085 "failed with status %i.",
2098 } /* int }}} plugin_dispatch_missing */
2100 static int plugin_dispatch_values_internal (value_list_t *vl)
2103 static c_complain_t no_write_complaint = C_COMPLAIN_INIT_STATIC;
2107 _Bool free_meta_data = 0;
2109 assert (vl != NULL);
2111 /* These fields are initialized by plugin_value_list_clone() if needed: */
2112 assert (vl->host[0] != 0);
2113 assert (vl->time != 0); /* The time is determined at _enqueue_ time. */
2114 assert (vl->interval != 0);
2116 if (vl->type[0] == 0 || vl->values == NULL || vl->values_len < 1)
2118 ERROR ("plugin_dispatch_values: Invalid value list "
2119 "from plugin %s.", vl->plugin);
2123 /* Free meta data only if the calling function didn't specify any. In
2124 * this case matches and targets may add some and the calling function
2125 * may not expect (and therefore free) that data. */
2126 if (vl->meta == NULL)
2129 if (list_write == NULL)
2130 c_complain_once (LOG_WARNING, &no_write_complaint,
2131 "plugin_dispatch_values: No write callback has been "
2132 "registered. Please load at least one output plugin, "
2133 "if you want the collected data to be stored.");
2135 if (data_sets == NULL)
2137 ERROR ("plugin_dispatch_values: No data sets registered. "
2138 "Could the types database be read? Check "
2139 "your `TypesDB' setting!");
2143 if (c_avl_get (data_sets, vl->type, (void *) &ds) != 0)
2145 char ident[6 * DATA_MAX_NAME_LEN];
2147 FORMAT_VL (ident, sizeof (ident), vl);
2148 INFO ("plugin_dispatch_values: Dataset not found: %s "
2149 "(from \"%s\"), check your types.db!",
2154 DEBUG ("plugin_dispatch_values: time = %.3f; interval = %.3f; "
2156 "plugin = %s; plugin_instance = %s; "
2157 "type = %s; type_instance = %s;",
2158 CDTIME_T_TO_DOUBLE (vl->time),
2159 CDTIME_T_TO_DOUBLE (vl->interval),
2161 vl->plugin, vl->plugin_instance,
2162 vl->type, vl->type_instance);
2165 assert (0 == strcmp (ds->type, vl->type));
2167 if (0 != strcmp (ds->type, vl->type))
2168 WARNING ("plugin_dispatch_values: (ds->type = %s) != (vl->type = %s)",
2169 ds->type, vl->type);
2173 assert (ds->ds_num == vl->values_len);
2175 if (ds->ds_num != vl->values_len)
2177 ERROR ("plugin_dispatch_values: ds->type = %s: "
2178 "(ds->ds_num = %zu) != "
2179 "(vl->values_len = %zu)",
2180 ds->type, ds->ds_num, vl->values_len);
2185 escape_slashes (vl->host, sizeof (vl->host));
2186 escape_slashes (vl->plugin, sizeof (vl->plugin));
2187 escape_slashes (vl->plugin_instance, sizeof (vl->plugin_instance));
2188 escape_slashes (vl->type, sizeof (vl->type));
2189 escape_slashes (vl->type_instance, sizeof (vl->type_instance));
2191 if (pre_cache_chain != NULL)
2193 status = fc_process_chain (ds, vl, pre_cache_chain);
2196 WARNING ("plugin_dispatch_values: Running the "
2197 "pre-cache chain failed with "
2201 else if (status == FC_TARGET_STOP)
2205 /* Update the value cache */
2208 if (post_cache_chain != NULL)
2210 status = fc_process_chain (ds, vl, post_cache_chain);
2213 WARNING ("plugin_dispatch_values: Running the "
2214 "post-cache chain failed with "
2220 fc_default_action (ds, vl);
2222 if ((free_meta_data != 0) && (vl->meta != NULL))
2224 meta_data_destroy (vl->meta);
2229 } /* int plugin_dispatch_values_internal */
2231 static double get_drop_probability (void) /* {{{ */
2237 pthread_mutex_lock (&write_lock);
2238 wql = write_queue_length;
2239 pthread_mutex_unlock (&write_lock);
2241 if (wql < write_limit_low)
2243 if (wql >= write_limit_high)
2246 pos = 1 + wql - write_limit_low;
2247 size = 1 + write_limit_high - write_limit_low;
2249 return (((double) pos) / ((double) size));
2250 } /* }}} double get_drop_probability */
2252 static _Bool check_drop_value (void) /* {{{ */
2254 static cdtime_t last_message_time = 0;
2255 static pthread_mutex_t last_message_lock = PTHREAD_MUTEX_INITIALIZER;
2261 if (write_limit_high == 0)
2264 p = get_drop_probability ();
2268 status = pthread_mutex_trylock (&last_message_lock);
2274 if ((now - last_message_time) > TIME_T_TO_CDTIME_T (1))
2276 last_message_time = now;
2277 ERROR ("plugin_dispatch_values: Low water mark "
2278 "reached. Dropping %.0f%% of metrics.",
2281 pthread_mutex_unlock (&last_message_lock);
2292 } /* }}} _Bool check_drop_value */
2294 int plugin_dispatch_values (value_list_t const *vl)
2297 static pthread_mutex_t statistics_lock = PTHREAD_MUTEX_INITIALIZER;
2299 if (check_drop_value ()) {
2300 if(record_statistics) {
2301 pthread_mutex_lock(&statistics_lock);
2302 stats_values_dropped++;
2303 pthread_mutex_unlock(&statistics_lock);
2308 status = plugin_write_enqueue (vl);
2312 ERROR ("plugin_dispatch_values: plugin_write_enqueue failed "
2313 "with status %i (%s).", status,
2314 sstrerror (status, errbuf, sizeof (errbuf)));
2321 __attribute__((sentinel))
2322 int plugin_dispatch_multivalue (value_list_t const *template, /* {{{ */
2323 _Bool store_percentage, int store_type, ...)
2330 assert (template->values_len == 1);
2332 /* Calculate sum for Gauge to calculate percent if needed */
2333 if (DS_TYPE_GAUGE == store_type) {
2334 va_start (ap, store_type);
2340 name = va_arg (ap, char const *);
2344 value = va_arg (ap, gauge_t);
2352 vl = plugin_value_list_clone (template);
2353 /* plugin_value_list_clone makes sure vl->time is set to non-zero. */
2354 if (store_percentage)
2355 sstrncpy (vl->type, "percent", sizeof (vl->type));
2357 va_start (ap, store_type);
2363 /* Set the type instance. */
2364 name = va_arg (ap, char const *);
2367 sstrncpy (vl->type_instance, name, sizeof (vl->type_instance));
2369 /* Set the value. */
2373 vl->values[0].gauge = va_arg (ap, gauge_t);
2374 if (store_percentage)
2375 vl->values[0].gauge *= sum ? (100.0 / sum) : NAN;
2377 case DS_TYPE_ABSOLUTE:
2378 vl->values[0].absolute = va_arg (ap, absolute_t);
2380 case DS_TYPE_COUNTER:
2381 vl->values[0].counter = va_arg (ap, counter_t);
2383 case DS_TYPE_DERIVE:
2384 vl->values[0].derive = va_arg (ap, derive_t);
2387 ERROR ("plugin_dispatch_multivalue: given store_type is incorrect.");
2392 status = plugin_write_enqueue (vl);
2398 plugin_value_list_free (vl);
2400 } /* }}} int plugin_dispatch_multivalue */
2402 int plugin_dispatch_notification (const notification_t *notif)
2405 /* Possible TODO: Add flap detection here */
2407 DEBUG ("plugin_dispatch_notification: severity = %i; message = %s; "
2408 "time = %.3f; host = %s;",
2409 notif->severity, notif->message,
2410 CDTIME_T_TO_DOUBLE (notif->time), notif->host);
2412 /* Nobody cares for notifications */
2413 if (list_notification == NULL)
2416 le = llist_head (list_notification);
2419 callback_func_t *cf;
2420 plugin_notification_cb callback;
2423 /* do not switch plugin context; rather keep the context
2424 * (interval) information of the calling plugin */
2427 callback = cf->cf_callback;
2428 status = (*callback) (notif, &cf->cf_udata);
2431 WARNING ("plugin_dispatch_notification: Notification "
2432 "callback %s returned %i.",
2440 } /* int plugin_dispatch_notification */
2442 void plugin_log (int level, const char *format, ...)
2449 if (level >= LOG_DEBUG)
2453 va_start (ap, format);
2454 vsnprintf (msg, sizeof (msg), format, ap);
2455 msg[sizeof (msg) - 1] = '\0';
2458 if (list_log == NULL)
2460 fprintf (stderr, "%s\n", msg);
2464 le = llist_head (list_log);
2467 callback_func_t *cf;
2468 plugin_log_cb callback;
2471 callback = cf->cf_callback;
2473 /* do not switch plugin context; rather keep the context
2474 * (interval) information of the calling plugin */
2476 (*callback) (level, msg, &cf->cf_udata);
2480 } /* void plugin_log */
2482 int parse_log_severity (const char *severity)
2486 if ((0 == strcasecmp (severity, "emerg"))
2487 || (0 == strcasecmp (severity, "alert"))
2488 || (0 == strcasecmp (severity, "crit"))
2489 || (0 == strcasecmp (severity, "err")))
2490 log_level = LOG_ERR;
2491 else if (0 == strcasecmp (severity, "warning"))
2492 log_level = LOG_WARNING;
2493 else if (0 == strcasecmp (severity, "notice"))
2494 log_level = LOG_NOTICE;
2495 else if (0 == strcasecmp (severity, "info"))
2496 log_level = LOG_INFO;
2498 else if (0 == strcasecmp (severity, "debug"))
2499 log_level = LOG_DEBUG;
2500 #endif /* COLLECT_DEBUG */
2503 } /* int parse_log_severity */
2505 int parse_notif_severity (const char *severity)
2507 int notif_severity = -1;
2509 if (strcasecmp (severity, "FAILURE") == 0)
2510 notif_severity = NOTIF_FAILURE;
2511 else if (strcmp (severity, "OKAY") == 0)
2512 notif_severity = NOTIF_OKAY;
2513 else if ((strcmp (severity, "WARNING") == 0)
2514 || (strcmp (severity, "WARN") == 0))
2515 notif_severity = NOTIF_WARNING;
2517 return (notif_severity);
2518 } /* int parse_notif_severity */
2520 const data_set_t *plugin_get_ds (const char *name)
2524 if (data_sets == NULL)
2526 ERROR ("plugin_get_ds: No data sets are defined yet.");
2530 if (c_avl_get (data_sets, name, (void *) &ds) != 0)
2532 DEBUG ("No such dataset registered: %s", name);
2537 } /* data_set_t *plugin_get_ds */
2539 static int plugin_notification_meta_add (notification_t *n,
2541 enum notification_meta_type_e type,
2544 notification_meta_t *meta;
2545 notification_meta_t *tail;
2547 if ((n == NULL) || (name == NULL) || (value == NULL))
2549 ERROR ("plugin_notification_meta_add: A pointer is NULL!");
2553 meta = calloc (1, sizeof (*meta));
2556 ERROR ("plugin_notification_meta_add: calloc failed.");
2560 sstrncpy (meta->name, name, sizeof (meta->name));
2565 case NM_TYPE_STRING:
2567 meta->nm_value.nm_string = strdup ((const char *) value);
2568 if (meta->nm_value.nm_string == NULL)
2570 ERROR ("plugin_notification_meta_add: strdup failed.");
2576 case NM_TYPE_SIGNED_INT:
2578 meta->nm_value.nm_signed_int = *((int64_t *) value);
2581 case NM_TYPE_UNSIGNED_INT:
2583 meta->nm_value.nm_unsigned_int = *((uint64_t *) value);
2586 case NM_TYPE_DOUBLE:
2588 meta->nm_value.nm_double = *((double *) value);
2591 case NM_TYPE_BOOLEAN:
2593 meta->nm_value.nm_boolean = *((_Bool *) value);
2598 ERROR ("plugin_notification_meta_add: Unknown type: %i", type);
2602 } /* switch (type) */
2606 while ((tail != NULL) && (tail->next != NULL))
2615 } /* int plugin_notification_meta_add */
2617 int plugin_notification_meta_add_string (notification_t *n,
2621 return (plugin_notification_meta_add (n, name, NM_TYPE_STRING, value));
2624 int plugin_notification_meta_add_signed_int (notification_t *n,
2628 return (plugin_notification_meta_add (n, name, NM_TYPE_SIGNED_INT, &value));
2631 int plugin_notification_meta_add_unsigned_int (notification_t *n,
2635 return (plugin_notification_meta_add (n, name, NM_TYPE_UNSIGNED_INT, &value));
2638 int plugin_notification_meta_add_double (notification_t *n,
2642 return (plugin_notification_meta_add (n, name, NM_TYPE_DOUBLE, &value));
2645 int plugin_notification_meta_add_boolean (notification_t *n,
2649 return (plugin_notification_meta_add (n, name, NM_TYPE_BOOLEAN, &value));
2652 int plugin_notification_meta_copy (notification_t *dst,
2653 const notification_t *src)
2655 assert (dst != NULL);
2656 assert (src != NULL);
2657 assert (dst != src);
2658 assert ((src->meta == NULL) || (src->meta != dst->meta));
2660 for (notification_meta_t *meta = src->meta; meta != NULL; meta = meta->next)
2662 if (meta->type == NM_TYPE_STRING)
2663 plugin_notification_meta_add_string (dst, meta->name,
2664 meta->nm_value.nm_string);
2665 else if (meta->type == NM_TYPE_SIGNED_INT)
2666 plugin_notification_meta_add_signed_int (dst, meta->name,
2667 meta->nm_value.nm_signed_int);
2668 else if (meta->type == NM_TYPE_UNSIGNED_INT)
2669 plugin_notification_meta_add_unsigned_int (dst, meta->name,
2670 meta->nm_value.nm_unsigned_int);
2671 else if (meta->type == NM_TYPE_DOUBLE)
2672 plugin_notification_meta_add_double (dst, meta->name,
2673 meta->nm_value.nm_double);
2674 else if (meta->type == NM_TYPE_BOOLEAN)
2675 plugin_notification_meta_add_boolean (dst, meta->name,
2676 meta->nm_value.nm_boolean);
2680 } /* int plugin_notification_meta_copy */
2682 int plugin_notification_meta_free (notification_meta_t *n)
2684 notification_meta_t *this;
2685 notification_meta_t *next;
2689 ERROR ("plugin_notification_meta_free: n == NULL!");
2694 while (this != NULL)
2698 if (this->type == NM_TYPE_STRING)
2700 /* Assign to a temporary variable to work around nm_string's const
2702 void *tmp = (void *) this->nm_value.nm_string;
2705 this->nm_value.nm_string = NULL;
2713 } /* int plugin_notification_meta_free */
2715 static void plugin_ctx_destructor (void *ctx)
2718 } /* void plugin_ctx_destructor */
2720 static plugin_ctx_t ctx_init = { /* interval = */ 0 };
2722 static plugin_ctx_t *plugin_ctx_create (void)
2726 ctx = malloc (sizeof (*ctx));
2729 ERROR ("Failed to allocate plugin context: %s",
2730 sstrerror (errno, errbuf, sizeof (errbuf)));
2735 assert (plugin_ctx_key_initialized);
2736 pthread_setspecific (plugin_ctx_key, ctx);
2737 DEBUG("Created new plugin context.");
2739 } /* int plugin_ctx_create */
2741 void plugin_init_ctx (void)
2743 pthread_key_create (&plugin_ctx_key, plugin_ctx_destructor);
2744 plugin_ctx_key_initialized = 1;
2745 } /* void plugin_init_ctx */
2747 plugin_ctx_t plugin_get_ctx (void)
2751 assert (plugin_ctx_key_initialized);
2752 ctx = pthread_getspecific (plugin_ctx_key);
2755 ctx = plugin_ctx_create ();
2756 /* this must no happen -- exit() instead? */
2762 } /* plugin_ctx_t plugin_get_ctx */
2764 plugin_ctx_t plugin_set_ctx (plugin_ctx_t ctx)
2769 assert (plugin_ctx_key_initialized);
2770 c = pthread_getspecific (plugin_ctx_key);
2773 c = plugin_ctx_create ();
2774 /* this must no happen -- exit() instead? */
2783 } /* void plugin_set_ctx */
2785 cdtime_t plugin_get_interval (void)
2789 interval = plugin_get_ctx().interval;
2793 return cf_get_default_interval ();
2794 } /* cdtime_t plugin_get_interval */
2798 void *(*start_routine) (void *);
2802 static void *plugin_thread_start (void *arg)
2804 plugin_thread_t *plugin_thread = arg;
2806 void *(*start_routine) (void *) = plugin_thread->start_routine;
2807 void *plugin_arg = plugin_thread->arg;
2809 plugin_set_ctx (plugin_thread->ctx);
2811 sfree (plugin_thread);
2813 return start_routine (plugin_arg);
2814 } /* void *plugin_thread_start */
2816 int plugin_thread_create (pthread_t *thread, const pthread_attr_t *attr,
2817 void *(*start_routine) (void *), void *arg, char *name)
2819 plugin_thread_t *plugin_thread;
2822 plugin_thread = malloc (sizeof (*plugin_thread));
2823 if (plugin_thread == NULL)
2826 plugin_thread->ctx = plugin_get_ctx ();
2827 plugin_thread->start_routine = start_routine;
2828 plugin_thread->arg = arg;
2830 ret = pthread_create (thread, attr,
2831 plugin_thread_start, plugin_thread);
2833 if (ret == 0 && name != NULL) {
2834 #if defined(HAVE_PTHREAD_SETNAME_NP) || defined(HAVE_PTHREAD_SET_NAME_NP)
2835 char thread_name[16];
2836 sstrncpy (thread_name, name, sizeof(thread_name));
2837 # if defined(HAVE_PTHREAD_SETNAME_NP)
2838 pthread_setname_np (*thread, thread_name);
2839 # elif defined(HAVE_PTHREAD_SET_NAME_NP)
2840 pthread_set_name_np (*thread, thread_name);
2846 } /* int plugin_thread_create */
2848 /* vim: set sw=8 ts=8 noet fdm=marker : */