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>
32 #include "configfile.h"
33 #include "filter_chain.h"
34 #include "utils_avltree.h"
35 #include "utils_cache.h"
36 #include "utils_complain.h"
37 #include "utils_llist.h"
38 #include "utils_heap.h"
39 #include "utils_time.h"
40 #include "utils_random.h"
47 struct callback_func_s
53 typedef struct callback_func_s callback_func_t;
57 #define RF_REMOVE 65535
60 /* `read_func_t' "inherits" from `callback_func_t'.
61 * The `rf_super' member MUST be the first one in this structure! */
62 #define rf_callback rf_super.cf_callback
63 #define rf_udata rf_super.cf_udata
64 #define rf_ctx rf_super.cf_ctx
65 callback_func_t rf_super;
66 char rf_group[DATA_MAX_NAME_LEN];
70 cdtime_t rf_effective_interval;
71 cdtime_t rf_next_read;
73 typedef struct read_func_s read_func_t;
76 typedef struct write_queue_s write_queue_t;
84 struct flush_callback_s {
88 typedef struct flush_callback_s flush_callback_t;
93 static c_avl_tree_t *plugins_loaded = NULL;
95 static llist_t *list_init;
96 static llist_t *list_write;
97 static llist_t *list_flush;
98 static llist_t *list_missing;
99 static llist_t *list_shutdown;
100 static llist_t *list_log;
101 static llist_t *list_notification;
103 static fc_chain_t *pre_cache_chain = NULL;
104 static fc_chain_t *post_cache_chain = NULL;
106 static c_avl_tree_t *data_sets;
108 static char *plugindir = NULL;
110 #ifndef DEFAULT_MAX_READ_INTERVAL
111 # define DEFAULT_MAX_READ_INTERVAL TIME_T_TO_CDTIME_T (86400)
113 static c_heap_t *read_heap = NULL;
114 static llist_t *read_list;
115 static int read_loop = 1;
116 static pthread_mutex_t read_lock = PTHREAD_MUTEX_INITIALIZER;
117 static pthread_cond_t read_cond = PTHREAD_COND_INITIALIZER;
118 static pthread_t *read_threads = NULL;
119 static int read_threads_num = 0;
120 static cdtime_t max_read_interval = DEFAULT_MAX_READ_INTERVAL;
122 static write_queue_t *write_queue_head;
123 static write_queue_t *write_queue_tail;
124 static long write_queue_length = 0;
125 static _Bool write_loop = 1;
126 static pthread_mutex_t write_lock = PTHREAD_MUTEX_INITIALIZER;
127 static pthread_cond_t write_cond = PTHREAD_COND_INITIALIZER;
128 static pthread_t *write_threads = NULL;
129 static size_t write_threads_num = 0;
131 static pthread_key_t plugin_ctx_key;
132 static _Bool plugin_ctx_key_initialized = 0;
134 static long write_limit_high = 0;
135 static long write_limit_low = 0;
137 static derive_t stats_values_dropped = 0;
138 static _Bool record_statistics = 0;
143 static int plugin_dispatch_values_internal (value_list_t *vl);
145 static const char *plugin_get_dir (void)
147 if (plugindir == NULL)
153 static void plugin_update_internal_statistics (void) { /* {{{ */
155 gauge_t copy_write_queue_length = (gauge_t) write_queue_length;
157 /* Initialize `vl' */
158 value_list_t vl = VALUE_LIST_INIT;
159 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
160 sstrncpy (vl.plugin, "collectd", sizeof (vl.plugin));
163 sstrncpy (vl.plugin_instance, "write_queue",
164 sizeof (vl.plugin_instance));
166 /* Write queue : queue length */
167 vl.values = &(value_t) { .gauge = copy_write_queue_length };
169 sstrncpy (vl.type, "queue_length", sizeof (vl.type));
170 vl.type_instance[0] = 0;
171 plugin_dispatch_values (&vl);
173 /* Write queue : Values dropped (queue length > low limit) */
174 vl.values = &(value_t) { .gauge = (gauge_t) stats_values_dropped };
176 sstrncpy (vl.type, "derive", sizeof (vl.type));
177 sstrncpy (vl.type_instance, "dropped", sizeof (vl.type_instance));
178 plugin_dispatch_values (&vl);
181 sstrncpy (vl.plugin_instance, "cache",
182 sizeof (vl.plugin_instance));
184 /* Cache : Nb entry in cache tree */
185 vl.values = &(value_t) { .gauge = (gauge_t) uc_get_size() };
187 sstrncpy (vl.type, "cache_size", sizeof (vl.type));
188 vl.type_instance[0] = 0;
189 plugin_dispatch_values (&vl);
192 } /* }}} void plugin_update_internal_statistics */
194 static void destroy_callback (callback_func_t *cf) /* {{{ */
199 if ((cf->cf_udata.data != NULL) && (cf->cf_udata.free_func != NULL))
201 cf->cf_udata.free_func (cf->cf_udata.data);
202 cf->cf_udata.data = NULL;
203 cf->cf_udata.free_func = NULL;
206 } /* }}} void destroy_callback */
208 static void destroy_all_callbacks (llist_t **list) /* {{{ */
215 le = llist_head (*list);
223 destroy_callback (le->value);
229 llist_destroy (*list);
231 } /* }}} void destroy_all_callbacks */
233 static void destroy_read_heap (void) /* {{{ */
235 if (read_heap == NULL)
242 rf = c_heap_get_root (read_heap);
246 destroy_callback ((callback_func_t *) rf);
249 c_heap_destroy (read_heap);
251 } /* }}} void destroy_read_heap */
253 static int register_callback (llist_t **list, /* {{{ */
254 const char *name, callback_func_t *cf)
261 *list = llist_create ();
264 ERROR ("plugin: register_callback: "
265 "llist_create failed.");
266 destroy_callback (cf);
274 ERROR ("plugin: register_callback: strdup failed.");
275 destroy_callback (cf);
279 le = llist_search (*list, name);
282 le = llentry_create (key, cf);
285 ERROR ("plugin: register_callback: "
286 "llentry_create failed.");
288 destroy_callback (cf);
292 llist_append (*list, le);
296 callback_func_t *old_cf;
301 WARNING ("plugin: register_callback: "
302 "a callback named `%s' already exists - "
303 "overwriting the old entry!", name);
305 destroy_callback (old_cf);
310 } /* }}} int register_callback */
312 static void log_list_callbacks (llist_t **list, /* {{{ */
322 n = llist_size(*list);
325 INFO("%s [none]", comment);
329 keys = calloc(n, sizeof(char*));
333 ERROR("%s: failed to allocate memory for list of callbacks",
339 for (le = llist_head (*list), i = 0, len = 0;
344 len += strlen(le->key) + 6;
346 str = malloc(len + 10);
349 ERROR("%s: failed to allocate memory for list of callbacks",
355 strjoin(str, len, keys, n, "', '");
356 INFO("%s ['%s']", comment, str);
360 } /* }}} void log_list_callbacks */
362 static int create_register_callback (llist_t **list, /* {{{ */
363 const char *name, void *callback, user_data_t *ud)
367 cf = calloc (1, sizeof (*cf));
370 ERROR ("plugin: create_register_callback: calloc failed.");
374 cf->cf_callback = callback;
377 cf->cf_udata.data = NULL;
378 cf->cf_udata.free_func = NULL;
385 cf->cf_ctx = plugin_get_ctx ();
387 return (register_callback (list, name, cf));
388 } /* }}} int create_register_callback */
390 static int plugin_unregister (llist_t *list, const char *name) /* {{{ */
397 e = llist_search (list, name);
401 llist_remove (list, e);
404 destroy_callback (e->value);
409 } /* }}} int plugin_unregister */
412 * (Try to) load the shared object `file'. Won't complain if it isn't a shared
413 * object, but it will bitch about a shared object not having a
414 * ``module_register'' symbol..
416 static int plugin_load_file (char *file, uint32_t flags)
419 void (*reg_handle) (void);
422 lt_dlerror (); /* clear errors */
424 #if LIBTOOL_VERSION == 2
425 if (flags & PLUGIN_FLAGS_GLOBAL) {
427 lt_dladvise_init(&advise);
428 lt_dladvise_global(&advise);
429 dlh = lt_dlopenadvise(file, advise);
430 lt_dladvise_destroy(&advise);
432 dlh = lt_dlopen (file);
434 #else /* if LIBTOOL_VERSION == 1 */
435 if (flags & PLUGIN_FLAGS_GLOBAL)
436 WARNING ("plugin_load_file: The global flag is not supported, "
437 "libtool 2 is required for this.");
438 dlh = lt_dlopen (file);
443 char errbuf[1024] = "";
445 ssnprintf (errbuf, sizeof (errbuf),
446 "lt_dlopen (\"%s\") failed: %s. "
447 "The most common cause for this problem is "
448 "missing dependencies. Use ldd(1) to check "
449 "the dependencies of the plugin "
451 file, lt_dlerror ());
453 ERROR ("%s", errbuf);
454 /* Make sure this is printed to STDERR in any case, but also
455 * make sure it's printed only once. */
456 if (list_log != NULL)
457 fprintf (stderr, "ERROR: %s\n", errbuf);
462 if ((reg_handle = (void (*) (void)) lt_dlsym (dlh, "module_register")) == NULL)
464 WARNING ("Couldn't find symbol \"module_register\" in \"%s\": %s\n",
465 file, lt_dlerror ());
475 static void *plugin_read_thread (void __attribute__((unused)) *args)
477 while (read_loop != 0)
480 plugin_ctx_t old_ctx;
488 /* Get the read function that needs to be read next.
489 * We don't need to hold "read_lock" for the heap, but we need
490 * to call c_heap_get_root() and pthread_cond_wait() in the
491 * same protected block. */
492 pthread_mutex_lock (&read_lock);
493 rf = c_heap_get_root (read_heap);
496 pthread_cond_wait (&read_cond, &read_lock);
497 pthread_mutex_unlock (&read_lock);
500 pthread_mutex_unlock (&read_lock);
502 if (rf->rf_interval == 0)
504 /* this should not happen, because the interval is set
505 * for each plugin when loading it
506 * XXX: issue a warning? */
507 rf->rf_interval = plugin_get_interval ();
508 rf->rf_effective_interval = rf->rf_interval;
510 rf->rf_next_read = cdtime ();
513 /* sleep until this entry is due,
514 * using pthread_cond_timedwait */
515 pthread_mutex_lock (&read_lock);
516 /* In pthread_cond_timedwait, spurious wakeups are possible
517 * (and really happen, at least on NetBSD with > 1 CPU), thus
518 * we need to re-evaluate the condition every time
519 * pthread_cond_timedwait returns. */
521 while ((read_loop != 0)
522 && (cdtime () < rf->rf_next_read)
525 struct timespec ts = { 0 };
527 CDTIME_T_TO_TIMESPEC (rf->rf_next_read, &ts);
529 rc = pthread_cond_timedwait (&read_cond, &read_lock,
533 /* Must hold `read_lock' when accessing `rf->rf_type'. */
534 rf_type = rf->rf_type;
535 pthread_mutex_unlock (&read_lock);
537 /* Check if we're supposed to stop.. This may have interrupted
541 /* Insert `rf' again, so it can be free'd correctly */
542 c_heap_insert (read_heap, rf);
546 /* The entry has been marked for deletion. The linked list
547 * entry has already been removed by `plugin_unregister_read'.
548 * All we have to do here is free the `read_func_t' and
550 if (rf_type == RF_REMOVE)
552 DEBUG ("plugin_read_thread: Destroying the `%s' "
553 "callback.", rf->rf_name);
555 destroy_callback ((callback_func_t *) rf);
560 DEBUG ("plugin_read_thread: Handling `%s'.", rf->rf_name);
564 old_ctx = plugin_set_ctx (rf->rf_ctx);
566 if (rf_type == RF_SIMPLE)
568 int (*callback) (void);
570 callback = rf->rf_callback;
571 status = (*callback) ();
575 plugin_read_cb callback;
577 assert (rf_type == RF_COMPLEX);
579 callback = rf->rf_callback;
580 status = (*callback) (&rf->rf_udata);
583 plugin_set_ctx (old_ctx);
585 /* If the function signals failure, we will increase the
586 * intervals in which it will be called. */
589 rf->rf_effective_interval *= 2;
590 if (rf->rf_effective_interval > max_read_interval)
591 rf->rf_effective_interval = max_read_interval;
593 NOTICE ("read-function of plugin `%s' failed. "
594 "Will suspend it for %.3f seconds.",
596 CDTIME_T_TO_DOUBLE (rf->rf_effective_interval));
600 /* Success: Restore the interval, if it was changed. */
601 rf->rf_effective_interval = rf->rf_interval;
604 /* update the ``next read due'' field */
607 /* calculate the time spent in the read function */
608 elapsed = (now - start);
610 if (elapsed > rf->rf_effective_interval)
611 WARNING ("plugin_read_thread: read-function of the `%s' plugin took %.3f "
612 "seconds, which is above its read interval (%.3f seconds). You might "
613 "want to adjust the `Interval' or `ReadThreads' settings.",
614 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed),
615 CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
617 DEBUG ("plugin_read_thread: read-function of the `%s' plugin took "
619 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed));
621 DEBUG ("plugin_read_thread: Effective interval of the "
622 "`%s' plugin is %.3f seconds.",
624 CDTIME_T_TO_DOUBLE (rf->rf_effective_interval));
626 /* Calculate the next (absolute) time at which this function
627 * should be called. */
628 rf->rf_next_read += rf->rf_effective_interval;
630 /* Check, if `rf_next_read' is in the past. */
631 if (rf->rf_next_read < now)
633 /* `rf_next_read' is in the past. Insert `now'
634 * so this value doesn't trail off into the
636 rf->rf_next_read = now;
639 DEBUG ("plugin_read_thread: Next read of the `%s' plugin at %.3f.",
641 CDTIME_T_TO_DOUBLE (rf->rf_next_read));
643 /* Re-insert this read function into the heap again. */
644 c_heap_insert (read_heap, rf);
645 } /* while (read_loop) */
649 } /* void *plugin_read_thread */
651 static void start_read_threads (int num)
653 if (read_threads != NULL)
656 read_threads = (pthread_t *) calloc (num, sizeof (pthread_t));
657 if (read_threads == NULL)
659 ERROR ("plugin: start_read_threads: calloc failed.");
663 read_threads_num = 0;
664 for (int i = 0; i < num; i++)
666 if (pthread_create (read_threads + read_threads_num, NULL,
667 plugin_read_thread, NULL) == 0)
673 ERROR ("plugin: start_read_threads: pthread_create failed.");
677 } /* void start_read_threads */
679 static void stop_read_threads (void)
681 if (read_threads == NULL)
684 INFO ("collectd: Stopping %i read threads.", read_threads_num);
686 pthread_mutex_lock (&read_lock);
688 DEBUG ("plugin: stop_read_threads: Signalling `read_cond'");
689 pthread_cond_broadcast (&read_cond);
690 pthread_mutex_unlock (&read_lock);
692 for (int i = 0; i < read_threads_num; i++)
694 if (pthread_join (read_threads[i], NULL) != 0)
696 ERROR ("plugin: stop_read_threads: pthread_join failed.");
698 read_threads[i] = (pthread_t) 0;
700 sfree (read_threads);
701 read_threads_num = 0;
702 } /* void stop_read_threads */
704 static void plugin_value_list_free (value_list_t *vl) /* {{{ */
709 meta_data_destroy (vl->meta);
712 } /* }}} void plugin_value_list_free */
714 static value_list_t *plugin_value_list_clone (value_list_t const *vl_orig) /* {{{ */
721 vl = malloc (sizeof (*vl));
724 memcpy (vl, vl_orig, sizeof (*vl));
726 if (vl->host[0] == 0)
727 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
729 vl->values = calloc (vl_orig->values_len, sizeof (*vl->values));
730 if (vl->values == NULL)
732 plugin_value_list_free (vl);
735 memcpy (vl->values, vl_orig->values,
736 vl_orig->values_len * sizeof (*vl->values));
738 vl->meta = meta_data_clone (vl->meta);
739 if ((vl_orig->meta != NULL) && (vl->meta == NULL))
741 plugin_value_list_free (vl);
746 vl->time = cdtime ();
748 /* Fill in the interval from the thread context, if it is zero. */
749 if (vl->interval == 0)
751 plugin_ctx_t ctx = plugin_get_ctx ();
753 if (ctx.interval != 0)
754 vl->interval = ctx.interval;
757 char name[6 * DATA_MAX_NAME_LEN];
758 FORMAT_VL (name, sizeof (name), vl);
759 ERROR ("plugin_value_list_clone: Unable to determine "
760 "interval from context for "
761 "value list \"%s\". "
762 "This indicates a broken plugin. "
763 "Please report this problem to the "
764 "collectd mailing list or at "
765 "<http://collectd.org/bugs/>.", name);
766 vl->interval = cf_get_default_interval ();
771 } /* }}} value_list_t *plugin_value_list_clone */
773 static int plugin_write_enqueue (value_list_t const *vl) /* {{{ */
777 q = malloc (sizeof (*q));
782 q->vl = plugin_value_list_clone (vl);
789 /* Store context of caller (read plugin); otherwise, it would not be
790 * available to the write plugins when actually dispatching the
791 * value-list later on. */
792 q->ctx = plugin_get_ctx ();
794 pthread_mutex_lock (&write_lock);
796 if (write_queue_tail == NULL)
798 write_queue_head = q;
799 write_queue_tail = q;
800 write_queue_length = 1;
804 write_queue_tail->next = q;
805 write_queue_tail = q;
806 write_queue_length += 1;
809 pthread_cond_signal (&write_cond);
810 pthread_mutex_unlock (&write_lock);
813 } /* }}} int plugin_write_enqueue */
815 static value_list_t *plugin_write_dequeue (void) /* {{{ */
820 pthread_mutex_lock (&write_lock);
822 while (write_loop && (write_queue_head == NULL))
823 pthread_cond_wait (&write_cond, &write_lock);
825 if (write_queue_head == NULL)
827 pthread_mutex_unlock (&write_lock);
831 q = write_queue_head;
832 write_queue_head = q->next;
833 write_queue_length -= 1;
834 if (write_queue_head == NULL) {
835 write_queue_tail = NULL;
836 assert(0 == write_queue_length);
839 pthread_mutex_unlock (&write_lock);
841 (void) plugin_set_ctx (q->ctx);
846 } /* }}} value_list_t *plugin_write_dequeue */
848 static void *plugin_write_thread (void __attribute__((unused)) *args) /* {{{ */
852 value_list_t *vl = plugin_write_dequeue ();
856 plugin_dispatch_values_internal (vl);
858 plugin_value_list_free (vl);
863 } /* }}} void *plugin_write_thread */
865 static void start_write_threads (size_t num) /* {{{ */
867 if (write_threads != NULL)
870 write_threads = (pthread_t *) calloc (num, sizeof (pthread_t));
871 if (write_threads == NULL)
873 ERROR ("plugin: start_write_threads: calloc failed.");
877 write_threads_num = 0;
878 for (size_t i = 0; i < num; i++)
882 status = pthread_create (write_threads + write_threads_num,
889 ERROR ("plugin: start_write_threads: pthread_create failed "
890 "with status %i (%s).", status,
891 sstrerror (status, errbuf, sizeof (errbuf)));
897 } /* }}} void start_write_threads */
899 static void stop_write_threads (void) /* {{{ */
904 if (write_threads == NULL)
907 INFO ("collectd: Stopping %zu write threads.", write_threads_num);
909 pthread_mutex_lock (&write_lock);
911 DEBUG ("plugin: stop_write_threads: Signalling `write_cond'");
912 pthread_cond_broadcast (&write_cond);
913 pthread_mutex_unlock (&write_lock);
915 for (i = 0; i < write_threads_num; i++)
917 if (pthread_join (write_threads[i], NULL) != 0)
919 ERROR ("plugin: stop_write_threads: pthread_join failed.");
921 write_threads[i] = (pthread_t) 0;
923 sfree (write_threads);
924 write_threads_num = 0;
926 pthread_mutex_lock (&write_lock);
928 for (q = write_queue_head; q != NULL; )
930 write_queue_t *q1 = q;
931 plugin_value_list_free (q->vl);
936 write_queue_head = NULL;
937 write_queue_tail = NULL;
938 write_queue_length = 0;
939 pthread_mutex_unlock (&write_lock);
943 WARNING ("plugin: %zu value list%s left after shutting down "
944 "the write threads.",
945 i, (i == 1) ? " was" : "s were");
947 } /* }}} void stop_write_threads */
952 void plugin_set_dir (const char *dir)
962 plugindir = strdup (dir);
963 if (plugindir == NULL)
964 ERROR ("plugin_set_dir: strdup(\"%s\") failed", dir);
967 static _Bool plugin_is_loaded (char const *name)
971 if (plugins_loaded == NULL)
972 plugins_loaded = c_avl_create ((int (*) (const void *, const void *)) strcasecmp);
973 assert (plugins_loaded != NULL);
975 status = c_avl_get (plugins_loaded, name, /* ret_value = */ NULL);
976 return (status == 0);
979 static int plugin_mark_loaded (char const *name)
984 name_copy = strdup (name);
985 if (name_copy == NULL)
988 status = c_avl_insert (plugins_loaded,
989 /* key = */ name_copy, /* value = */ NULL);
993 static void plugin_free_loaded (void)
998 if (plugins_loaded == NULL)
1001 while (c_avl_pick (plugins_loaded, &key, &value) == 0)
1004 assert (value == NULL);
1007 c_avl_destroy (plugins_loaded);
1008 plugins_loaded = NULL;
1012 int plugin_load (char const *plugin_name, uint32_t flags)
1016 char filename[BUFSIZE] = "";
1017 char typename[BUFSIZE];
1019 struct stat statbuf;
1023 if (plugin_name == NULL)
1026 /* Check if plugin is already loaded and don't do anything in this
1028 if (plugin_is_loaded (plugin_name))
1031 dir = plugin_get_dir ();
1035 * XXX: Magic at work:
1037 * Some of the language bindings, for example the Python and Perl
1038 * plugins, need to be able to export symbols to the scripts they run.
1039 * For this to happen, the "Globals" flag needs to be set.
1040 * Unfortunately, this technical detail is hard to explain to the
1041 * average user and she shouldn't have to worry about this, ideally.
1042 * So in order to save everyone's sanity use a different default for a
1043 * handful of special plugins. --octo
1045 if ((strcasecmp ("perl", plugin_name) == 0)
1046 || (strcasecmp ("python", plugin_name) == 0))
1047 flags |= PLUGIN_FLAGS_GLOBAL;
1049 /* `cpu' should not match `cpufreq'. To solve this we add `.so' to the
1050 * type when matching the filename */
1051 status = ssnprintf (typename, sizeof (typename), "%s.so", plugin_name);
1052 if ((status < 0) || ((size_t) status >= sizeof (typename)))
1054 WARNING ("plugin_load: Filename too long: \"%s.so\"", plugin_name);
1058 if ((dh = opendir (dir)) == NULL)
1061 ERROR ("plugin_load: opendir (%s) failed: %s", dir,
1062 sstrerror (errno, errbuf, sizeof (errbuf)));
1066 while ((de = readdir (dh)) != NULL)
1068 if (strcasecmp (de->d_name, typename))
1071 status = ssnprintf (filename, sizeof (filename),
1072 "%s/%s", dir, de->d_name);
1073 if ((status < 0) || ((size_t) status >= sizeof (filename)))
1075 WARNING ("plugin_load: Filename too long: \"%s/%s\"",
1080 if (lstat (filename, &statbuf) == -1)
1083 WARNING ("plugin_load: stat (\"%s\") failed: %s",
1085 sstrerror (errno, errbuf, sizeof (errbuf)));
1088 else if (!S_ISREG (statbuf.st_mode))
1090 /* don't follow symlinks */
1091 WARNING ("plugin_load: %s is not a regular file.",
1096 status = plugin_load_file (filename, flags);
1100 plugin_mark_loaded (plugin_name);
1102 INFO ("plugin_load: plugin \"%s\" successfully loaded.", plugin_name);
1107 ERROR ("plugin_load: Load plugin \"%s\" failed with "
1108 "status %i.", plugin_name, status);
1114 if (filename[0] == 0)
1115 ERROR ("plugin_load: Could not find plugin \"%s\" in %s",
1122 * The `register_*' functions follow
1124 int plugin_register_config (const char *name,
1125 int (*callback) (const char *key, const char *val),
1126 const char **keys, int keys_num)
1128 cf_register (name, callback, keys, keys_num);
1130 } /* int plugin_register_config */
1132 int plugin_register_complex_config (const char *type,
1133 int (*callback) (oconfig_item_t *))
1135 return (cf_register_complex (type, callback));
1136 } /* int plugin_register_complex_config */
1138 int plugin_register_init (const char *name,
1139 int (*callback) (void))
1141 return (create_register_callback (&list_init, name, (void *) callback,
1142 /* user_data = */ NULL));
1143 } /* plugin_register_init */
1145 static int plugin_compare_read_func (const void *arg0, const void *arg1)
1147 const read_func_t *rf0;
1148 const read_func_t *rf1;
1153 if (rf0->rf_next_read < rf1->rf_next_read)
1155 else if (rf0->rf_next_read > rf1->rf_next_read)
1159 } /* int plugin_compare_read_func */
1161 /* Add a read function to both, the heap and a linked list. The linked list if
1162 * used to look-up read functions, especially for the remove function. The heap
1163 * is used to determine which plugin to read next. */
1164 static int plugin_insert_read (read_func_t *rf)
1169 rf->rf_next_read = cdtime ();
1170 rf->rf_effective_interval = rf->rf_interval;
1172 pthread_mutex_lock (&read_lock);
1174 if (read_list == NULL)
1176 read_list = llist_create ();
1177 if (read_list == NULL)
1179 pthread_mutex_unlock (&read_lock);
1180 ERROR ("plugin_insert_read: read_list failed.");
1185 if (read_heap == NULL)
1187 read_heap = c_heap_create (plugin_compare_read_func);
1188 if (read_heap == NULL)
1190 pthread_mutex_unlock (&read_lock);
1191 ERROR ("plugin_insert_read: c_heap_create failed.");
1196 le = llist_search (read_list, rf->rf_name);
1199 pthread_mutex_unlock (&read_lock);
1200 WARNING ("The read function \"%s\" is already registered. "
1201 "Check for duplicate \"LoadPlugin\" lines "
1202 "in your configuration!",
1207 le = llentry_create (rf->rf_name, rf);
1210 pthread_mutex_unlock (&read_lock);
1211 ERROR ("plugin_insert_read: llentry_create failed.");
1215 status = c_heap_insert (read_heap, rf);
1218 pthread_mutex_unlock (&read_lock);
1219 ERROR ("plugin_insert_read: c_heap_insert failed.");
1220 llentry_destroy (le);
1224 /* This does not fail. */
1225 llist_append (read_list, le);
1227 /* Wake up all the read threads. */
1228 pthread_cond_broadcast (&read_cond);
1229 pthread_mutex_unlock (&read_lock);
1231 } /* int plugin_insert_read */
1233 int plugin_register_read (const char *name,
1234 int (*callback) (void))
1239 rf = calloc (1, sizeof (*rf));
1242 ERROR ("plugin_register_read: calloc failed.");
1246 rf->rf_callback = (void *) callback;
1247 rf->rf_udata.data = NULL;
1248 rf->rf_udata.free_func = NULL;
1249 rf->rf_ctx = plugin_get_ctx ();
1250 rf->rf_group[0] = '\0';
1251 rf->rf_name = strdup (name);
1252 rf->rf_type = RF_SIMPLE;
1253 rf->rf_interval = plugin_get_interval ();
1255 status = plugin_insert_read (rf);
1257 sfree (rf->rf_name);
1262 } /* int plugin_register_read */
1264 int plugin_register_complex_read (const char *group, const char *name,
1265 plugin_read_cb callback,
1267 user_data_t *user_data)
1272 rf = calloc (1,sizeof (*rf));
1275 ERROR ("plugin_register_complex_read: calloc failed.");
1279 rf->rf_callback = (void *) callback;
1281 sstrncpy (rf->rf_group, group, sizeof (rf->rf_group));
1283 rf->rf_group[0] = '\0';
1284 rf->rf_name = strdup (name);
1285 rf->rf_type = RF_COMPLEX;
1286 rf->rf_interval = (interval != 0) ? interval : plugin_get_interval ();
1289 if (user_data == NULL)
1291 rf->rf_udata.data = NULL;
1292 rf->rf_udata.free_func = NULL;
1296 rf->rf_udata = *user_data;
1299 rf->rf_ctx = plugin_get_ctx ();
1301 status = plugin_insert_read (rf);
1303 sfree (rf->rf_name);
1308 } /* int plugin_register_complex_read */
1310 int plugin_register_write (const char *name,
1311 plugin_write_cb callback, user_data_t *ud)
1313 return (create_register_callback (&list_write, name,
1314 (void *) callback, ud));
1315 } /* int plugin_register_write */
1317 static int plugin_flush_timeout_callback (user_data_t *ud)
1319 flush_callback_t *cb = ud->data;
1321 return plugin_flush (cb->name, cb->timeout, /* identifier = */ NULL);
1322 } /* static int plugin_flush_callback */
1324 static void plugin_flush_timeout_callback_free (void *data)
1326 flush_callback_t *cb = data;
1328 if (cb == NULL) return;
1332 } /* static void plugin_flush_callback_free */
1334 static char *plugin_flush_callback_name (const char *name)
1336 const char *flush_prefix = "flush/";
1341 prefix_size = strlen(flush_prefix);
1342 name_size = strlen(name);
1344 flush_name = malloc (name_size + prefix_size + 1);
1345 if (flush_name == NULL)
1347 ERROR ("plugin_flush_callback_name: malloc failed.");
1351 sstrncpy (flush_name, flush_prefix, prefix_size + 1);
1352 sstrncpy (flush_name + prefix_size, name, name_size + 1);
1355 } /* static char *plugin_flush_callback_name */
1357 int plugin_register_flush (const char *name,
1358 plugin_flush_cb callback, user_data_t *ud)
1361 plugin_ctx_t ctx = plugin_get_ctx ();
1363 status = create_register_callback (&list_flush, name,
1364 (void *) callback, ud);
1368 if (ctx.flush_interval != 0)
1371 flush_callback_t *cb;
1373 flush_name = plugin_flush_callback_name (name);
1374 if (flush_name == NULL)
1377 cb = malloc(sizeof (*cb));
1380 ERROR ("plugin_register_flush: malloc failed.");
1385 cb->name = strdup (name);
1386 if (cb->name == NULL)
1388 ERROR ("plugin_register_flush: strdup failed.");
1393 cb->timeout = ctx.flush_timeout;
1396 ud->free_func = plugin_flush_timeout_callback_free;
1398 status = plugin_register_complex_read (
1399 /* group = */ "flush",
1400 /* name = */ flush_name,
1401 /* callback = */ plugin_flush_timeout_callback,
1402 /* interval = */ ctx.flush_interval,
1403 /* user data = */ ud);
1415 } /* int plugin_register_flush */
1417 int plugin_register_missing (const char *name,
1418 plugin_missing_cb callback, user_data_t *ud)
1420 return (create_register_callback (&list_missing, name,
1421 (void *) callback, ud));
1422 } /* int plugin_register_missing */
1424 int plugin_register_shutdown (const char *name,
1425 int (*callback) (void))
1427 return (create_register_callback (&list_shutdown, name,
1428 (void *) callback, /* user_data = */ NULL));
1429 } /* int plugin_register_shutdown */
1431 static void plugin_free_data_sets (void)
1436 if (data_sets == NULL)
1439 while (c_avl_pick (data_sets, &key, &value) == 0)
1441 data_set_t *ds = value;
1442 /* key is a pointer to ds->type */
1448 c_avl_destroy (data_sets);
1450 } /* void plugin_free_data_sets */
1452 int plugin_register_data_set (const data_set_t *ds)
1454 data_set_t *ds_copy;
1456 if ((data_sets != NULL)
1457 && (c_avl_get (data_sets, ds->type, NULL) == 0))
1459 NOTICE ("Replacing DS `%s' with another version.", ds->type);
1460 plugin_unregister_data_set (ds->type);
1462 else if (data_sets == NULL)
1464 data_sets = c_avl_create ((int (*) (const void *, const void *)) strcmp);
1465 if (data_sets == NULL)
1469 ds_copy = malloc (sizeof (*ds_copy));
1470 if (ds_copy == NULL)
1472 memcpy(ds_copy, ds, sizeof (data_set_t));
1474 ds_copy->ds = malloc (sizeof (*ds_copy->ds)
1476 if (ds_copy->ds == NULL)
1482 for (size_t i = 0; i < ds->ds_num; i++)
1483 memcpy (ds_copy->ds + i, ds->ds + i, sizeof (data_source_t));
1485 return (c_avl_insert (data_sets, (void *) ds_copy->type, (void *) ds_copy));
1486 } /* int plugin_register_data_set */
1488 int plugin_register_log (const char *name,
1489 plugin_log_cb callback, user_data_t *ud)
1491 return (create_register_callback (&list_log, name,
1492 (void *) callback, ud));
1493 } /* int plugin_register_log */
1495 int plugin_register_notification (const char *name,
1496 plugin_notification_cb callback, user_data_t *ud)
1498 return (create_register_callback (&list_notification, name,
1499 (void *) callback, ud));
1500 } /* int plugin_register_log */
1502 int plugin_unregister_config (const char *name)
1504 cf_unregister (name);
1506 } /* int plugin_unregister_config */
1508 int plugin_unregister_complex_config (const char *name)
1510 cf_unregister_complex (name);
1512 } /* int plugin_unregister_complex_config */
1514 int plugin_unregister_init (const char *name)
1516 return (plugin_unregister (list_init, name));
1519 int plugin_unregister_read (const char *name) /* {{{ */
1527 pthread_mutex_lock (&read_lock);
1529 if (read_list == NULL)
1531 pthread_mutex_unlock (&read_lock);
1535 le = llist_search (read_list, name);
1538 pthread_mutex_unlock (&read_lock);
1539 WARNING ("plugin_unregister_read: No such read function: %s",
1544 llist_remove (read_list, le);
1547 assert (rf != NULL);
1548 rf->rf_type = RF_REMOVE;
1550 pthread_mutex_unlock (&read_lock);
1552 llentry_destroy (le);
1554 DEBUG ("plugin_unregister_read: Marked `%s' for removal.", name);
1557 } /* }}} int plugin_unregister_read */
1559 void plugin_log_available_writers (void)
1561 log_list_callbacks (&list_write, "Available write targets:");
1564 static int compare_read_func_group (llentry_t *e, void *ud) /* {{{ */
1566 read_func_t *rf = e->value;
1569 return strcmp (rf->rf_group, (const char *)group);
1570 } /* }}} int compare_read_func_group */
1572 int plugin_unregister_read_group (const char *group) /* {{{ */
1582 pthread_mutex_lock (&read_lock);
1584 if (read_list == NULL)
1586 pthread_mutex_unlock (&read_lock);
1592 le = llist_search_custom (read_list,
1593 compare_read_func_group, (void *)group);
1600 llist_remove (read_list, le);
1603 assert (rf != NULL);
1604 rf->rf_type = RF_REMOVE;
1606 llentry_destroy (le);
1608 DEBUG ("plugin_unregister_read_group: "
1609 "Marked `%s' (group `%s') for removal.",
1610 rf->rf_name, group);
1613 pthread_mutex_unlock (&read_lock);
1617 WARNING ("plugin_unregister_read_group: No such "
1618 "group of read function: %s", group);
1623 } /* }}} int plugin_unregister_read_group */
1625 int plugin_unregister_write (const char *name)
1627 return (plugin_unregister (list_write, name));
1630 int plugin_unregister_flush (const char *name)
1632 plugin_ctx_t ctx = plugin_get_ctx ();
1634 if (ctx.flush_interval != 0)
1638 flush_name = plugin_flush_callback_name (name);
1639 if (flush_name != NULL)
1641 plugin_unregister_read(flush_name);
1646 return plugin_unregister (list_flush, name);
1649 int plugin_unregister_missing (const char *name)
1651 return (plugin_unregister (list_missing, name));
1654 int plugin_unregister_shutdown (const char *name)
1656 return (plugin_unregister (list_shutdown, name));
1659 int plugin_unregister_data_set (const char *name)
1663 if (data_sets == NULL)
1666 if (c_avl_remove (data_sets, name, NULL, (void *) &ds) != 0)
1673 } /* int plugin_unregister_data_set */
1675 int plugin_unregister_log (const char *name)
1677 return (plugin_unregister (list_log, name));
1680 int plugin_unregister_notification (const char *name)
1682 return (plugin_unregister (list_notification, name));
1685 int plugin_init_all (void)
1687 char const *chain_name;
1692 /* Init the value cache */
1695 if (IS_TRUE (global_option_get ("CollectInternalStats")))
1696 record_statistics = 1;
1698 chain_name = global_option_get ("PreCacheChain");
1699 pre_cache_chain = fc_chain_get_by_name (chain_name);
1701 chain_name = global_option_get ("PostCacheChain");
1702 post_cache_chain = fc_chain_get_by_name (chain_name);
1704 write_limit_high = global_option_get_long ("WriteQueueLimitHigh",
1706 if (write_limit_high < 0)
1708 ERROR ("WriteQueueLimitHigh must be positive or zero.");
1709 write_limit_high = 0;
1712 write_limit_low = global_option_get_long ("WriteQueueLimitLow",
1713 /* default = */ write_limit_high / 2);
1714 if (write_limit_low < 0)
1716 ERROR ("WriteQueueLimitLow must be positive or zero.");
1717 write_limit_low = write_limit_high / 2;
1719 else if (write_limit_low > write_limit_high)
1721 ERROR ("WriteQueueLimitLow must not be larger than "
1722 "WriteQueueLimitHigh.");
1723 write_limit_low = write_limit_high;
1726 write_threads_num = global_option_get_long ("WriteThreads",
1728 if (write_threads_num < 1)
1730 ERROR ("WriteThreads must be positive.");
1731 write_threads_num = 5;
1734 if ((list_init == NULL) && (read_heap == NULL))
1737 /* Calling all init callbacks before checking if read callbacks
1738 * are available allows the init callbacks to register the read
1740 le = llist_head (list_init);
1743 callback_func_t *cf;
1744 plugin_init_cb callback;
1745 plugin_ctx_t old_ctx;
1748 old_ctx = plugin_set_ctx (cf->cf_ctx);
1749 callback = cf->cf_callback;
1750 status = (*callback) ();
1751 plugin_set_ctx (old_ctx);
1755 ERROR ("Initialization of plugin `%s' "
1756 "failed with status %i. "
1757 "Plugin will be unloaded.",
1759 /* Plugins that register read callbacks from the init
1760 * callback should take care of appropriate error
1761 * handling themselves. */
1762 /* FIXME: Unload _all_ functions */
1763 plugin_unregister_read (le->key);
1770 start_write_threads ((size_t) write_threads_num);
1772 max_read_interval = global_option_get_time ("MaxReadInterval",
1773 DEFAULT_MAX_READ_INTERVAL);
1775 /* Start read-threads */
1776 if (read_heap != NULL)
1781 rt = global_option_get ("ReadThreads");
1784 start_read_threads ((num > 0) ? num : 5);
1787 } /* void plugin_init_all */
1789 /* TODO: Rename this function. */
1790 void plugin_read_all (void)
1792 if(record_statistics) {
1793 plugin_update_internal_statistics ();
1795 uc_check_timeout ();
1798 } /* void plugin_read_all */
1800 /* Read function called when the `-T' command line argument is given. */
1801 int plugin_read_all_once (void)
1804 int return_status = 0;
1806 if (read_heap == NULL)
1808 NOTICE ("No read-functions are registered.");
1815 plugin_ctx_t old_ctx;
1817 rf = c_heap_get_root (read_heap);
1821 old_ctx = plugin_set_ctx (rf->rf_ctx);
1823 if (rf->rf_type == RF_SIMPLE)
1825 int (*callback) (void);
1827 callback = rf->rf_callback;
1828 status = (*callback) ();
1832 plugin_read_cb callback;
1834 callback = rf->rf_callback;
1835 status = (*callback) (&rf->rf_udata);
1838 plugin_set_ctx (old_ctx);
1842 NOTICE ("read-function of plugin `%s' failed.",
1847 sfree (rf->rf_name);
1848 destroy_callback ((void *) rf);
1851 return (return_status);
1852 } /* int plugin_read_all_once */
1854 int plugin_write (const char *plugin, /* {{{ */
1855 const data_set_t *ds, const value_list_t *vl)
1863 if (list_write == NULL)
1868 ds = plugin_get_ds (vl->type);
1871 ERROR ("plugin_write: Unable to lookup type `%s'.", vl->type);
1881 le = llist_head (list_write);
1884 callback_func_t *cf = le->value;
1885 plugin_write_cb callback;
1887 /* do not switch plugin context; rather keep the context (interval)
1888 * information of the calling read plugin */
1890 DEBUG ("plugin: plugin_write: Writing values via %s.", le->key);
1891 callback = cf->cf_callback;
1892 status = (*callback) (ds, vl, &cf->cf_udata);
1901 if ((success == 0) && (failure != 0))
1906 else /* plugin != NULL */
1908 callback_func_t *cf;
1909 plugin_write_cb callback;
1911 le = llist_head (list_write);
1914 if (strcasecmp (plugin, le->key) == 0)
1925 /* do not switch plugin context; rather keep the context (interval)
1926 * information of the calling read plugin */
1928 DEBUG ("plugin: plugin_write: Writing values via %s.", le->key);
1929 callback = cf->cf_callback;
1930 status = (*callback) (ds, vl, &cf->cf_udata);
1934 } /* }}} int plugin_write */
1936 int plugin_flush (const char *plugin, cdtime_t timeout, const char *identifier)
1940 if (list_flush == NULL)
1943 le = llist_head (list_flush);
1946 callback_func_t *cf;
1947 plugin_flush_cb callback;
1948 plugin_ctx_t old_ctx;
1950 if ((plugin != NULL)
1951 && (strcmp (plugin, le->key) != 0))
1958 old_ctx = plugin_set_ctx (cf->cf_ctx);
1959 callback = cf->cf_callback;
1961 (*callback) (timeout, identifier, &cf->cf_udata);
1963 plugin_set_ctx (old_ctx);
1968 } /* int plugin_flush */
1970 int plugin_shutdown_all (void)
1973 int ret = 0; // Assume success.
1975 destroy_all_callbacks (&list_init);
1977 stop_read_threads ();
1979 pthread_mutex_lock (&read_lock);
1980 llist_destroy (read_list);
1982 pthread_mutex_unlock (&read_lock);
1984 destroy_read_heap ();
1986 /* blocks until all write threads have shut down. */
1987 stop_write_threads ();
1989 /* ask all plugins to write out the state they kept. */
1990 plugin_flush (/* plugin = */ NULL,
1992 /* identifier = */ NULL);
1995 if (list_shutdown != NULL)
1996 le = llist_head (list_shutdown);
2000 callback_func_t *cf;
2001 plugin_shutdown_cb callback;
2002 plugin_ctx_t old_ctx;
2005 old_ctx = plugin_set_ctx (cf->cf_ctx);
2006 callback = cf->cf_callback;
2008 /* Advance the pointer before calling the callback allows
2009 * shutdown functions to unregister themselves. If done the
2010 * other way around the memory `le' points to will be freed
2011 * after callback returns. */
2014 if ((*callback) () != 0)
2017 plugin_set_ctx (old_ctx);
2020 /* Write plugins which use the `user_data' pointer usually need the
2021 * same data available to the flush callback. If this is the case, set
2022 * the free_function to NULL when registering the flush callback and to
2023 * the real free function when registering the write callback. This way
2024 * the data isn't freed twice. */
2025 destroy_all_callbacks (&list_flush);
2026 destroy_all_callbacks (&list_missing);
2027 destroy_all_callbacks (&list_write);
2029 destroy_all_callbacks (&list_notification);
2030 destroy_all_callbacks (&list_shutdown);
2031 destroy_all_callbacks (&list_log);
2033 plugin_free_loaded ();
2034 plugin_free_data_sets ();
2036 } /* void plugin_shutdown_all */
2038 int plugin_dispatch_missing (const value_list_t *vl) /* {{{ */
2042 if (list_missing == NULL)
2045 le = llist_head (list_missing);
2048 callback_func_t *cf;
2049 plugin_missing_cb callback;
2050 plugin_ctx_t old_ctx;
2054 old_ctx = plugin_set_ctx (cf->cf_ctx);
2055 callback = cf->cf_callback;
2057 status = (*callback) (vl, &cf->cf_udata);
2058 plugin_set_ctx (old_ctx);
2063 ERROR ("plugin_dispatch_missing: Callback function \"%s\" "
2064 "failed with status %i.",
2077 } /* int }}} plugin_dispatch_missing */
2079 static int plugin_dispatch_values_internal (value_list_t *vl)
2082 static c_complain_t no_write_complaint = C_COMPLAIN_INIT_STATIC;
2084 value_t *saved_values;
2085 int saved_values_len;
2089 _Bool free_meta_data = 0;
2091 assert (vl != NULL);
2093 /* These fields are initialized by plugin_value_list_clone() if needed: */
2094 assert (vl->host[0] != 0);
2095 assert (vl->time != 0); /* The time is determined at _enqueue_ time. */
2096 assert (vl->interval != 0);
2098 if (vl->type[0] == 0 || vl->values == NULL || vl->values_len < 1)
2100 ERROR ("plugin_dispatch_values: Invalid value list "
2101 "from plugin %s.", vl->plugin);
2105 /* Free meta data only if the calling function didn't specify any. In
2106 * this case matches and targets may add some and the calling function
2107 * may not expect (and therefore free) that data. */
2108 if (vl->meta == NULL)
2111 if (list_write == NULL)
2112 c_complain_once (LOG_WARNING, &no_write_complaint,
2113 "plugin_dispatch_values: No write callback has been "
2114 "registered. Please load at least one output plugin, "
2115 "if you want the collected data to be stored.");
2117 if (data_sets == NULL)
2119 ERROR ("plugin_dispatch_values: No data sets registered. "
2120 "Could the types database be read? Check "
2121 "your `TypesDB' setting!");
2125 if (c_avl_get (data_sets, vl->type, (void *) &ds) != 0)
2127 char ident[6 * DATA_MAX_NAME_LEN];
2129 FORMAT_VL (ident, sizeof (ident), vl);
2130 INFO ("plugin_dispatch_values: Dataset not found: %s "
2131 "(from \"%s\"), check your types.db!",
2136 DEBUG ("plugin_dispatch_values: time = %.3f; interval = %.3f; "
2138 "plugin = %s; plugin_instance = %s; "
2139 "type = %s; type_instance = %s;",
2140 CDTIME_T_TO_DOUBLE (vl->time),
2141 CDTIME_T_TO_DOUBLE (vl->interval),
2143 vl->plugin, vl->plugin_instance,
2144 vl->type, vl->type_instance);
2147 assert (0 == strcmp (ds->type, vl->type));
2149 if (0 != strcmp (ds->type, vl->type))
2150 WARNING ("plugin_dispatch_values: (ds->type = %s) != (vl->type = %s)",
2151 ds->type, vl->type);
2155 assert (ds->ds_num == vl->values_len);
2157 if (ds->ds_num != vl->values_len)
2159 ERROR ("plugin_dispatch_values: ds->type = %s: "
2160 "(ds->ds_num = %zu) != "
2161 "(vl->values_len = %zu)",
2162 ds->type, ds->ds_num, vl->values_len);
2167 escape_slashes (vl->host, sizeof (vl->host));
2168 escape_slashes (vl->plugin, sizeof (vl->plugin));
2169 escape_slashes (vl->plugin_instance, sizeof (vl->plugin_instance));
2170 escape_slashes (vl->type, sizeof (vl->type));
2171 escape_slashes (vl->type_instance, sizeof (vl->type_instance));
2173 /* Copy the values. This way, we can assure `targets' that they get
2174 * dynamically allocated values, which they can free and replace if
2176 if ((pre_cache_chain != NULL) || (post_cache_chain != NULL))
2178 saved_values = vl->values;
2179 saved_values_len = vl->values_len;
2181 vl->values = (value_t *) calloc (vl->values_len,
2182 sizeof (*vl->values));
2183 if (vl->values == NULL)
2185 ERROR ("plugin_dispatch_values: calloc failed.");
2186 vl->values = saved_values;
2189 memcpy (vl->values, saved_values,
2190 vl->values_len * sizeof (*vl->values));
2192 else /* if ((pre == NULL) && (post == NULL)) */
2194 saved_values = NULL;
2195 saved_values_len = 0;
2198 if (pre_cache_chain != NULL)
2200 status = fc_process_chain (ds, vl, pre_cache_chain);
2203 WARNING ("plugin_dispatch_values: Running the "
2204 "pre-cache chain failed with "
2208 else if (status == FC_TARGET_STOP)
2210 /* Restore the state of the value_list so that plugins
2211 * don't get confused.. */
2212 if (saved_values != NULL)
2215 vl->values = saved_values;
2216 vl->values_len = saved_values_len;
2222 /* Update the value cache */
2225 if (post_cache_chain != NULL)
2227 status = fc_process_chain (ds, vl, post_cache_chain);
2230 WARNING ("plugin_dispatch_values: Running the "
2231 "post-cache chain failed with "
2237 fc_default_action (ds, vl);
2239 /* Restore the state of the value_list so that plugins don't get
2241 if (saved_values != NULL)
2244 vl->values = saved_values;
2245 vl->values_len = saved_values_len;
2248 if ((free_meta_data != 0) && (vl->meta != NULL))
2250 meta_data_destroy (vl->meta);
2255 } /* int plugin_dispatch_values_internal */
2257 static double get_drop_probability (void) /* {{{ */
2263 pthread_mutex_lock (&write_lock);
2264 wql = write_queue_length;
2265 pthread_mutex_unlock (&write_lock);
2267 if (wql < write_limit_low)
2269 if (wql >= write_limit_high)
2272 pos = 1 + wql - write_limit_low;
2273 size = 1 + write_limit_high - write_limit_low;
2275 return (((double) pos) / ((double) size));
2276 } /* }}} double get_drop_probability */
2278 static _Bool check_drop_value (void) /* {{{ */
2280 static cdtime_t last_message_time = 0;
2281 static pthread_mutex_t last_message_lock = PTHREAD_MUTEX_INITIALIZER;
2287 if (write_limit_high == 0)
2290 p = get_drop_probability ();
2294 status = pthread_mutex_trylock (&last_message_lock);
2300 if ((now - last_message_time) > TIME_T_TO_CDTIME_T (1))
2302 last_message_time = now;
2303 ERROR ("plugin_dispatch_values: Low water mark "
2304 "reached. Dropping %.0f%% of metrics.",
2307 pthread_mutex_unlock (&last_message_lock);
2318 } /* }}} _Bool check_drop_value */
2320 int plugin_dispatch_values (value_list_t const *vl)
2323 static pthread_mutex_t statistics_lock = PTHREAD_MUTEX_INITIALIZER;
2325 if (check_drop_value ()) {
2326 if(record_statistics) {
2327 pthread_mutex_lock(&statistics_lock);
2328 stats_values_dropped++;
2329 pthread_mutex_unlock(&statistics_lock);
2334 status = plugin_write_enqueue (vl);
2338 ERROR ("plugin_dispatch_values: plugin_write_enqueue failed "
2339 "with status %i (%s).", status,
2340 sstrerror (status, errbuf, sizeof (errbuf)));
2347 __attribute__((sentinel))
2348 int plugin_dispatch_multivalue (value_list_t const *template, /* {{{ */
2349 _Bool store_percentage, int store_type, ...)
2356 assert (template->values_len == 1);
2358 /* Calculate sum for Gauge to calculate percent if needed */
2359 if (DS_TYPE_GAUGE == store_type) {
2360 va_start (ap, store_type);
2366 name = va_arg (ap, char const *);
2370 value = va_arg (ap, gauge_t);
2378 vl = plugin_value_list_clone (template);
2379 /* plugin_value_list_clone makes sure vl->time is set to non-zero. */
2380 if (store_percentage)
2381 sstrncpy (vl->type, "percent", sizeof (vl->type));
2383 va_start (ap, store_type);
2389 /* Set the type instance. */
2390 name = va_arg (ap, char const *);
2393 sstrncpy (vl->type_instance, name, sizeof (vl->type_instance));
2395 /* Set the value. */
2399 vl->values[0].gauge = va_arg (ap, gauge_t);
2400 if (store_percentage)
2401 vl->values[0].gauge *= sum ? (100.0 / sum) : NAN;
2403 case DS_TYPE_ABSOLUTE:
2404 vl->values[0].absolute = va_arg (ap, absolute_t);
2406 case DS_TYPE_COUNTER:
2407 vl->values[0].counter = va_arg (ap, counter_t);
2409 case DS_TYPE_DERIVE:
2410 vl->values[0].derive = va_arg (ap, derive_t);
2413 ERROR ("plugin_dispatch_multivalue: given store_type is incorrect.");
2418 status = plugin_write_enqueue (vl);
2424 plugin_value_list_free (vl);
2426 } /* }}} int plugin_dispatch_multivalue */
2428 int plugin_dispatch_notification (const notification_t *notif)
2431 /* Possible TODO: Add flap detection here */
2433 DEBUG ("plugin_dispatch_notification: severity = %i; message = %s; "
2434 "time = %.3f; host = %s;",
2435 notif->severity, notif->message,
2436 CDTIME_T_TO_DOUBLE (notif->time), notif->host);
2438 /* Nobody cares for notifications */
2439 if (list_notification == NULL)
2442 le = llist_head (list_notification);
2445 callback_func_t *cf;
2446 plugin_notification_cb callback;
2449 /* do not switch plugin context; rather keep the context
2450 * (interval) information of the calling plugin */
2453 callback = cf->cf_callback;
2454 status = (*callback) (notif, &cf->cf_udata);
2457 WARNING ("plugin_dispatch_notification: Notification "
2458 "callback %s returned %i.",
2466 } /* int plugin_dispatch_notification */
2468 void plugin_log (int level, const char *format, ...)
2475 if (level >= LOG_DEBUG)
2479 va_start (ap, format);
2480 vsnprintf (msg, sizeof (msg), format, ap);
2481 msg[sizeof (msg) - 1] = '\0';
2484 if (list_log == NULL)
2486 fprintf (stderr, "%s\n", msg);
2490 le = llist_head (list_log);
2493 callback_func_t *cf;
2494 plugin_log_cb callback;
2497 callback = cf->cf_callback;
2499 /* do not switch plugin context; rather keep the context
2500 * (interval) information of the calling plugin */
2502 (*callback) (level, msg, &cf->cf_udata);
2506 } /* void plugin_log */
2508 int parse_log_severity (const char *severity)
2512 if ((0 == strcasecmp (severity, "emerg"))
2513 || (0 == strcasecmp (severity, "alert"))
2514 || (0 == strcasecmp (severity, "crit"))
2515 || (0 == strcasecmp (severity, "err")))
2516 log_level = LOG_ERR;
2517 else if (0 == strcasecmp (severity, "warning"))
2518 log_level = LOG_WARNING;
2519 else if (0 == strcasecmp (severity, "notice"))
2520 log_level = LOG_NOTICE;
2521 else if (0 == strcasecmp (severity, "info"))
2522 log_level = LOG_INFO;
2524 else if (0 == strcasecmp (severity, "debug"))
2525 log_level = LOG_DEBUG;
2526 #endif /* COLLECT_DEBUG */
2529 } /* int parse_log_severity */
2531 int parse_notif_severity (const char *severity)
2533 int notif_severity = -1;
2535 if (strcasecmp (severity, "FAILURE") == 0)
2536 notif_severity = NOTIF_FAILURE;
2537 else if (strcmp (severity, "OKAY") == 0)
2538 notif_severity = NOTIF_OKAY;
2539 else if ((strcmp (severity, "WARNING") == 0)
2540 || (strcmp (severity, "WARN") == 0))
2541 notif_severity = NOTIF_WARNING;
2543 return (notif_severity);
2544 } /* int parse_notif_severity */
2546 const data_set_t *plugin_get_ds (const char *name)
2550 if (data_sets == NULL)
2552 ERROR ("plugin_get_ds: No data sets are defined yet.");
2556 if (c_avl_get (data_sets, name, (void *) &ds) != 0)
2558 DEBUG ("No such dataset registered: %s", name);
2563 } /* data_set_t *plugin_get_ds */
2565 static int plugin_notification_meta_add (notification_t *n,
2567 enum notification_meta_type_e type,
2570 notification_meta_t *meta;
2571 notification_meta_t *tail;
2573 if ((n == NULL) || (name == NULL) || (value == NULL))
2575 ERROR ("plugin_notification_meta_add: A pointer is NULL!");
2579 meta = calloc (1, sizeof (*meta));
2582 ERROR ("plugin_notification_meta_add: calloc failed.");
2586 sstrncpy (meta->name, name, sizeof (meta->name));
2591 case NM_TYPE_STRING:
2593 meta->nm_value.nm_string = strdup ((const char *) value);
2594 if (meta->nm_value.nm_string == NULL)
2596 ERROR ("plugin_notification_meta_add: strdup failed.");
2602 case NM_TYPE_SIGNED_INT:
2604 meta->nm_value.nm_signed_int = *((int64_t *) value);
2607 case NM_TYPE_UNSIGNED_INT:
2609 meta->nm_value.nm_unsigned_int = *((uint64_t *) value);
2612 case NM_TYPE_DOUBLE:
2614 meta->nm_value.nm_double = *((double *) value);
2617 case NM_TYPE_BOOLEAN:
2619 meta->nm_value.nm_boolean = *((_Bool *) value);
2624 ERROR ("plugin_notification_meta_add: Unknown type: %i", type);
2628 } /* switch (type) */
2632 while ((tail != NULL) && (tail->next != NULL))
2641 } /* int plugin_notification_meta_add */
2643 int plugin_notification_meta_add_string (notification_t *n,
2647 return (plugin_notification_meta_add (n, name, NM_TYPE_STRING, value));
2650 int plugin_notification_meta_add_signed_int (notification_t *n,
2654 return (plugin_notification_meta_add (n, name, NM_TYPE_SIGNED_INT, &value));
2657 int plugin_notification_meta_add_unsigned_int (notification_t *n,
2661 return (plugin_notification_meta_add (n, name, NM_TYPE_UNSIGNED_INT, &value));
2664 int plugin_notification_meta_add_double (notification_t *n,
2668 return (plugin_notification_meta_add (n, name, NM_TYPE_DOUBLE, &value));
2671 int plugin_notification_meta_add_boolean (notification_t *n,
2675 return (plugin_notification_meta_add (n, name, NM_TYPE_BOOLEAN, &value));
2678 int plugin_notification_meta_copy (notification_t *dst,
2679 const notification_t *src)
2681 assert (dst != NULL);
2682 assert (src != NULL);
2683 assert (dst != src);
2684 assert ((src->meta == NULL) || (src->meta != dst->meta));
2686 for (notification_meta_t *meta = src->meta; meta != NULL; meta = meta->next)
2688 if (meta->type == NM_TYPE_STRING)
2689 plugin_notification_meta_add_string (dst, meta->name,
2690 meta->nm_value.nm_string);
2691 else if (meta->type == NM_TYPE_SIGNED_INT)
2692 plugin_notification_meta_add_signed_int (dst, meta->name,
2693 meta->nm_value.nm_signed_int);
2694 else if (meta->type == NM_TYPE_UNSIGNED_INT)
2695 plugin_notification_meta_add_unsigned_int (dst, meta->name,
2696 meta->nm_value.nm_unsigned_int);
2697 else if (meta->type == NM_TYPE_DOUBLE)
2698 plugin_notification_meta_add_double (dst, meta->name,
2699 meta->nm_value.nm_double);
2700 else if (meta->type == NM_TYPE_BOOLEAN)
2701 plugin_notification_meta_add_boolean (dst, meta->name,
2702 meta->nm_value.nm_boolean);
2706 } /* int plugin_notification_meta_copy */
2708 int plugin_notification_meta_free (notification_meta_t *n)
2710 notification_meta_t *this;
2711 notification_meta_t *next;
2715 ERROR ("plugin_notification_meta_free: n == NULL!");
2720 while (this != NULL)
2724 if (this->type == NM_TYPE_STRING)
2726 /* Assign to a temporary variable to work around nm_string's const
2728 void *tmp = (void *) this->nm_value.nm_string;
2731 this->nm_value.nm_string = NULL;
2739 } /* int plugin_notification_meta_free */
2741 static void plugin_ctx_destructor (void *ctx)
2744 } /* void plugin_ctx_destructor */
2746 static plugin_ctx_t ctx_init = { /* interval = */ 0 };
2748 static plugin_ctx_t *plugin_ctx_create (void)
2752 ctx = malloc (sizeof (*ctx));
2755 ERROR ("Failed to allocate plugin context: %s",
2756 sstrerror (errno, errbuf, sizeof (errbuf)));
2761 assert (plugin_ctx_key_initialized);
2762 pthread_setspecific (plugin_ctx_key, ctx);
2763 DEBUG("Created new plugin context.");
2765 } /* int plugin_ctx_create */
2767 void plugin_init_ctx (void)
2769 pthread_key_create (&plugin_ctx_key, plugin_ctx_destructor);
2770 plugin_ctx_key_initialized = 1;
2771 } /* void plugin_init_ctx */
2773 plugin_ctx_t plugin_get_ctx (void)
2777 assert (plugin_ctx_key_initialized);
2778 ctx = pthread_getspecific (plugin_ctx_key);
2781 ctx = plugin_ctx_create ();
2782 /* this must no happen -- exit() instead? */
2788 } /* plugin_ctx_t plugin_get_ctx */
2790 plugin_ctx_t plugin_set_ctx (plugin_ctx_t ctx)
2795 assert (plugin_ctx_key_initialized);
2796 c = pthread_getspecific (plugin_ctx_key);
2799 c = plugin_ctx_create ();
2800 /* this must no happen -- exit() instead? */
2809 } /* void plugin_set_ctx */
2811 cdtime_t plugin_get_interval (void)
2815 interval = plugin_get_ctx().interval;
2819 return cf_get_default_interval ();
2820 } /* cdtime_t plugin_get_interval */
2824 void *(*start_routine) (void *);
2828 static void *plugin_thread_start (void *arg)
2830 plugin_thread_t *plugin_thread = arg;
2832 void *(*start_routine) (void *) = plugin_thread->start_routine;
2833 void *plugin_arg = plugin_thread->arg;
2835 plugin_set_ctx (plugin_thread->ctx);
2837 sfree (plugin_thread);
2839 return start_routine (plugin_arg);
2840 } /* void *plugin_thread_start */
2842 int plugin_thread_create (pthread_t *thread, const pthread_attr_t *attr,
2843 void *(*start_routine) (void *), void *arg)
2845 plugin_thread_t *plugin_thread;
2847 plugin_thread = malloc (sizeof (*plugin_thread));
2848 if (plugin_thread == NULL)
2851 plugin_thread->ctx = plugin_get_ctx ();
2852 plugin_thread->start_routine = start_routine;
2853 plugin_thread->arg = arg;
2855 return pthread_create (thread, attr,
2856 plugin_thread_start, plugin_thread);
2857 } /* int plugin_thread_create */
2859 /* vim: set sw=8 ts=8 noet fdm=marker : */