0f067374d05e7148ce79ae32a44d531e5db42ac2
1 /**
2 * collectd - src/plugin.c
3 * Copyright (C) 2005-2014 Florian octo Forster
4 *
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:
11 *
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
14 *
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.
22 *
23 * Authors:
24 * Florian octo Forster <octo at collectd.org>
25 * Sebastian Harl <sh at tokkee.org>
26 **/
28 /* _GNU_SOURCE is needed in Linux to use pthread_setname_np */
29 #define _GNU_SOURCE
31 #include "collectd.h"
33 #include "common.h"
34 #include "configfile.h"
35 #include "filter_chain.h"
36 #include "plugin.h"
37 #include "utils_avltree.h"
38 #include "utils_cache.h"
39 #include "utils_complain.h"
40 #include "utils_heap.h"
41 #include "utils_llist.h"
42 #include "utils_random.h"
43 #include "utils_time.h"
45 #if HAVE_PTHREAD_NP_H
46 #include <pthread_np.h> /* for pthread_set_name_np(3) */
47 #endif
49 #include <ltdl.h>
51 /*
52 * Private structures
53 */
54 struct callback_func_s {
55 void *cf_callback;
56 user_data_t cf_udata;
57 plugin_ctx_t cf_ctx;
58 };
59 typedef struct callback_func_s callback_func_t;
61 #define RF_SIMPLE 0
62 #define RF_COMPLEX 1
63 #define RF_REMOVE 65535
64 struct read_func_s {
65 /* `read_func_t' "inherits" from `callback_func_t'.
66 * The `rf_super' member MUST be the first one in this structure! */
67 #define rf_callback rf_super.cf_callback
68 #define rf_udata rf_super.cf_udata
69 #define rf_ctx rf_super.cf_ctx
70 callback_func_t rf_super;
71 char rf_group[DATA_MAX_NAME_LEN];
72 char *rf_name;
73 int rf_type;
74 cdtime_t rf_interval;
75 cdtime_t rf_effective_interval;
76 cdtime_t rf_next_read;
77 };
78 typedef struct read_func_s read_func_t;
80 struct write_queue_s;
81 typedef struct write_queue_s write_queue_t;
82 struct write_queue_s {
83 value_list_t *vl;
84 plugin_ctx_t ctx;
85 write_queue_t *next;
86 };
88 struct flush_callback_s {
89 char *name;
90 cdtime_t timeout;
91 };
92 typedef struct flush_callback_s flush_callback_t;
94 /*
95 * Private variables
96 */
97 static c_avl_tree_t *plugins_loaded = NULL;
99 static llist_t *list_init;
100 static llist_t *list_write;
101 static llist_t *list_flush;
102 static llist_t *list_missing;
103 static llist_t *list_shutdown;
104 static llist_t *list_log;
105 static llist_t *list_notification;
107 static fc_chain_t *pre_cache_chain = NULL;
108 static fc_chain_t *post_cache_chain = NULL;
110 static c_avl_tree_t *data_sets;
112 static char *plugindir = NULL;
114 #ifndef DEFAULT_MAX_READ_INTERVAL
115 #define DEFAULT_MAX_READ_INTERVAL TIME_T_TO_CDTIME_T_STATIC(86400)
116 #endif
117 static c_heap_t *read_heap = NULL;
118 static llist_t *read_list;
119 static int read_loop = 1;
120 static pthread_mutex_t read_lock = PTHREAD_MUTEX_INITIALIZER;
121 static pthread_cond_t read_cond = PTHREAD_COND_INITIALIZER;
122 static pthread_t *read_threads = NULL;
123 static size_t read_threads_num = 0;
124 static cdtime_t max_read_interval = DEFAULT_MAX_READ_INTERVAL;
126 static write_queue_t *write_queue_head;
127 static write_queue_t *write_queue_tail;
128 static long write_queue_length = 0;
129 static _Bool write_loop = 1;
130 static pthread_mutex_t write_lock = PTHREAD_MUTEX_INITIALIZER;
131 static pthread_cond_t write_cond = PTHREAD_COND_INITIALIZER;
132 static pthread_t *write_threads = NULL;
133 static size_t write_threads_num = 0;
135 static pthread_key_t plugin_ctx_key;
136 static _Bool plugin_ctx_key_initialized = 0;
138 static long write_limit_high = 0;
139 static long write_limit_low = 0;
141 static derive_t stats_values_dropped = 0;
142 static _Bool record_statistics = 0;
144 /*
145 * Static functions
146 */
147 static int plugin_dispatch_values_internal(value_list_t *vl);
149 static const char *plugin_get_dir(void) {
150 if (plugindir == NULL)
151 return (PLUGINDIR);
152 else
153 return (plugindir);
154 }
156 static int plugin_update_internal_statistics(void) { /* {{{ */
157 gauge_t copy_write_queue_length = (gauge_t)write_queue_length;
159 /* Initialize `vl' */
160 value_list_t vl = VALUE_LIST_INIT;
161 sstrncpy(vl.plugin, "collectd", sizeof(vl.plugin));
162 vl.interval = plugin_get_interval();
164 /* Write queue */
165 sstrncpy(vl.plugin_instance, "write_queue", sizeof(vl.plugin_instance));
167 /* Write queue : queue length */
168 vl.values = &(value_t){.gauge = copy_write_queue_length};
169 vl.values_len = 1;
170 sstrncpy(vl.type, "queue_length", sizeof(vl.type));
171 vl.type_instance[0] = 0;
172 plugin_dispatch_values(&vl);
174 /* Write queue : Values dropped (queue length > low limit) */
175 vl.values = &(value_t){.gauge = (gauge_t)stats_values_dropped};
176 vl.values_len = 1;
177 sstrncpy(vl.type, "derive", sizeof(vl.type));
178 sstrncpy(vl.type_instance, "dropped", sizeof(vl.type_instance));
179 plugin_dispatch_values(&vl);
181 /* Cache */
182 sstrncpy(vl.plugin_instance, "cache", sizeof(vl.plugin_instance));
184 /* Cache : Nb entry in cache tree */
185 vl.values = &(value_t){.gauge = (gauge_t)uc_get_size()};
186 vl.values_len = 1;
187 sstrncpy(vl.type, "cache_size", sizeof(vl.type));
188 vl.type_instance[0] = 0;
189 plugin_dispatch_values(&vl);
191 return 0;
192 } /* }}} int plugin_update_internal_statistics */
194 static void destroy_callback(callback_func_t *cf) /* {{{ */
195 {
196 if (cf == NULL)
197 return;
199 if ((cf->cf_udata.data != NULL) && (cf->cf_udata.free_func != NULL)) {
200 cf->cf_udata.free_func(cf->cf_udata.data);
201 cf->cf_udata.data = NULL;
202 cf->cf_udata.free_func = NULL;
203 }
204 sfree(cf);
205 } /* }}} void destroy_callback */
207 static void destroy_all_callbacks(llist_t **list) /* {{{ */
208 {
209 llentry_t *le;
211 if (*list == NULL)
212 return;
214 le = llist_head(*list);
215 while (le != NULL) {
216 llentry_t *le_next;
218 le_next = le->next;
220 sfree(le->key);
221 destroy_callback(le->value);
222 le->value = NULL;
224 le = le_next;
225 }
227 llist_destroy(*list);
228 *list = NULL;
229 } /* }}} void destroy_all_callbacks */
231 static void destroy_read_heap(void) /* {{{ */
232 {
233 if (read_heap == NULL)
234 return;
236 while (42) {
237 read_func_t *rf;
239 rf = c_heap_get_root(read_heap);
240 if (rf == NULL)
241 break;
242 sfree(rf->rf_name);
243 destroy_callback((callback_func_t *)rf);
244 }
246 c_heap_destroy(read_heap);
247 read_heap = NULL;
248 } /* }}} void destroy_read_heap */
250 static int register_callback(llist_t **list, /* {{{ */
251 const char *name, callback_func_t *cf) {
252 llentry_t *le;
253 char *key;
255 if (*list == NULL) {
256 *list = llist_create();
257 if (*list == NULL) {
258 ERROR("plugin: register_callback: "
259 "llist_create failed.");
260 destroy_callback(cf);
261 return (-1);
262 }
263 }
265 key = strdup(name);
266 if (key == NULL) {
267 ERROR("plugin: register_callback: strdup failed.");
268 destroy_callback(cf);
269 return (-1);
270 }
272 le = llist_search(*list, name);
273 if (le == NULL) {
274 le = llentry_create(key, cf);
275 if (le == NULL) {
276 ERROR("plugin: register_callback: "
277 "llentry_create failed.");
278 sfree(key);
279 destroy_callback(cf);
280 return (-1);
281 }
283 llist_append(*list, le);
284 } else {
285 callback_func_t *old_cf;
287 old_cf = le->value;
288 le->value = cf;
290 WARNING("plugin: register_callback: "
291 "a callback named `%s' already exists - "
292 "overwriting the old entry!",
293 name);
295 destroy_callback(old_cf);
296 sfree(key);
297 }
299 return (0);
300 } /* }}} int register_callback */
302 static void log_list_callbacks(llist_t **list, /* {{{ */
303 const char *comment) {
304 char *str;
305 int len;
306 int i;
307 llentry_t *le;
308 int n;
309 char **keys;
311 n = llist_size(*list);
312 if (n == 0) {
313 INFO("%s [none]", comment);
314 return;
315 }
317 keys = calloc(n, sizeof(char *));
319 if (keys == NULL) {
320 ERROR("%s: failed to allocate memory for list of callbacks", comment);
322 return;
323 }
325 for (le = llist_head(*list), i = 0, len = 0; le != NULL; le = le->next, i++) {
326 keys[i] = le->key;
327 len += strlen(le->key) + 6;
328 }
329 str = malloc(len + 10);
330 if (str == NULL) {
331 ERROR("%s: failed to allocate memory for list of callbacks", comment);
332 } else {
333 *str = '\0';
334 strjoin(str, len, keys, n, "', '");
335 INFO("%s ['%s']", comment, str);
336 sfree(str);
337 }
338 sfree(keys);
339 } /* }}} void log_list_callbacks */
341 static int create_register_callback(llist_t **list, /* {{{ */
342 const char *name, void *callback,
343 user_data_t const *ud) {
344 callback_func_t *cf;
346 cf = calloc(1, sizeof(*cf));
347 if (cf == NULL) {
348 ERROR("plugin: create_register_callback: calloc failed.");
349 return (-1);
350 }
352 cf->cf_callback = callback;
353 if (ud == NULL) {
354 cf->cf_udata.data = NULL;
355 cf->cf_udata.free_func = NULL;
356 } else {
357 cf->cf_udata = *ud;
358 }
360 cf->cf_ctx = plugin_get_ctx();
362 return (register_callback(list, name, cf));
363 } /* }}} int create_register_callback */
365 static int plugin_unregister(llist_t *list, const char *name) /* {{{ */
366 {
367 llentry_t *e;
369 if (list == NULL)
370 return (-1);
372 e = llist_search(list, name);
373 if (e == NULL)
374 return (-1);
376 llist_remove(list, e);
378 sfree(e->key);
379 destroy_callback(e->value);
381 llentry_destroy(e);
383 return (0);
384 } /* }}} int plugin_unregister */
386 /*
387 * (Try to) load the shared object `file'. Won't complain if it isn't a shared
388 * object, but it will bitch about a shared object not having a
389 * ``module_register'' symbol..
390 */
391 static int plugin_load_file(char *file, uint32_t flags) {
392 lt_dlhandle dlh;
393 void (*reg_handle)(void);
395 lt_dlinit();
396 lt_dlerror(); /* clear errors */
398 #if LIBTOOL_VERSION == 2
399 if (flags & PLUGIN_FLAGS_GLOBAL) {
400 lt_dladvise advise;
401 lt_dladvise_init(&advise);
402 lt_dladvise_global(&advise);
403 dlh = lt_dlopenadvise(file, advise);
404 lt_dladvise_destroy(&advise);
405 } else {
406 dlh = lt_dlopen(file);
407 }
408 #else /* if LIBTOOL_VERSION == 1 */
409 if (flags & PLUGIN_FLAGS_GLOBAL)
410 WARNING("plugin_load_file: The global flag is not supported, "
411 "libtool 2 is required for this.");
412 dlh = lt_dlopen(file);
413 #endif
415 if (dlh == NULL) {
416 char errbuf[1024] = "";
418 ssnprintf(errbuf, sizeof(errbuf),
419 "lt_dlopen (\"%s\") failed: %s. "
420 "The most common cause for this problem is "
421 "missing dependencies. Use ldd(1) to check "
422 "the dependencies of the plugin "
423 "/ shared object.",
424 file, lt_dlerror());
426 ERROR("%s", errbuf);
427 /* Make sure this is printed to STDERR in any case, but also
428 * make sure it's printed only once. */
429 if (list_log != NULL)
430 fprintf(stderr, "ERROR: %s\n", errbuf);
432 return (1);
433 }
435 if ((reg_handle = (void (*)(void))lt_dlsym(dlh, "module_register")) == NULL) {
436 WARNING("Couldn't find symbol \"module_register\" in \"%s\": %s\n", file,
437 lt_dlerror());
438 lt_dlclose(dlh);
439 return (-1);
440 }
442 (*reg_handle)();
444 return (0);
445 }
447 static void *plugin_read_thread(void __attribute__((unused)) * args) {
448 while (read_loop != 0) {
449 read_func_t *rf;
450 plugin_ctx_t old_ctx;
451 cdtime_t start;
452 cdtime_t now;
453 cdtime_t elapsed;
454 int status;
455 int rf_type;
456 int rc;
458 /* Get the read function that needs to be read next.
459 * We don't need to hold "read_lock" for the heap, but we need
460 * to call c_heap_get_root() and pthread_cond_wait() in the
461 * same protected block. */
462 pthread_mutex_lock(&read_lock);
463 rf = c_heap_get_root(read_heap);
464 if (rf == NULL) {
465 pthread_cond_wait(&read_cond, &read_lock);
466 pthread_mutex_unlock(&read_lock);
467 continue;
468 }
469 pthread_mutex_unlock(&read_lock);
471 if (rf->rf_interval == 0) {
472 /* this should not happen, because the interval is set
473 * for each plugin when loading it
474 * XXX: issue a warning? */
475 rf->rf_interval = plugin_get_interval();
476 rf->rf_effective_interval = rf->rf_interval;
478 rf->rf_next_read = cdtime();
479 }
481 /* sleep until this entry is due,
482 * using pthread_cond_timedwait */
483 pthread_mutex_lock(&read_lock);
484 /* In pthread_cond_timedwait, spurious wakeups are possible
485 * (and really happen, at least on NetBSD with > 1 CPU), thus
486 * we need to re-evaluate the condition every time
487 * pthread_cond_timedwait returns. */
488 rc = 0;
489 while ((read_loop != 0) && (cdtime() < rf->rf_next_read) && rc == 0) {
490 rc = pthread_cond_timedwait(&read_cond, &read_lock,
491 &CDTIME_T_TO_TIMESPEC(rf->rf_next_read));
492 }
494 /* Must hold `read_lock' when accessing `rf->rf_type'. */
495 rf_type = rf->rf_type;
496 pthread_mutex_unlock(&read_lock);
498 /* Check if we're supposed to stop.. This may have interrupted
499 * the sleep, too. */
500 if (read_loop == 0) {
501 /* Insert `rf' again, so it can be free'd correctly */
502 c_heap_insert(read_heap, rf);
503 break;
504 }
506 /* The entry has been marked for deletion. The linked list
507 * entry has already been removed by `plugin_unregister_read'.
508 * All we have to do here is free the `read_func_t' and
509 * continue. */
510 if (rf_type == RF_REMOVE) {
511 DEBUG("plugin_read_thread: Destroying the `%s' "
512 "callback.",
513 rf->rf_name);
514 sfree(rf->rf_name);
515 destroy_callback((callback_func_t *)rf);
516 rf = NULL;
517 continue;
518 }
520 DEBUG("plugin_read_thread: Handling `%s'.", rf->rf_name);
522 start = cdtime();
524 old_ctx = plugin_set_ctx(rf->rf_ctx);
526 if (rf_type == RF_SIMPLE) {
527 int (*callback)(void);
529 callback = rf->rf_callback;
530 status = (*callback)();
531 } else {
532 plugin_read_cb callback;
534 assert(rf_type == RF_COMPLEX);
536 callback = rf->rf_callback;
537 status = (*callback)(&rf->rf_udata);
538 }
540 plugin_set_ctx(old_ctx);
542 /* If the function signals failure, we will increase the
543 * intervals in which it will be called. */
544 if (status != 0) {
545 rf->rf_effective_interval *= 2;
546 if (rf->rf_effective_interval > max_read_interval)
547 rf->rf_effective_interval = max_read_interval;
549 NOTICE("read-function of plugin `%s' failed. "
550 "Will suspend it for %.3f seconds.",
551 rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
552 } else {
553 /* Success: Restore the interval, if it was changed. */
554 rf->rf_effective_interval = rf->rf_interval;
555 }
557 /* update the ``next read due'' field */
558 now = cdtime();
560 /* calculate the time spent in the read function */
561 elapsed = (now - start);
563 if (elapsed > rf->rf_effective_interval)
564 WARNING(
565 "plugin_read_thread: read-function of the `%s' plugin took %.3f "
566 "seconds, which is above its read interval (%.3f seconds). You might "
567 "want to adjust the `Interval' or `ReadThreads' settings.",
568 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed),
569 CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
571 DEBUG("plugin_read_thread: read-function of the `%s' plugin took "
572 "%.6f seconds.",
573 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed));
575 DEBUG("plugin_read_thread: Effective interval of the "
576 "`%s' plugin is %.3f seconds.",
577 rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
579 /* Calculate the next (absolute) time at which this function
580 * should be called. */
581 rf->rf_next_read += rf->rf_effective_interval;
583 /* Check, if `rf_next_read' is in the past. */
584 if (rf->rf_next_read < now) {
585 /* `rf_next_read' is in the past. Insert `now'
586 * so this value doesn't trail off into the
587 * past too much. */
588 rf->rf_next_read = now;
589 }
591 DEBUG("plugin_read_thread: Next read of the `%s' plugin at %.3f.",
592 rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_next_read));
594 /* Re-insert this read function into the heap again. */
595 c_heap_insert(read_heap, rf);
596 } /* while (read_loop) */
598 pthread_exit(NULL);
599 return ((void *)0);
600 } /* void *plugin_read_thread */
602 #ifdef PTHREAD_MAX_NAMELEN_NP
603 #define THREAD_NAME_MAX PTHREAD_MAX_NAMELEN_NP
604 #else
605 #define THREAD_NAME_MAX 16
606 #endif
608 static void set_thread_name(pthread_t tid, char const *name) {
609 #if defined(HAVE_PTHREAD_SETNAME_NP) || defined(HAVE_PTHREAD_SET_NAME_NP)
611 /* glibc limits the length of the name and fails if the passed string
612 * is too long, so we truncate it here. */
613 char n[THREAD_NAME_MAX];
614 if (strlen(name) >= THREAD_NAME_MAX)
615 WARNING("set_thread_name(\"%s\"): name too long", name);
616 sstrncpy(n, name, sizeof(n));
618 #if defined(HAVE_PTHREAD_SETNAME_NP)
619 int status = pthread_setname_np(tid, n);
620 if (status != 0) {
621 char errbuf[1024];
622 ERROR("set_thread_name(\"%s\"): %s", n,
623 sstrerror(status, errbuf, sizeof(errbuf)));
624 }
625 #else /* if defined(HAVE_PTHREAD_SET_NAME_NP) */
626 pthread_set_name_np(tid, n);
627 #endif
629 #endif
630 }
632 static void start_read_threads(size_t num) /* {{{ */
633 {
634 if (read_threads != NULL)
635 return;
637 read_threads = (pthread_t *)calloc(num, sizeof(pthread_t));
638 if (read_threads == NULL) {
639 ERROR("plugin: start_read_threads: calloc failed.");
640 return;
641 }
643 read_threads_num = 0;
644 for (size_t i = 0; i < num; i++) {
645 int status = pthread_create(read_threads + read_threads_num,
646 /* attr = */ NULL, plugin_read_thread,
647 /* arg = */ NULL);
648 if (status != 0) {
649 char errbuf[1024];
650 ERROR("plugin: start_read_threads: pthread_create failed "
651 "with status %i (%s).",
652 status, sstrerror(status, errbuf, sizeof(errbuf)));
653 return;
654 }
656 char name[THREAD_NAME_MAX];
657 ssnprintf(name, sizeof(name), "reader#%zu", read_threads_num);
658 set_thread_name(read_threads[read_threads_num], name);
660 read_threads_num++;
661 } /* for (i) */
662 } /* }}} void start_read_threads */
664 static void stop_read_threads(void) {
665 if (read_threads == NULL)
666 return;
668 INFO("collectd: Stopping %zu read threads.", read_threads_num);
670 pthread_mutex_lock(&read_lock);
671 read_loop = 0;
672 DEBUG("plugin: stop_read_threads: Signalling `read_cond'");
673 pthread_cond_broadcast(&read_cond);
674 pthread_mutex_unlock(&read_lock);
676 for (size_t i = 0; i < read_threads_num; i++) {
677 if (pthread_join(read_threads[i], NULL) != 0) {
678 ERROR("plugin: stop_read_threads: pthread_join failed.");
679 }
680 read_threads[i] = (pthread_t)0;
681 }
682 sfree(read_threads);
683 read_threads_num = 0;
684 } /* void stop_read_threads */
686 static void plugin_value_list_free(value_list_t *vl) /* {{{ */
687 {
688 if (vl == NULL)
689 return;
691 meta_data_destroy(vl->meta);
692 sfree(vl->values);
693 sfree(vl);
694 } /* }}} void plugin_value_list_free */
696 static value_list_t *
697 plugin_value_list_clone(value_list_t const *vl_orig) /* {{{ */
698 {
699 value_list_t *vl;
701 if (vl_orig == NULL)
702 return (NULL);
704 vl = malloc(sizeof(*vl));
705 if (vl == NULL)
706 return (NULL);
707 memcpy(vl, vl_orig, sizeof(*vl));
709 if (vl->host[0] == 0)
710 sstrncpy(vl->host, hostname_g, sizeof(vl->host));
712 vl->values = calloc(vl_orig->values_len, sizeof(*vl->values));
713 if (vl->values == NULL) {
714 plugin_value_list_free(vl);
715 return (NULL);
716 }
717 memcpy(vl->values, vl_orig->values,
718 vl_orig->values_len * sizeof(*vl->values));
720 vl->meta = meta_data_clone(vl->meta);
721 if ((vl_orig->meta != NULL) && (vl->meta == NULL)) {
722 plugin_value_list_free(vl);
723 return (NULL);
724 }
726 if (vl->time == 0)
727 vl->time = cdtime();
729 /* Fill in the interval from the thread context, if it is zero. */
730 if (vl->interval == 0) {
731 plugin_ctx_t ctx = plugin_get_ctx();
733 if (ctx.interval != 0)
734 vl->interval = ctx.interval;
735 else {
736 char name[6 * DATA_MAX_NAME_LEN];
737 FORMAT_VL(name, sizeof(name), vl);
738 ERROR("plugin_value_list_clone: Unable to determine "
739 "interval from context for "
740 "value list \"%s\". "
741 "This indicates a broken plugin. "
742 "Please report this problem to the "
743 "collectd mailing list or at "
744 "<http://collectd.org/bugs/>.",
745 name);
746 vl->interval = cf_get_default_interval();
747 }
748 }
750 return (vl);
751 } /* }}} value_list_t *plugin_value_list_clone */
753 static int plugin_write_enqueue(value_list_t const *vl) /* {{{ */
754 {
755 write_queue_t *q;
757 q = malloc(sizeof(*q));
758 if (q == NULL)
759 return (ENOMEM);
760 q->next = NULL;
762 q->vl = plugin_value_list_clone(vl);
763 if (q->vl == NULL) {
764 sfree(q);
765 return (ENOMEM);
766 }
768 /* Store context of caller (read plugin); otherwise, it would not be
769 * available to the write plugins when actually dispatching the
770 * value-list later on. */
771 q->ctx = plugin_get_ctx();
773 pthread_mutex_lock(&write_lock);
775 if (write_queue_tail == NULL) {
776 write_queue_head = q;
777 write_queue_tail = q;
778 write_queue_length = 1;
779 } else {
780 write_queue_tail->next = q;
781 write_queue_tail = q;
782 write_queue_length += 1;
783 }
785 pthread_cond_signal(&write_cond);
786 pthread_mutex_unlock(&write_lock);
788 return (0);
789 } /* }}} int plugin_write_enqueue */
791 static value_list_t *plugin_write_dequeue(void) /* {{{ */
792 {
793 write_queue_t *q;
794 value_list_t *vl;
796 pthread_mutex_lock(&write_lock);
798 while (write_loop && (write_queue_head == NULL))
799 pthread_cond_wait(&write_cond, &write_lock);
801 if (write_queue_head == NULL) {
802 pthread_mutex_unlock(&write_lock);
803 return (NULL);
804 }
806 q = write_queue_head;
807 write_queue_head = q->next;
808 write_queue_length -= 1;
809 if (write_queue_head == NULL) {
810 write_queue_tail = NULL;
811 assert(0 == write_queue_length);
812 }
814 pthread_mutex_unlock(&write_lock);
816 (void)plugin_set_ctx(q->ctx);
818 vl = q->vl;
819 sfree(q);
820 return (vl);
821 } /* }}} value_list_t *plugin_write_dequeue */
823 static void *plugin_write_thread(void __attribute__((unused)) * args) /* {{{ */
824 {
825 while (write_loop) {
826 value_list_t *vl = plugin_write_dequeue();
827 if (vl == NULL)
828 continue;
830 plugin_dispatch_values_internal(vl);
832 plugin_value_list_free(vl);
833 }
835 pthread_exit(NULL);
836 return ((void *)0);
837 } /* }}} void *plugin_write_thread */
839 static void start_write_threads(size_t num) /* {{{ */
840 {
841 if (write_threads != NULL)
842 return;
844 write_threads = (pthread_t *)calloc(num, sizeof(pthread_t));
845 if (write_threads == NULL) {
846 ERROR("plugin: start_write_threads: calloc failed.");
847 return;
848 }
850 write_threads_num = 0;
851 for (size_t i = 0; i < num; i++) {
852 int status = pthread_create(write_threads + write_threads_num,
853 /* attr = */ NULL, plugin_write_thread,
854 /* arg = */ NULL);
855 if (status != 0) {
856 char errbuf[1024];
857 ERROR("plugin: start_write_threads: pthread_create failed "
858 "with status %i (%s).",
859 status, sstrerror(status, errbuf, sizeof(errbuf)));
860 return;
861 }
863 char name[THREAD_NAME_MAX];
864 ssnprintf(name, sizeof(name), "writer#%zu", write_threads_num);
865 set_thread_name(write_threads[write_threads_num], name);
867 write_threads_num++;
868 } /* for (i) */
869 } /* }}} void start_write_threads */
871 static void stop_write_threads(void) /* {{{ */
872 {
873 write_queue_t *q;
874 size_t i;
876 if (write_threads == NULL)
877 return;
879 INFO("collectd: Stopping %zu write threads.", write_threads_num);
881 pthread_mutex_lock(&write_lock);
882 write_loop = 0;
883 DEBUG("plugin: stop_write_threads: Signalling `write_cond'");
884 pthread_cond_broadcast(&write_cond);
885 pthread_mutex_unlock(&write_lock);
887 for (i = 0; i < write_threads_num; i++) {
888 if (pthread_join(write_threads[i], NULL) != 0) {
889 ERROR("plugin: stop_write_threads: pthread_join failed.");
890 }
891 write_threads[i] = (pthread_t)0;
892 }
893 sfree(write_threads);
894 write_threads_num = 0;
896 pthread_mutex_lock(&write_lock);
897 i = 0;
898 for (q = write_queue_head; q != NULL;) {
899 write_queue_t *q1 = q;
900 plugin_value_list_free(q->vl);
901 q = q->next;
902 sfree(q1);
903 i++;
904 }
905 write_queue_head = NULL;
906 write_queue_tail = NULL;
907 write_queue_length = 0;
908 pthread_mutex_unlock(&write_lock);
910 if (i > 0) {
911 WARNING("plugin: %zu value list%s left after shutting down "
912 "the write threads.",
913 i, (i == 1) ? " was" : "s were");
914 }
915 } /* }}} void stop_write_threads */
917 /*
918 * Public functions
919 */
920 void plugin_set_dir(const char *dir) {
921 sfree(plugindir);
923 if (dir == NULL) {
924 plugindir = NULL;
925 return;
926 }
928 plugindir = strdup(dir);
929 if (plugindir == NULL)
930 ERROR("plugin_set_dir: strdup(\"%s\") failed", dir);
931 }
933 static _Bool plugin_is_loaded(char const *name) {
934 int status;
936 if (plugins_loaded == NULL)
937 plugins_loaded =
938 c_avl_create((int (*)(const void *, const void *))strcasecmp);
939 assert(plugins_loaded != NULL);
941 status = c_avl_get(plugins_loaded, name, /* ret_value = */ NULL);
942 return (status == 0);
943 }
945 static int plugin_mark_loaded(char const *name) {
946 char *name_copy;
947 int status;
949 name_copy = strdup(name);
950 if (name_copy == NULL)
951 return (ENOMEM);
953 status = c_avl_insert(plugins_loaded,
954 /* key = */ name_copy, /* value = */ NULL);
955 return (status);
956 }
958 static void plugin_free_loaded(void) {
959 void *key;
960 void *value;
962 if (plugins_loaded == NULL)
963 return;
965 while (c_avl_pick(plugins_loaded, &key, &value) == 0) {
966 sfree(key);
967 assert(value == NULL);
968 }
970 c_avl_destroy(plugins_loaded);
971 plugins_loaded = NULL;
972 }
974 #define BUFSIZE 512
975 int plugin_load(char const *plugin_name, uint32_t flags) {
976 DIR *dh;
977 const char *dir;
978 char filename[BUFSIZE] = "";
979 char typename[BUFSIZE];
980 int ret;
981 struct stat statbuf;
982 struct dirent *de;
983 int status;
985 if (plugin_name == NULL)
986 return (EINVAL);
988 /* Check if plugin is already loaded and don't do anything in this
989 * case. */
990 if (plugin_is_loaded(plugin_name))
991 return (0);
993 dir = plugin_get_dir();
994 ret = 1;
996 /*
997 * XXX: Magic at work:
998 *
999 * Some of the language bindings, for example the Python and Perl
1000 * plugins, need to be able to export symbols to the scripts they run.
1001 * For this to happen, the "Globals" flag needs to be set.
1002 * Unfortunately, this technical detail is hard to explain to the
1003 * average user and she shouldn't have to worry about this, ideally.
1004 * So in order to save everyone's sanity use a different default for a
1005 * handful of special plugins. --octo
1006 */
1007 if ((strcasecmp("perl", plugin_name) == 0) ||
1008 (strcasecmp("python", plugin_name) == 0))
1009 flags |= PLUGIN_FLAGS_GLOBAL;
1011 /* `cpu' should not match `cpufreq'. To solve this we add `.so' to the
1012 * type when matching the filename */
1013 status = ssnprintf(typename, sizeof(typename), "%s.so", plugin_name);
1014 if ((status < 0) || ((size_t)status >= sizeof(typename))) {
1015 WARNING("plugin_load: Filename too long: \"%s.so\"", plugin_name);
1016 return (-1);
1017 }
1019 if ((dh = opendir(dir)) == NULL) {
1020 char errbuf[1024];
1021 ERROR("plugin_load: opendir (%s) failed: %s", dir,
1022 sstrerror(errno, errbuf, sizeof(errbuf)));
1023 return (-1);
1024 }
1026 while ((de = readdir(dh)) != NULL) {
1027 if (strcasecmp(de->d_name, typename))
1028 continue;
1030 status = ssnprintf(filename, sizeof(filename), "%s/%s", dir, de->d_name);
1031 if ((status < 0) || ((size_t)status >= sizeof(filename))) {
1032 WARNING("plugin_load: Filename too long: \"%s/%s\"", dir, de->d_name);
1033 continue;
1034 }
1036 if (lstat(filename, &statbuf) == -1) {
1037 char errbuf[1024];
1038 WARNING("plugin_load: stat (\"%s\") failed: %s", filename,
1039 sstrerror(errno, errbuf, sizeof(errbuf)));
1040 continue;
1041 } else if (!S_ISREG(statbuf.st_mode)) {
1042 /* don't follow symlinks */
1043 WARNING("plugin_load: %s is not a regular file.", filename);
1044 continue;
1045 }
1047 status = plugin_load_file(filename, flags);
1048 if (status == 0) {
1049 /* success */
1050 plugin_mark_loaded(plugin_name);
1051 ret = 0;
1052 INFO("plugin_load: plugin \"%s\" successfully loaded.", plugin_name);
1053 break;
1054 } else {
1055 ERROR("plugin_load: Load plugin \"%s\" failed with "
1056 "status %i.",
1057 plugin_name, status);
1058 }
1059 }
1061 closedir(dh);
1063 if (filename[0] == 0)
1064 ERROR("plugin_load: Could not find plugin \"%s\" in %s", plugin_name, dir);
1066 return (ret);
1067 }
1069 /*
1070 * The `register_*' functions follow
1071 */
1072 int plugin_register_config(const char *name,
1073 int (*callback)(const char *key, const char *val),
1074 const char **keys, int keys_num) {
1075 cf_register(name, callback, keys, keys_num);
1076 return (0);
1077 } /* int plugin_register_config */
1079 int plugin_register_complex_config(const char *type,
1080 int (*callback)(oconfig_item_t *)) {
1081 return (cf_register_complex(type, callback));
1082 } /* int plugin_register_complex_config */
1084 int plugin_register_init(const char *name, int (*callback)(void)) {
1085 return (create_register_callback(&list_init, name, (void *)callback,
1086 /* user_data = */ NULL));
1087 } /* plugin_register_init */
1089 static int plugin_compare_read_func(const void *arg0, const void *arg1) {
1090 const read_func_t *rf0;
1091 const read_func_t *rf1;
1093 rf0 = arg0;
1094 rf1 = arg1;
1096 if (rf0->rf_next_read < rf1->rf_next_read)
1097 return (-1);
1098 else if (rf0->rf_next_read > rf1->rf_next_read)
1099 return (1);
1100 else
1101 return (0);
1102 } /* int plugin_compare_read_func */
1104 /* Add a read function to both, the heap and a linked list. The linked list if
1105 * used to look-up read functions, especially for the remove function. The heap
1106 * is used to determine which plugin to read next. */
1107 static int plugin_insert_read(read_func_t *rf) {
1108 int status;
1109 llentry_t *le;
1111 rf->rf_next_read = cdtime();
1112 rf->rf_effective_interval = rf->rf_interval;
1114 pthread_mutex_lock(&read_lock);
1116 if (read_list == NULL) {
1117 read_list = llist_create();
1118 if (read_list == NULL) {
1119 pthread_mutex_unlock(&read_lock);
1120 ERROR("plugin_insert_read: read_list failed.");
1121 return (-1);
1122 }
1123 }
1125 if (read_heap == NULL) {
1126 read_heap = c_heap_create(plugin_compare_read_func);
1127 if (read_heap == NULL) {
1128 pthread_mutex_unlock(&read_lock);
1129 ERROR("plugin_insert_read: c_heap_create failed.");
1130 return (-1);
1131 }
1132 }
1134 le = llist_search(read_list, rf->rf_name);
1135 if (le != NULL) {
1136 pthread_mutex_unlock(&read_lock);
1137 WARNING("The read function \"%s\" is already registered. "
1138 "Check for duplicate \"LoadPlugin\" lines "
1139 "in your configuration!",
1140 rf->rf_name);
1141 return (EINVAL);
1142 }
1144 le = llentry_create(rf->rf_name, rf);
1145 if (le == NULL) {
1146 pthread_mutex_unlock(&read_lock);
1147 ERROR("plugin_insert_read: llentry_create failed.");
1148 return (-1);
1149 }
1151 status = c_heap_insert(read_heap, rf);
1152 if (status != 0) {
1153 pthread_mutex_unlock(&read_lock);
1154 ERROR("plugin_insert_read: c_heap_insert failed.");
1155 llentry_destroy(le);
1156 return (-1);
1157 }
1159 /* This does not fail. */
1160 llist_append(read_list, le);
1162 /* Wake up all the read threads. */
1163 pthread_cond_broadcast(&read_cond);
1164 pthread_mutex_unlock(&read_lock);
1165 return (0);
1166 } /* int plugin_insert_read */
1168 int plugin_register_read(const char *name, int (*callback)(void)) {
1169 read_func_t *rf;
1170 int status;
1172 rf = calloc(1, sizeof(*rf));
1173 if (rf == NULL) {
1174 ERROR("plugin_register_read: calloc failed.");
1175 return (ENOMEM);
1176 }
1178 rf->rf_callback = (void *)callback;
1179 rf->rf_udata.data = NULL;
1180 rf->rf_udata.free_func = NULL;
1181 rf->rf_ctx = plugin_get_ctx();
1182 rf->rf_group[0] = '\0';
1183 rf->rf_name = strdup(name);
1184 rf->rf_type = RF_SIMPLE;
1185 rf->rf_interval = plugin_get_interval();
1187 status = plugin_insert_read(rf);
1188 if (status != 0) {
1189 sfree(rf->rf_name);
1190 sfree(rf);
1191 }
1193 return (status);
1194 } /* int plugin_register_read */
1196 int plugin_register_complex_read(const char *group, const char *name,
1197 plugin_read_cb callback, cdtime_t interval,
1198 user_data_t const *user_data) {
1199 read_func_t *rf;
1200 int status;
1202 rf = calloc(1, sizeof(*rf));
1203 if (rf == NULL) {
1204 ERROR("plugin_register_complex_read: calloc failed.");
1205 return (ENOMEM);
1206 }
1208 rf->rf_callback = (void *)callback;
1209 if (group != NULL)
1210 sstrncpy(rf->rf_group, group, sizeof(rf->rf_group));
1211 else
1212 rf->rf_group[0] = '\0';
1213 rf->rf_name = strdup(name);
1214 rf->rf_type = RF_COMPLEX;
1215 rf->rf_interval = (interval != 0) ? interval : plugin_get_interval();
1217 /* Set user data */
1218 if (user_data == NULL) {
1219 rf->rf_udata.data = NULL;
1220 rf->rf_udata.free_func = NULL;
1221 } else {
1222 rf->rf_udata = *user_data;
1223 }
1225 rf->rf_ctx = plugin_get_ctx();
1227 status = plugin_insert_read(rf);
1228 if (status != 0) {
1229 sfree(rf->rf_name);
1230 sfree(rf);
1231 }
1233 return (status);
1234 } /* int plugin_register_complex_read */
1236 int plugin_register_write(const char *name, plugin_write_cb callback,
1237 user_data_t const *ud) {
1238 return (create_register_callback(&list_write, name, (void *)callback, ud));
1239 } /* int plugin_register_write */
1241 static int plugin_flush_timeout_callback(user_data_t *ud) {
1242 flush_callback_t *cb = ud->data;
1244 return plugin_flush(cb->name, cb->timeout, /* identifier = */ NULL);
1245 } /* static int plugin_flush_callback */
1247 static void plugin_flush_timeout_callback_free(void *data) {
1248 flush_callback_t *cb = data;
1250 if (cb == NULL)
1251 return;
1253 sfree(cb->name);
1254 sfree(cb);
1255 } /* static void plugin_flush_callback_free */
1257 static char *plugin_flush_callback_name(const char *name) {
1258 const char *flush_prefix = "flush/";
1259 size_t prefix_size;
1260 char *flush_name;
1261 size_t name_size;
1263 prefix_size = strlen(flush_prefix);
1264 name_size = strlen(name);
1266 flush_name = malloc(name_size + prefix_size + 1);
1267 if (flush_name == NULL) {
1268 ERROR("plugin_flush_callback_name: malloc failed.");
1269 return (NULL);
1270 }
1272 sstrncpy(flush_name, flush_prefix, prefix_size + 1);
1273 sstrncpy(flush_name + prefix_size, name, name_size + 1);
1275 return flush_name;
1276 } /* static char *plugin_flush_callback_name */
1278 int plugin_register_flush(const char *name, plugin_flush_cb callback,
1279 user_data_t const *ud) {
1280 int status;
1281 plugin_ctx_t ctx = plugin_get_ctx();
1283 status = create_register_callback(&list_flush, name, (void *)callback, ud);
1284 if (status != 0)
1285 return status;
1287 if (ctx.flush_interval != 0) {
1288 char *flush_name;
1289 flush_callback_t *cb;
1291 flush_name = plugin_flush_callback_name(name);
1292 if (flush_name == NULL)
1293 return (-1);
1295 cb = malloc(sizeof(*cb));
1296 if (cb == NULL) {
1297 ERROR("plugin_register_flush: malloc failed.");
1298 sfree(flush_name);
1299 return (-1);
1300 }
1302 cb->name = strdup(name);
1303 if (cb->name == NULL) {
1304 ERROR("plugin_register_flush: strdup failed.");
1305 sfree(cb);
1306 sfree(flush_name);
1307 return (-1);
1308 }
1309 cb->timeout = ctx.flush_timeout;
1311 status = plugin_register_complex_read(
1312 /* group = */ "flush",
1313 /* name = */ flush_name,
1314 /* callback = */ plugin_flush_timeout_callback,
1315 /* interval = */ ctx.flush_interval,
1316 /* user data = */ &(user_data_t){
1317 .data = cb, .free_func = plugin_flush_timeout_callback_free,
1318 });
1320 sfree(flush_name);
1321 if (status != 0) {
1322 sfree(cb->name);
1323 sfree(cb);
1324 return status;
1325 }
1326 }
1328 return 0;
1329 } /* int plugin_register_flush */
1331 int plugin_register_missing(const char *name, plugin_missing_cb callback,
1332 user_data_t const *ud) {
1333 return (create_register_callback(&list_missing, name, (void *)callback, ud));
1334 } /* int plugin_register_missing */
1336 int plugin_register_shutdown(const char *name, int (*callback)(void)) {
1337 return (create_register_callback(&list_shutdown, name, (void *)callback,
1338 /* user_data = */ NULL));
1339 } /* int plugin_register_shutdown */
1341 static void plugin_free_data_sets(void) {
1342 void *key;
1343 void *value;
1345 if (data_sets == NULL)
1346 return;
1348 while (c_avl_pick(data_sets, &key, &value) == 0) {
1349 data_set_t *ds = value;
1350 /* key is a pointer to ds->type */
1352 sfree(ds->ds);
1353 sfree(ds);
1354 }
1356 c_avl_destroy(data_sets);
1357 data_sets = NULL;
1358 } /* void plugin_free_data_sets */
1360 int plugin_register_data_set(const data_set_t *ds) {
1361 data_set_t *ds_copy;
1363 if ((data_sets != NULL) && (c_avl_get(data_sets, ds->type, NULL) == 0)) {
1364 NOTICE("Replacing DS `%s' with another version.", ds->type);
1365 plugin_unregister_data_set(ds->type);
1366 } else if (data_sets == NULL) {
1367 data_sets = c_avl_create((int (*)(const void *, const void *))strcmp);
1368 if (data_sets == NULL)
1369 return (-1);
1370 }
1372 ds_copy = malloc(sizeof(*ds_copy));
1373 if (ds_copy == NULL)
1374 return (-1);
1375 memcpy(ds_copy, ds, sizeof(data_set_t));
1377 ds_copy->ds = malloc(sizeof(*ds_copy->ds) * ds->ds_num);
1378 if (ds_copy->ds == NULL) {
1379 sfree(ds_copy);
1380 return (-1);
1381 }
1383 for (size_t i = 0; i < ds->ds_num; i++)
1384 memcpy(ds_copy->ds + i, ds->ds + i, sizeof(data_source_t));
1386 return (c_avl_insert(data_sets, (void *)ds_copy->type, (void *)ds_copy));
1387 } /* int plugin_register_data_set */
1389 int plugin_register_log(const char *name, plugin_log_cb callback,
1390 user_data_t const *ud) {
1391 return (create_register_callback(&list_log, name, (void *)callback, ud));
1392 } /* int plugin_register_log */
1394 int plugin_register_notification(const char *name,
1395 plugin_notification_cb callback,
1396 user_data_t const *ud) {
1397 return (
1398 create_register_callback(&list_notification, name, (void *)callback, ud));
1399 } /* int plugin_register_log */
1401 int plugin_unregister_config(const char *name) {
1402 cf_unregister(name);
1403 return (0);
1404 } /* int plugin_unregister_config */
1406 int plugin_unregister_complex_config(const char *name) {
1407 cf_unregister_complex(name);
1408 return (0);
1409 } /* int plugin_unregister_complex_config */
1411 int plugin_unregister_init(const char *name) {
1412 return (plugin_unregister(list_init, name));
1413 }
1415 int plugin_unregister_read(const char *name) /* {{{ */
1416 {
1417 llentry_t *le;
1418 read_func_t *rf;
1420 if (name == NULL)
1421 return (-ENOENT);
1423 pthread_mutex_lock(&read_lock);
1425 if (read_list == NULL) {
1426 pthread_mutex_unlock(&read_lock);
1427 return (-ENOENT);
1428 }
1430 le = llist_search(read_list, name);
1431 if (le == NULL) {
1432 pthread_mutex_unlock(&read_lock);
1433 WARNING("plugin_unregister_read: No such read function: %s", name);
1434 return (-ENOENT);
1435 }
1437 llist_remove(read_list, le);
1439 rf = le->value;
1440 assert(rf != NULL);
1441 rf->rf_type = RF_REMOVE;
1443 pthread_mutex_unlock(&read_lock);
1445 llentry_destroy(le);
1447 DEBUG("plugin_unregister_read: Marked `%s' for removal.", name);
1449 return (0);
1450 } /* }}} int plugin_unregister_read */
1452 void plugin_log_available_writers(void) {
1453 log_list_callbacks(&list_write, "Available write targets:");
1454 }
1456 static int compare_read_func_group(llentry_t *e, void *ud) /* {{{ */
1457 {
1458 read_func_t *rf = e->value;
1459 char *group = ud;
1461 return strcmp(rf->rf_group, (const char *)group);
1462 } /* }}} int compare_read_func_group */
1464 int plugin_unregister_read_group(const char *group) /* {{{ */
1465 {
1466 llentry_t *le;
1467 read_func_t *rf;
1469 int found = 0;
1471 if (group == NULL)
1472 return (-ENOENT);
1474 pthread_mutex_lock(&read_lock);
1476 if (read_list == NULL) {
1477 pthread_mutex_unlock(&read_lock);
1478 return (-ENOENT);
1479 }
1481 while (42) {
1482 le = llist_search_custom(read_list, compare_read_func_group, (void *)group);
1484 if (le == NULL)
1485 break;
1487 ++found;
1489 llist_remove(read_list, le);
1491 rf = le->value;
1492 assert(rf != NULL);
1493 rf->rf_type = RF_REMOVE;
1495 llentry_destroy(le);
1497 DEBUG("plugin_unregister_read_group: "
1498 "Marked `%s' (group `%s') for removal.",
1499 rf->rf_name, group);
1500 }
1502 pthread_mutex_unlock(&read_lock);
1504 if (found == 0) {
1505 WARNING("plugin_unregister_read_group: No such "
1506 "group of read function: %s",
1507 group);
1508 return (-ENOENT);
1509 }
1511 return (0);
1512 } /* }}} int plugin_unregister_read_group */
1514 int plugin_unregister_write(const char *name) {
1515 return (plugin_unregister(list_write, name));
1516 }
1518 int plugin_unregister_flush(const char *name) {
1519 plugin_ctx_t ctx = plugin_get_ctx();
1521 if (ctx.flush_interval != 0) {
1522 char *flush_name;
1524 flush_name = plugin_flush_callback_name(name);
1525 if (flush_name != NULL) {
1526 plugin_unregister_read(flush_name);
1527 sfree(flush_name);
1528 }
1529 }
1531 return plugin_unregister(list_flush, name);
1532 }
1534 int plugin_unregister_missing(const char *name) {
1535 return (plugin_unregister(list_missing, name));
1536 }
1538 int plugin_unregister_shutdown(const char *name) {
1539 return (plugin_unregister(list_shutdown, name));
1540 }
1542 int plugin_unregister_data_set(const char *name) {
1543 data_set_t *ds;
1545 if (data_sets == NULL)
1546 return (-1);
1548 if (c_avl_remove(data_sets, name, NULL, (void *)&ds) != 0)
1549 return (-1);
1551 sfree(ds->ds);
1552 sfree(ds);
1554 return (0);
1555 } /* int plugin_unregister_data_set */
1557 int plugin_unregister_log(const char *name) {
1558 return (plugin_unregister(list_log, name));
1559 }
1561 int plugin_unregister_notification(const char *name) {
1562 return (plugin_unregister(list_notification, name));
1563 }
1565 int plugin_init_all(void) {
1566 char const *chain_name;
1567 llentry_t *le;
1568 int status;
1569 int ret = 0;
1571 /* Init the value cache */
1572 uc_init();
1574 if (IS_TRUE(global_option_get("CollectInternalStats"))) {
1575 record_statistics = 1;
1576 plugin_register_read("collectd", plugin_update_internal_statistics);
1577 }
1579 chain_name = global_option_get("PreCacheChain");
1580 pre_cache_chain = fc_chain_get_by_name(chain_name);
1582 chain_name = global_option_get("PostCacheChain");
1583 post_cache_chain = fc_chain_get_by_name(chain_name);
1585 write_limit_high = global_option_get_long("WriteQueueLimitHigh",
1586 /* default = */ 0);
1587 if (write_limit_high < 0) {
1588 ERROR("WriteQueueLimitHigh must be positive or zero.");
1589 write_limit_high = 0;
1590 }
1592 write_limit_low =
1593 global_option_get_long("WriteQueueLimitLow",
1594 /* default = */ write_limit_high / 2);
1595 if (write_limit_low < 0) {
1596 ERROR("WriteQueueLimitLow must be positive or zero.");
1597 write_limit_low = write_limit_high / 2;
1598 } else if (write_limit_low > write_limit_high) {
1599 ERROR("WriteQueueLimitLow must not be larger than "
1600 "WriteQueueLimitHigh.");
1601 write_limit_low = write_limit_high;
1602 }
1604 write_threads_num = global_option_get_long("WriteThreads",
1605 /* default = */ 5);
1606 if (write_threads_num < 1) {
1607 ERROR("WriteThreads must be positive.");
1608 write_threads_num = 5;
1609 }
1611 if ((list_init == NULL) && (read_heap == NULL))
1612 return ret;
1614 /* Calling all init callbacks before checking if read callbacks
1615 * are available allows the init callbacks to register the read
1616 * callback. */
1617 le = llist_head(list_init);
1618 while (le != NULL) {
1619 callback_func_t *cf;
1620 plugin_init_cb callback;
1621 plugin_ctx_t old_ctx;
1623 cf = le->value;
1624 old_ctx = plugin_set_ctx(cf->cf_ctx);
1625 callback = cf->cf_callback;
1626 status = (*callback)();
1627 plugin_set_ctx(old_ctx);
1629 if (status != 0) {
1630 ERROR("Initialization of plugin `%s' "
1631 "failed with status %i. "
1632 "Plugin will be unloaded.",
1633 le->key, status);
1634 /* Plugins that register read callbacks from the init
1635 * callback should take care of appropriate error
1636 * handling themselves. */
1637 /* FIXME: Unload _all_ functions */
1638 plugin_unregister_read(le->key);
1639 ret = -1;
1640 }
1642 le = le->next;
1643 }
1645 start_write_threads((size_t)write_threads_num);
1647 max_read_interval =
1648 global_option_get_time("MaxReadInterval", DEFAULT_MAX_READ_INTERVAL);
1650 /* Start read-threads */
1651 if (read_heap != NULL) {
1652 const char *rt;
1653 int num;
1655 rt = global_option_get("ReadThreads");
1656 num = atoi(rt);
1657 if (num != -1)
1658 start_read_threads((num > 0) ? ((size_t)num) : 5);
1659 }
1660 return ret;
1661 } /* void plugin_init_all */
1663 /* TODO: Rename this function. */
1664 void plugin_read_all(void) {
1665 uc_check_timeout();
1667 return;
1668 } /* void plugin_read_all */
1670 /* Read function called when the `-T' command line argument is given. */
1671 int plugin_read_all_once(void) {
1672 int status;
1673 int return_status = 0;
1675 if (read_heap == NULL) {
1676 NOTICE("No read-functions are registered.");
1677 return (0);
1678 }
1680 while (42) {
1681 read_func_t *rf;
1682 plugin_ctx_t old_ctx;
1684 rf = c_heap_get_root(read_heap);
1685 if (rf == NULL)
1686 break;
1688 old_ctx = plugin_set_ctx(rf->rf_ctx);
1690 if (rf->rf_type == RF_SIMPLE) {
1691 int (*callback)(void);
1693 callback = rf->rf_callback;
1694 status = (*callback)();
1695 } else {
1696 plugin_read_cb callback;
1698 callback = rf->rf_callback;
1699 status = (*callback)(&rf->rf_udata);
1700 }
1702 plugin_set_ctx(old_ctx);
1704 if (status != 0) {
1705 NOTICE("read-function of plugin `%s' failed.", rf->rf_name);
1706 return_status = -1;
1707 }
1709 sfree(rf->rf_name);
1710 destroy_callback((void *)rf);
1711 }
1713 return (return_status);
1714 } /* int plugin_read_all_once */
1716 int plugin_write(const char *plugin, /* {{{ */
1717 const data_set_t *ds, const value_list_t *vl) {
1718 llentry_t *le;
1719 int status;
1721 if (vl == NULL)
1722 return (EINVAL);
1724 if (list_write == NULL)
1725 return (ENOENT);
1727 if (ds == NULL) {
1728 ds = plugin_get_ds(vl->type);
1729 if (ds == NULL) {
1730 ERROR("plugin_write: Unable to lookup type `%s'.", vl->type);
1731 return (ENOENT);
1732 }
1733 }
1735 if (plugin == NULL) {
1736 int success = 0;
1737 int failure = 0;
1739 le = llist_head(list_write);
1740 while (le != NULL) {
1741 callback_func_t *cf = le->value;
1742 plugin_write_cb callback;
1744 /* do not switch plugin context; rather keep the context (interval)
1745 * information of the calling read plugin */
1747 DEBUG("plugin: plugin_write: Writing values via %s.", le->key);
1748 callback = cf->cf_callback;
1749 status = (*callback)(ds, vl, &cf->cf_udata);
1750 if (status != 0)
1751 failure++;
1752 else
1753 success++;
1755 le = le->next;
1756 }
1758 if ((success == 0) && (failure != 0))
1759 status = -1;
1760 else
1761 status = 0;
1762 } else /* plugin != NULL */
1763 {
1764 callback_func_t *cf;
1765 plugin_write_cb callback;
1767 le = llist_head(list_write);
1768 while (le != NULL) {
1769 if (strcasecmp(plugin, le->key) == 0)
1770 break;
1772 le = le->next;
1773 }
1775 if (le == NULL)
1776 return (ENOENT);
1778 cf = le->value;
1780 /* do not switch plugin context; rather keep the context (interval)
1781 * information of the calling read plugin */
1783 DEBUG("plugin: plugin_write: Writing values via %s.", le->key);
1784 callback = cf->cf_callback;
1785 status = (*callback)(ds, vl, &cf->cf_udata);
1786 }
1788 return (status);
1789 } /* }}} int plugin_write */
1791 int plugin_flush(const char *plugin, cdtime_t timeout, const char *identifier) {
1792 llentry_t *le;
1794 if (list_flush == NULL)
1795 return (0);
1797 le = llist_head(list_flush);
1798 while (le != NULL) {
1799 callback_func_t *cf;
1800 plugin_flush_cb callback;
1801 plugin_ctx_t old_ctx;
1803 if ((plugin != NULL) && (strcmp(plugin, le->key) != 0)) {
1804 le = le->next;
1805 continue;
1806 }
1808 cf = le->value;
1809 old_ctx = plugin_set_ctx(cf->cf_ctx);
1810 callback = cf->cf_callback;
1812 (*callback)(timeout, identifier, &cf->cf_udata);
1814 plugin_set_ctx(old_ctx);
1816 le = le->next;
1817 }
1818 return (0);
1819 } /* int plugin_flush */
1821 int plugin_shutdown_all(void) {
1822 llentry_t *le;
1823 int ret = 0; // Assume success.
1825 destroy_all_callbacks(&list_init);
1827 stop_read_threads();
1829 pthread_mutex_lock(&read_lock);
1830 llist_destroy(read_list);
1831 read_list = NULL;
1832 pthread_mutex_unlock(&read_lock);
1834 destroy_read_heap();
1836 /* blocks until all write threads have shut down. */
1837 stop_write_threads();
1839 /* ask all plugins to write out the state they kept. */
1840 plugin_flush(/* plugin = */ NULL,
1841 /* timeout = */ 0,
1842 /* identifier = */ NULL);
1844 le = NULL;
1845 if (list_shutdown != NULL)
1846 le = llist_head(list_shutdown);
1848 while (le != NULL) {
1849 callback_func_t *cf;
1850 plugin_shutdown_cb callback;
1851 plugin_ctx_t old_ctx;
1853 cf = le->value;
1854 old_ctx = plugin_set_ctx(cf->cf_ctx);
1855 callback = cf->cf_callback;
1857 /* Advance the pointer before calling the callback allows
1858 * shutdown functions to unregister themselves. If done the
1859 * other way around the memory `le' points to will be freed
1860 * after callback returns. */
1861 le = le->next;
1863 if ((*callback)() != 0)
1864 ret = -1;
1866 plugin_set_ctx(old_ctx);
1867 }
1869 /* Write plugins which use the `user_data' pointer usually need the
1870 * same data available to the flush callback. If this is the case, set
1871 * the free_function to NULL when registering the flush callback and to
1872 * the real free function when registering the write callback. This way
1873 * the data isn't freed twice. */
1874 destroy_all_callbacks(&list_flush);
1875 destroy_all_callbacks(&list_missing);
1876 destroy_all_callbacks(&list_write);
1878 destroy_all_callbacks(&list_notification);
1879 destroy_all_callbacks(&list_shutdown);
1880 destroy_all_callbacks(&list_log);
1882 plugin_free_loaded();
1883 plugin_free_data_sets();
1884 return (ret);
1885 } /* void plugin_shutdown_all */
1887 int plugin_dispatch_missing(const value_list_t *vl) /* {{{ */
1888 {
1889 llentry_t *le;
1891 if (list_missing == NULL)
1892 return (0);
1894 le = llist_head(list_missing);
1895 while (le != NULL) {
1896 callback_func_t *cf;
1897 plugin_missing_cb callback;
1898 plugin_ctx_t old_ctx;
1899 int status;
1901 cf = le->value;
1902 old_ctx = plugin_set_ctx(cf->cf_ctx);
1903 callback = cf->cf_callback;
1905 status = (*callback)(vl, &cf->cf_udata);
1906 plugin_set_ctx(old_ctx);
1907 if (status != 0) {
1908 if (status < 0) {
1909 ERROR("plugin_dispatch_missing: Callback function \"%s\" "
1910 "failed with status %i.",
1911 le->key, status);
1912 return (status);
1913 } else {
1914 return (0);
1915 }
1916 }
1918 le = le->next;
1919 }
1920 return (0);
1921 } /* int }}} plugin_dispatch_missing */
1923 static int plugin_dispatch_values_internal(value_list_t *vl) {
1924 int status;
1925 static c_complain_t no_write_complaint = C_COMPLAIN_INIT_STATIC;
1927 data_set_t *ds;
1929 _Bool free_meta_data = 0;
1931 assert(vl != NULL);
1933 /* These fields are initialized by plugin_value_list_clone() if needed: */
1934 assert(vl->host[0] != 0);
1935 assert(vl->time != 0); /* The time is determined at _enqueue_ time. */
1936 assert(vl->interval != 0);
1938 if (vl->type[0] == 0 || vl->values == NULL || vl->values_len < 1) {
1939 ERROR("plugin_dispatch_values: Invalid value list "
1940 "from plugin %s.",
1941 vl->plugin);
1942 return (-1);
1943 }
1945 /* Free meta data only if the calling function didn't specify any. In
1946 * this case matches and targets may add some and the calling function
1947 * may not expect (and therefore free) that data. */
1948 if (vl->meta == NULL)
1949 free_meta_data = 1;
1951 if (list_write == NULL)
1952 c_complain_once(LOG_WARNING, &no_write_complaint,
1953 "plugin_dispatch_values: No write callback has been "
1954 "registered. Please load at least one output plugin, "
1955 "if you want the collected data to be stored.");
1957 if (data_sets == NULL) {
1958 ERROR("plugin_dispatch_values: No data sets registered. "
1959 "Could the types database be read? Check "
1960 "your `TypesDB' setting!");
1961 return (-1);
1962 }
1964 if (c_avl_get(data_sets, vl->type, (void *)&ds) != 0) {
1965 char ident[6 * DATA_MAX_NAME_LEN];
1967 FORMAT_VL(ident, sizeof(ident), vl);
1968 INFO("plugin_dispatch_values: Dataset not found: %s "
1969 "(from \"%s\"), check your types.db!",
1970 vl->type, ident);
1971 return (-1);
1972 }
1974 DEBUG("plugin_dispatch_values: time = %.3f; interval = %.3f; "
1975 "host = %s; "
1976 "plugin = %s; plugin_instance = %s; "
1977 "type = %s; type_instance = %s;",
1978 CDTIME_T_TO_DOUBLE(vl->time), CDTIME_T_TO_DOUBLE(vl->interval),
1979 vl->host, vl->plugin, vl->plugin_instance, vl->type, vl->type_instance);
1981 #if COLLECT_DEBUG
1982 assert(0 == strcmp(ds->type, vl->type));
1983 #else
1984 if (0 != strcmp(ds->type, vl->type))
1985 WARNING("plugin_dispatch_values: (ds->type = %s) != (vl->type = %s)",
1986 ds->type, vl->type);
1987 #endif
1989 #if COLLECT_DEBUG
1990 assert(ds->ds_num == vl->values_len);
1991 #else
1992 if (ds->ds_num != vl->values_len) {
1993 ERROR("plugin_dispatch_values: ds->type = %s: "
1994 "(ds->ds_num = %zu) != "
1995 "(vl->values_len = %zu)",
1996 ds->type, ds->ds_num, vl->values_len);
1997 return (-1);
1998 }
1999 #endif
2001 escape_slashes(vl->host, sizeof(vl->host));
2002 escape_slashes(vl->plugin, sizeof(vl->plugin));
2003 escape_slashes(vl->plugin_instance, sizeof(vl->plugin_instance));
2004 escape_slashes(vl->type, sizeof(vl->type));
2005 escape_slashes(vl->type_instance, sizeof(vl->type_instance));
2007 if (pre_cache_chain != NULL) {
2008 status = fc_process_chain(ds, vl, pre_cache_chain);
2009 if (status < 0) {
2010 WARNING("plugin_dispatch_values: Running the "
2011 "pre-cache chain failed with "
2012 "status %i (%#x).",
2013 status, status);
2014 } else if (status == FC_TARGET_STOP)
2015 return (0);
2016 }
2018 /* Update the value cache */
2019 uc_update(ds, vl);
2021 if (post_cache_chain != NULL) {
2022 status = fc_process_chain(ds, vl, post_cache_chain);
2023 if (status < 0) {
2024 WARNING("plugin_dispatch_values: Running the "
2025 "post-cache chain failed with "
2026 "status %i (%#x).",
2027 status, status);
2028 }
2029 } else
2030 fc_default_action(ds, vl);
2032 if ((free_meta_data != 0) && (vl->meta != NULL)) {
2033 meta_data_destroy(vl->meta);
2034 vl->meta = NULL;
2035 }
2037 return (0);
2038 } /* int plugin_dispatch_values_internal */
2040 static double get_drop_probability(void) /* {{{ */
2041 {
2042 long pos;
2043 long size;
2044 long wql;
2046 pthread_mutex_lock(&write_lock);
2047 wql = write_queue_length;
2048 pthread_mutex_unlock(&write_lock);
2050 if (wql < write_limit_low)
2051 return (0.0);
2052 if (wql >= write_limit_high)
2053 return (1.0);
2055 pos = 1 + wql - write_limit_low;
2056 size = 1 + write_limit_high - write_limit_low;
2058 return (((double)pos) / ((double)size));
2059 } /* }}} double get_drop_probability */
2061 static _Bool check_drop_value(void) /* {{{ */
2062 {
2063 static cdtime_t last_message_time = 0;
2064 static pthread_mutex_t last_message_lock = PTHREAD_MUTEX_INITIALIZER;
2066 double p;
2067 double q;
2068 int status;
2070 if (write_limit_high == 0)
2071 return (0);
2073 p = get_drop_probability();
2074 if (p == 0.0)
2075 return (0);
2077 status = pthread_mutex_trylock(&last_message_lock);
2078 if (status == 0) {
2079 cdtime_t now;
2081 now = cdtime();
2082 if ((now - last_message_time) > TIME_T_TO_CDTIME_T(1)) {
2083 last_message_time = now;
2084 ERROR("plugin_dispatch_values: Low water mark "
2085 "reached. Dropping %.0f%% of metrics.",
2086 100.0 * p);
2087 }
2088 pthread_mutex_unlock(&last_message_lock);
2089 }
2091 if (p == 1.0)
2092 return (1);
2094 q = cdrand_d();
2095 if (q > p)
2096 return (1);
2097 else
2098 return (0);
2099 } /* }}} _Bool check_drop_value */
2101 int plugin_dispatch_values(value_list_t const *vl) {
2102 int status;
2103 static pthread_mutex_t statistics_lock = PTHREAD_MUTEX_INITIALIZER;
2105 if (check_drop_value()) {
2106 if (record_statistics) {
2107 pthread_mutex_lock(&statistics_lock);
2108 stats_values_dropped++;
2109 pthread_mutex_unlock(&statistics_lock);
2110 }
2111 return (0);
2112 }
2114 status = plugin_write_enqueue(vl);
2115 if (status != 0) {
2116 char errbuf[1024];
2117 ERROR("plugin_dispatch_values: plugin_write_enqueue failed "
2118 "with status %i (%s).",
2119 status, sstrerror(status, errbuf, sizeof(errbuf)));
2120 return (status);
2121 }
2123 return (0);
2124 }
2126 __attribute__((sentinel)) int
2127 plugin_dispatch_multivalue(value_list_t const *template, /* {{{ */
2128 _Bool store_percentage, int store_type, ...) {
2129 value_list_t *vl;
2130 int failed = 0;
2131 gauge_t sum = 0.0;
2132 va_list ap;
2134 assert(template->values_len == 1);
2136 /* Calculate sum for Gauge to calculate percent if needed */
2137 if (DS_TYPE_GAUGE == store_type) {
2138 va_start(ap, store_type);
2139 while (42) {
2140 char const *name;
2141 gauge_t value;
2143 name = va_arg(ap, char const *);
2144 if (name == NULL)
2145 break;
2147 value = va_arg(ap, gauge_t);
2148 if (!isnan(value))
2149 sum += value;
2150 }
2151 va_end(ap);
2152 }
2154 vl = plugin_value_list_clone(template);
2155 /* plugin_value_list_clone makes sure vl->time is set to non-zero. */
2156 if (store_percentage)
2157 sstrncpy(vl->type, "percent", sizeof(vl->type));
2159 va_start(ap, store_type);
2160 while (42) {
2161 char const *name;
2162 int status;
2164 /* Set the type instance. */
2165 name = va_arg(ap, char const *);
2166 if (name == NULL)
2167 break;
2168 sstrncpy(vl->type_instance, name, sizeof(vl->type_instance));
2170 /* Set the value. */
2171 switch (store_type) {
2172 case DS_TYPE_GAUGE:
2173 vl->values[0].gauge = va_arg(ap, gauge_t);
2174 if (store_percentage)
2175 vl->values[0].gauge *= sum ? (100.0 / sum) : NAN;
2176 break;
2177 case DS_TYPE_ABSOLUTE:
2178 vl->values[0].absolute = va_arg(ap, absolute_t);
2179 break;
2180 case DS_TYPE_COUNTER:
2181 vl->values[0].counter = va_arg(ap, counter_t);
2182 break;
2183 case DS_TYPE_DERIVE:
2184 vl->values[0].derive = va_arg(ap, derive_t);
2185 break;
2186 default:
2187 ERROR("plugin_dispatch_multivalue: given store_type is incorrect.");
2188 failed++;
2189 }
2191 status = plugin_write_enqueue(vl);
2192 if (status != 0)
2193 failed++;
2194 }
2195 va_end(ap);
2197 plugin_value_list_free(vl);
2198 return (failed);
2199 } /* }}} int plugin_dispatch_multivalue */
2201 int plugin_dispatch_notification(const notification_t *notif) {
2202 llentry_t *le;
2203 /* Possible TODO: Add flap detection here */
2205 DEBUG("plugin_dispatch_notification: severity = %i; message = %s; "
2206 "time = %.3f; host = %s;",
2207 notif->severity, notif->message, CDTIME_T_TO_DOUBLE(notif->time),
2208 notif->host);
2210 /* Nobody cares for notifications */
2211 if (list_notification == NULL)
2212 return (-1);
2214 le = llist_head(list_notification);
2215 while (le != NULL) {
2216 callback_func_t *cf;
2217 plugin_notification_cb callback;
2218 int status;
2220 /* do not switch plugin context; rather keep the context
2221 * (interval) information of the calling plugin */
2223 cf = le->value;
2224 callback = cf->cf_callback;
2225 status = (*callback)(notif, &cf->cf_udata);
2226 if (status != 0) {
2227 WARNING("plugin_dispatch_notification: Notification "
2228 "callback %s returned %i.",
2229 le->key, status);
2230 }
2232 le = le->next;
2233 }
2235 return (0);
2236 } /* int plugin_dispatch_notification */
2238 void plugin_log(int level, const char *format, ...) {
2239 char msg[1024];
2240 va_list ap;
2241 llentry_t *le;
2243 #if !COLLECT_DEBUG
2244 if (level >= LOG_DEBUG)
2245 return;
2246 #endif
2248 va_start(ap, format);
2249 vsnprintf(msg, sizeof(msg), format, ap);
2250 msg[sizeof(msg) - 1] = '\0';
2251 va_end(ap);
2253 if (list_log == NULL) {
2254 fprintf(stderr, "%s\n", msg);
2255 return;
2256 }
2258 le = llist_head(list_log);
2259 while (le != NULL) {
2260 callback_func_t *cf;
2261 plugin_log_cb callback;
2263 cf = le->value;
2264 callback = cf->cf_callback;
2266 /* do not switch plugin context; rather keep the context
2267 * (interval) information of the calling plugin */
2269 (*callback)(level, msg, &cf->cf_udata);
2271 le = le->next;
2272 }
2273 } /* void plugin_log */
2275 int parse_log_severity(const char *severity) {
2276 int log_level = -1;
2278 if ((0 == strcasecmp(severity, "emerg")) ||
2279 (0 == strcasecmp(severity, "alert")) ||
2280 (0 == strcasecmp(severity, "crit")) || (0 == strcasecmp(severity, "err")))
2281 log_level = LOG_ERR;
2282 else if (0 == strcasecmp(severity, "warning"))
2283 log_level = LOG_WARNING;
2284 else if (0 == strcasecmp(severity, "notice"))
2285 log_level = LOG_NOTICE;
2286 else if (0 == strcasecmp(severity, "info"))
2287 log_level = LOG_INFO;
2288 #if COLLECT_DEBUG
2289 else if (0 == strcasecmp(severity, "debug"))
2290 log_level = LOG_DEBUG;
2291 #endif /* COLLECT_DEBUG */
2293 return (log_level);
2294 } /* int parse_log_severity */
2296 int parse_notif_severity(const char *severity) {
2297 int notif_severity = -1;
2299 if (strcasecmp(severity, "FAILURE") == 0)
2300 notif_severity = NOTIF_FAILURE;
2301 else if (strcmp(severity, "OKAY") == 0)
2302 notif_severity = NOTIF_OKAY;
2303 else if ((strcmp(severity, "WARNING") == 0) ||
2304 (strcmp(severity, "WARN") == 0))
2305 notif_severity = NOTIF_WARNING;
2307 return (notif_severity);
2308 } /* int parse_notif_severity */
2310 const data_set_t *plugin_get_ds(const char *name) {
2311 data_set_t *ds;
2313 if (data_sets == NULL) {
2314 ERROR("plugin_get_ds: No data sets are defined yet.");
2315 return (NULL);
2316 }
2318 if (c_avl_get(data_sets, name, (void *)&ds) != 0) {
2319 DEBUG("No such dataset registered: %s", name);
2320 return (NULL);
2321 }
2323 return (ds);
2324 } /* data_set_t *plugin_get_ds */
2326 static int plugin_notification_meta_add(notification_t *n, const char *name,
2327 enum notification_meta_type_e type,
2328 const void *value) {
2329 notification_meta_t *meta;
2330 notification_meta_t *tail;
2332 if ((n == NULL) || (name == NULL) || (value == NULL)) {
2333 ERROR("plugin_notification_meta_add: A pointer is NULL!");
2334 return (-1);
2335 }
2337 meta = calloc(1, sizeof(*meta));
2338 if (meta == NULL) {
2339 ERROR("plugin_notification_meta_add: calloc failed.");
2340 return (-1);
2341 }
2343 sstrncpy(meta->name, name, sizeof(meta->name));
2344 meta->type = type;
2346 switch (type) {
2347 case NM_TYPE_STRING: {
2348 meta->nm_value.nm_string = strdup((const char *)value);
2349 if (meta->nm_value.nm_string == NULL) {
2350 ERROR("plugin_notification_meta_add: strdup failed.");
2351 sfree(meta);
2352 return (-1);
2353 }
2354 break;
2355 }
2356 case NM_TYPE_SIGNED_INT: {
2357 meta->nm_value.nm_signed_int = *((int64_t *)value);
2358 break;
2359 }
2360 case NM_TYPE_UNSIGNED_INT: {
2361 meta->nm_value.nm_unsigned_int = *((uint64_t *)value);
2362 break;
2363 }
2364 case NM_TYPE_DOUBLE: {
2365 meta->nm_value.nm_double = *((double *)value);
2366 break;
2367 }
2368 case NM_TYPE_BOOLEAN: {
2369 meta->nm_value.nm_boolean = *((_Bool *)value);
2370 break;
2371 }
2372 default: {
2373 ERROR("plugin_notification_meta_add: Unknown type: %i", type);
2374 sfree(meta);
2375 return (-1);
2376 }
2377 } /* switch (type) */
2379 meta->next = NULL;
2380 tail = n->meta;
2381 while ((tail != NULL) && (tail->next != NULL))
2382 tail = tail->next;
2384 if (tail == NULL)
2385 n->meta = meta;
2386 else
2387 tail->next = meta;
2389 return (0);
2390 } /* int plugin_notification_meta_add */
2392 int plugin_notification_meta_add_string(notification_t *n, const char *name,
2393 const char *value) {
2394 return (plugin_notification_meta_add(n, name, NM_TYPE_STRING, value));
2395 }
2397 int plugin_notification_meta_add_signed_int(notification_t *n, const char *name,
2398 int64_t value) {
2399 return (plugin_notification_meta_add(n, name, NM_TYPE_SIGNED_INT, &value));
2400 }
2402 int plugin_notification_meta_add_unsigned_int(notification_t *n,
2403 const char *name,
2404 uint64_t value) {
2405 return (plugin_notification_meta_add(n, name, NM_TYPE_UNSIGNED_INT, &value));
2406 }
2408 int plugin_notification_meta_add_double(notification_t *n, const char *name,
2409 double value) {
2410 return (plugin_notification_meta_add(n, name, NM_TYPE_DOUBLE, &value));
2411 }
2413 int plugin_notification_meta_add_boolean(notification_t *n, const char *name,
2414 _Bool value) {
2415 return (plugin_notification_meta_add(n, name, NM_TYPE_BOOLEAN, &value));
2416 }
2418 int plugin_notification_meta_copy(notification_t *dst,
2419 const notification_t *src) {
2420 assert(dst != NULL);
2421 assert(src != NULL);
2422 assert(dst != src);
2423 assert((src->meta == NULL) || (src->meta != dst->meta));
2425 for (notification_meta_t *meta = src->meta; meta != NULL; meta = meta->next) {
2426 if (meta->type == NM_TYPE_STRING)
2427 plugin_notification_meta_add_string(dst, meta->name,
2428 meta->nm_value.nm_string);
2429 else if (meta->type == NM_TYPE_SIGNED_INT)
2430 plugin_notification_meta_add_signed_int(dst, meta->name,
2431 meta->nm_value.nm_signed_int);
2432 else if (meta->type == NM_TYPE_UNSIGNED_INT)
2433 plugin_notification_meta_add_unsigned_int(dst, meta->name,
2434 meta->nm_value.nm_unsigned_int);
2435 else if (meta->type == NM_TYPE_DOUBLE)
2436 plugin_notification_meta_add_double(dst, meta->name,
2437 meta->nm_value.nm_double);
2438 else if (meta->type == NM_TYPE_BOOLEAN)
2439 plugin_notification_meta_add_boolean(dst, meta->name,
2440 meta->nm_value.nm_boolean);
2441 }
2443 return (0);
2444 } /* int plugin_notification_meta_copy */
2446 int plugin_notification_meta_free(notification_meta_t *n) {
2447 notification_meta_t *this;
2448 notification_meta_t *next;
2450 if (n == NULL) {
2451 ERROR("plugin_notification_meta_free: n == NULL!");
2452 return (-1);
2453 }
2455 this = n;
2456 while (this != NULL) {
2457 next = this->next;
2459 if (this->type == NM_TYPE_STRING) {
2460 /* Assign to a temporary variable to work around nm_string's const
2461 * modifier. */
2462 void *tmp = (void *)this->nm_value.nm_string;
2464 sfree(tmp);
2465 this->nm_value.nm_string = NULL;
2466 }
2467 sfree(this);
2469 this = next;
2470 }
2472 return (0);
2473 } /* int plugin_notification_meta_free */
2475 static void plugin_ctx_destructor(void *ctx) {
2476 sfree(ctx);
2477 } /* void plugin_ctx_destructor */
2479 static plugin_ctx_t ctx_init = {/* interval = */ 0};
2481 static plugin_ctx_t *plugin_ctx_create(void) {
2482 plugin_ctx_t *ctx;
2484 ctx = malloc(sizeof(*ctx));
2485 if (ctx == NULL) {
2486 char errbuf[1024];
2487 ERROR("Failed to allocate plugin context: %s",
2488 sstrerror(errno, errbuf, sizeof(errbuf)));
2489 return NULL;
2490 }
2492 *ctx = ctx_init;
2493 assert(plugin_ctx_key_initialized);
2494 pthread_setspecific(plugin_ctx_key, ctx);
2495 DEBUG("Created new plugin context.");
2496 return (ctx);
2497 } /* int plugin_ctx_create */
2499 void plugin_init_ctx(void) {
2500 pthread_key_create(&plugin_ctx_key, plugin_ctx_destructor);
2501 plugin_ctx_key_initialized = 1;
2502 } /* void plugin_init_ctx */
2504 plugin_ctx_t plugin_get_ctx(void) {
2505 plugin_ctx_t *ctx;
2507 assert(plugin_ctx_key_initialized);
2508 ctx = pthread_getspecific(plugin_ctx_key);
2510 if (ctx == NULL) {
2511 ctx = plugin_ctx_create();
2512 /* this must no happen -- exit() instead? */
2513 if (ctx == NULL)
2514 return ctx_init;
2515 }
2517 return (*ctx);
2518 } /* plugin_ctx_t plugin_get_ctx */
2520 plugin_ctx_t plugin_set_ctx(plugin_ctx_t ctx) {
2521 plugin_ctx_t *c;
2522 plugin_ctx_t old;
2524 assert(plugin_ctx_key_initialized);
2525 c = pthread_getspecific(plugin_ctx_key);
2527 if (c == NULL) {
2528 c = plugin_ctx_create();
2529 /* this must no happen -- exit() instead? */
2530 if (c == NULL)
2531 return ctx_init;
2532 }
2534 old = *c;
2535 *c = ctx;
2537 return (old);
2538 } /* void plugin_set_ctx */
2540 cdtime_t plugin_get_interval(void) {
2541 cdtime_t interval;
2543 interval = plugin_get_ctx().interval;
2544 if (interval > 0)
2545 return interval;
2547 return cf_get_default_interval();
2548 } /* cdtime_t plugin_get_interval */
2550 typedef struct {
2551 plugin_ctx_t ctx;
2552 void *(*start_routine)(void *);
2553 void *arg;
2554 } plugin_thread_t;
2556 static void *plugin_thread_start(void *arg) {
2557 plugin_thread_t *plugin_thread = arg;
2559 void *(*start_routine)(void *) = plugin_thread->start_routine;
2560 void *plugin_arg = plugin_thread->arg;
2562 plugin_set_ctx(plugin_thread->ctx);
2564 sfree(plugin_thread);
2566 return start_routine(plugin_arg);
2567 } /* void *plugin_thread_start */
2569 int plugin_thread_create(pthread_t *thread, const pthread_attr_t *attr,
2570 void *(*start_routine)(void *), void *arg,
2571 char const *name) {
2572 plugin_thread_t *plugin_thread;
2574 plugin_thread = malloc(sizeof(*plugin_thread));
2575 if (plugin_thread == NULL)
2576 return ENOMEM;
2578 plugin_thread->ctx = plugin_get_ctx();
2579 plugin_thread->start_routine = start_routine;
2580 plugin_thread->arg = arg;
2582 int ret = pthread_create(thread, attr, plugin_thread_start, plugin_thread);
2583 if (ret != 0) {
2584 sfree(plugin_thread);
2585 return ret;
2586 }
2588 if (name != NULL)
2589 set_thread_name(*thread, name);
2591 return 0;
2592 } /* int plugin_thread_create */
2594 /* vim: set sw=8 ts=8 noet fdm=marker : */