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 <dlfcn.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 void plugin_update_internal_statistics(void) { /* {{{ */
158 gauge_t copy_write_queue_length = (gauge_t)write_queue_length;
160 /* Initialize `vl' */
161 value_list_t vl = VALUE_LIST_INIT;
162 sstrncpy(vl.host, hostname_g, sizeof(vl.host));
163 sstrncpy(vl.plugin, "collectd", sizeof(vl.plugin));
165 /* Write queue */
166 sstrncpy(vl.plugin_instance, "write_queue", sizeof(vl.plugin_instance));
168 /* Write queue : queue length */
169 vl.values = &(value_t){.gauge = copy_write_queue_length};
170 vl.values_len = 1;
171 sstrncpy(vl.type, "queue_length", sizeof(vl.type));
172 vl.type_instance[0] = 0;
173 plugin_dispatch_values(&vl);
175 /* Write queue : Values dropped (queue length > low limit) */
176 vl.values = &(value_t){.gauge = (gauge_t)stats_values_dropped};
177 vl.values_len = 1;
178 sstrncpy(vl.type, "derive", sizeof(vl.type));
179 sstrncpy(vl.type_instance, "dropped", sizeof(vl.type_instance));
180 plugin_dispatch_values(&vl);
182 /* Cache */
183 sstrncpy(vl.plugin_instance, "cache", sizeof(vl.plugin_instance));
185 /* Cache : Nb entry in cache tree */
186 vl.values = &(value_t){.gauge = (gauge_t)uc_get_size()};
187 vl.values_len = 1;
188 sstrncpy(vl.type, "cache_size", sizeof(vl.type));
189 vl.type_instance[0] = 0;
190 plugin_dispatch_values(&vl);
192 return;
193 } /* }}} void plugin_update_internal_statistics */
195 static void destroy_callback(callback_func_t *cf) /* {{{ */
196 {
197 if (cf == NULL)
198 return;
200 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;
204 }
205 sfree(cf);
206 } /* }}} void destroy_callback */
208 static void destroy_all_callbacks(llist_t **list) /* {{{ */
209 {
210 llentry_t *le;
212 if (*list == NULL)
213 return;
215 le = llist_head(*list);
216 while (le != NULL) {
217 llentry_t *le_next;
219 le_next = le->next;
221 sfree(le->key);
222 destroy_callback(le->value);
223 le->value = NULL;
225 le = le_next;
226 }
228 llist_destroy(*list);
229 *list = NULL;
230 } /* }}} void destroy_all_callbacks */
232 static void destroy_read_heap(void) /* {{{ */
233 {
234 if (read_heap == NULL)
235 return;
237 while (42) {
238 read_func_t *rf;
240 rf = c_heap_get_root(read_heap);
241 if (rf == NULL)
242 break;
243 sfree(rf->rf_name);
244 destroy_callback((callback_func_t *)rf);
245 }
247 c_heap_destroy(read_heap);
248 read_heap = NULL;
249 } /* }}} void destroy_read_heap */
251 static int register_callback(llist_t **list, /* {{{ */
252 const char *name, callback_func_t *cf) {
253 llentry_t *le;
254 char *key;
256 if (*list == NULL) {
257 *list = llist_create();
258 if (*list == NULL) {
259 ERROR("plugin: register_callback: "
260 "llist_create failed.");
261 destroy_callback(cf);
262 return (-1);
263 }
264 }
266 key = strdup(name);
267 if (key == NULL) {
268 ERROR("plugin: register_callback: strdup failed.");
269 destroy_callback(cf);
270 return (-1);
271 }
273 le = llist_search(*list, name);
274 if (le == NULL) {
275 le = llentry_create(key, cf);
276 if (le == NULL) {
277 ERROR("plugin: register_callback: "
278 "llentry_create failed.");
279 sfree(key);
280 destroy_callback(cf);
281 return (-1);
282 }
284 llist_append(*list, le);
285 } else {
286 callback_func_t *old_cf;
288 old_cf = le->value;
289 le->value = cf;
291 WARNING("plugin: register_callback: "
292 "a callback named `%s' already exists - "
293 "overwriting the old entry!",
294 name);
296 destroy_callback(old_cf);
297 sfree(key);
298 }
300 return (0);
301 } /* }}} int register_callback */
303 static void log_list_callbacks(llist_t **list, /* {{{ */
304 const char *comment) {
305 char *str;
306 int len;
307 int i;
308 llentry_t *le;
309 int n;
310 char **keys;
312 n = llist_size(*list);
313 if (n == 0) {
314 INFO("%s [none]", comment);
315 return;
316 }
318 keys = calloc(n, sizeof(char *));
320 if (keys == NULL) {
321 ERROR("%s: failed to allocate memory for list of callbacks", comment);
323 return;
324 }
326 for (le = llist_head(*list), i = 0, len = 0; le != NULL; le = le->next, i++) {
327 keys[i] = le->key;
328 len += strlen(le->key) + 6;
329 }
330 str = malloc(len + 10);
331 if (str == NULL) {
332 ERROR("%s: failed to allocate memory for list of callbacks", comment);
333 } else {
334 *str = '\0';
335 strjoin(str, len, keys, n, "', '");
336 INFO("%s ['%s']", comment, str);
337 sfree(str);
338 }
339 sfree(keys);
340 } /* }}} void log_list_callbacks */
342 static int create_register_callback(llist_t **list, /* {{{ */
343 const char *name, void *callback,
344 user_data_t const *ud) {
345 callback_func_t *cf;
347 cf = calloc(1, sizeof(*cf));
348 if (cf == NULL) {
349 ERROR("plugin: create_register_callback: calloc failed.");
350 return (-1);
351 }
353 cf->cf_callback = callback;
354 if (ud == NULL) {
355 cf->cf_udata.data = NULL;
356 cf->cf_udata.free_func = NULL;
357 } else {
358 cf->cf_udata = *ud;
359 }
361 cf->cf_ctx = plugin_get_ctx();
363 return (register_callback(list, name, cf));
364 } /* }}} int create_register_callback */
366 static int plugin_unregister(llist_t *list, const char *name) /* {{{ */
367 {
368 llentry_t *e;
370 if (list == NULL)
371 return (-1);
373 e = llist_search(list, name);
374 if (e == NULL)
375 return (-1);
377 llist_remove(list, e);
379 sfree(e->key);
380 destroy_callback(e->value);
382 llentry_destroy(e);
384 return (0);
385 } /* }}} int plugin_unregister */
387 /*
388 * (Try to) load the shared object `file'. Won't complain if it isn't a shared
389 * object, but it will bitch about a shared object not having a
390 * ``module_register'' symbol..
391 */
392 static int plugin_load_file(const char *file, _Bool global) {
393 void (*reg_handle)(void);
395 int flags = RTLD_NOW;
396 if (global)
397 flags |= RTLD_GLOBAL;
399 void *dlh = dlopen(file, flags);
401 if (dlh == NULL) {
402 char errbuf[1024] = "";
404 ssnprintf(errbuf, sizeof(errbuf),
405 "dlopen (\"%s\") failed: %s. "
406 "The most common cause for this problem is "
407 "missing dependencies. Use ldd(1) to check "
408 "the dependencies of the plugin "
409 "/ shared object.",
410 file, dlerror());
412 ERROR("%s", errbuf);
413 /* Make sure this is printed to STDERR in any case, but also
414 * make sure it's printed only once. */
415 if (list_log != NULL)
416 fprintf(stderr, "ERROR: %s\n", errbuf);
418 return (1);
419 }
421 reg_handle = (void (*)(void))dlsym(dlh, "module_register");
422 if (reg_handle == NULL) {
423 WARNING("Couldn't find symbol \"module_register\" in \"%s\": %s\n", file,
424 dlerror());
425 dlclose(dlh);
426 return (-1);
427 }
429 (*reg_handle)();
431 return (0);
432 }
434 static void *plugin_read_thread(void __attribute__((unused)) * args) {
435 while (read_loop != 0) {
436 read_func_t *rf;
437 plugin_ctx_t old_ctx;
438 cdtime_t start;
439 cdtime_t now;
440 cdtime_t elapsed;
441 int status;
442 int rf_type;
443 int rc;
445 /* Get the read function that needs to be read next.
446 * We don't need to hold "read_lock" for the heap, but we need
447 * to call c_heap_get_root() and pthread_cond_wait() in the
448 * same protected block. */
449 pthread_mutex_lock(&read_lock);
450 rf = c_heap_get_root(read_heap);
451 if (rf == NULL) {
452 pthread_cond_wait(&read_cond, &read_lock);
453 pthread_mutex_unlock(&read_lock);
454 continue;
455 }
456 pthread_mutex_unlock(&read_lock);
458 if (rf->rf_interval == 0) {
459 /* this should not happen, because the interval is set
460 * for each plugin when loading it
461 * XXX: issue a warning? */
462 rf->rf_interval = plugin_get_interval();
463 rf->rf_effective_interval = rf->rf_interval;
465 rf->rf_next_read = cdtime();
466 }
468 /* sleep until this entry is due,
469 * using pthread_cond_timedwait */
470 pthread_mutex_lock(&read_lock);
471 /* In pthread_cond_timedwait, spurious wakeups are possible
472 * (and really happen, at least on NetBSD with > 1 CPU), thus
473 * we need to re-evaluate the condition every time
474 * pthread_cond_timedwait returns. */
475 rc = 0;
476 while ((read_loop != 0) && (cdtime() < rf->rf_next_read) && rc == 0) {
477 rc = pthread_cond_timedwait(&read_cond, &read_lock,
478 &CDTIME_T_TO_TIMESPEC(rf->rf_next_read));
479 }
481 /* Must hold `read_lock' when accessing `rf->rf_type'. */
482 rf_type = rf->rf_type;
483 pthread_mutex_unlock(&read_lock);
485 /* Check if we're supposed to stop.. This may have interrupted
486 * the sleep, too. */
487 if (read_loop == 0) {
488 /* Insert `rf' again, so it can be free'd correctly */
489 c_heap_insert(read_heap, rf);
490 break;
491 }
493 /* The entry has been marked for deletion. The linked list
494 * entry has already been removed by `plugin_unregister_read'.
495 * All we have to do here is free the `read_func_t' and
496 * continue. */
497 if (rf_type == RF_REMOVE) {
498 DEBUG("plugin_read_thread: Destroying the `%s' "
499 "callback.",
500 rf->rf_name);
501 sfree(rf->rf_name);
502 destroy_callback((callback_func_t *)rf);
503 rf = NULL;
504 continue;
505 }
507 DEBUG("plugin_read_thread: Handling `%s'.", rf->rf_name);
509 start = cdtime();
511 old_ctx = plugin_set_ctx(rf->rf_ctx);
513 if (rf_type == RF_SIMPLE) {
514 int (*callback)(void);
516 callback = rf->rf_callback;
517 status = (*callback)();
518 } else {
519 plugin_read_cb callback;
521 assert(rf_type == RF_COMPLEX);
523 callback = rf->rf_callback;
524 status = (*callback)(&rf->rf_udata);
525 }
527 plugin_set_ctx(old_ctx);
529 /* If the function signals failure, we will increase the
530 * intervals in which it will be called. */
531 if (status != 0) {
532 rf->rf_effective_interval *= 2;
533 if (rf->rf_effective_interval > max_read_interval)
534 rf->rf_effective_interval = max_read_interval;
536 NOTICE("read-function of plugin `%s' failed. "
537 "Will suspend it for %.3f seconds.",
538 rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
539 } else {
540 /* Success: Restore the interval, if it was changed. */
541 rf->rf_effective_interval = rf->rf_interval;
542 }
544 /* update the ``next read due'' field */
545 now = cdtime();
547 /* calculate the time spent in the read function */
548 elapsed = (now - start);
550 if (elapsed > rf->rf_effective_interval)
551 WARNING(
552 "plugin_read_thread: read-function of the `%s' plugin took %.3f "
553 "seconds, which is above its read interval (%.3f seconds). You might "
554 "want to adjust the `Interval' or `ReadThreads' settings.",
555 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed),
556 CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
558 DEBUG("plugin_read_thread: read-function of the `%s' plugin took "
559 "%.6f seconds.",
560 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed));
562 DEBUG("plugin_read_thread: Effective interval of the "
563 "`%s' plugin is %.3f seconds.",
564 rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
566 /* Calculate the next (absolute) time at which this function
567 * should be called. */
568 rf->rf_next_read += rf->rf_effective_interval;
570 /* Check, if `rf_next_read' is in the past. */
571 if (rf->rf_next_read < now) {
572 /* `rf_next_read' is in the past. Insert `now'
573 * so this value doesn't trail off into the
574 * past too much. */
575 rf->rf_next_read = now;
576 }
578 DEBUG("plugin_read_thread: Next read of the `%s' plugin at %.3f.",
579 rf->rf_name, CDTIME_T_TO_DOUBLE(rf->rf_next_read));
581 /* Re-insert this read function into the heap again. */
582 c_heap_insert(read_heap, rf);
583 } /* while (read_loop) */
585 pthread_exit(NULL);
586 return ((void *)0);
587 } /* void *plugin_read_thread */
589 #ifdef PTHREAD_MAX_NAMELEN_NP
590 #define THREAD_NAME_MAX PTHREAD_MAX_NAMELEN_NP
591 #else
592 #define THREAD_NAME_MAX 16
593 #endif
595 static void set_thread_name(pthread_t tid, char const *name) {
596 #if defined(HAVE_PTHREAD_SETNAME_NP) || defined(HAVE_PTHREAD_SET_NAME_NP)
598 /* glibc limits the length of the name and fails if the passed string
599 * is too long, so we truncate it here. */
600 char n[THREAD_NAME_MAX];
601 if (strlen(name) >= THREAD_NAME_MAX)
602 WARNING("set_thread_name(\"%s\"): name too long", name);
603 sstrncpy(n, name, sizeof(n));
605 #if defined(HAVE_PTHREAD_SETNAME_NP)
606 int status = pthread_setname_np(tid, n);
607 if (status != 0) {
608 char errbuf[1024];
609 ERROR("set_thread_name(\"%s\"): %s", n,
610 sstrerror(status, errbuf, sizeof(errbuf)));
611 }
612 #else /* if defined(HAVE_PTHREAD_SET_NAME_NP) */
613 pthread_set_name_np(tid, n);
614 #endif
616 #endif
617 }
619 static void start_read_threads(size_t num) /* {{{ */
620 {
621 if (read_threads != NULL)
622 return;
624 read_threads = (pthread_t *)calloc(num, sizeof(pthread_t));
625 if (read_threads == NULL) {
626 ERROR("plugin: start_read_threads: calloc failed.");
627 return;
628 }
630 read_threads_num = 0;
631 for (size_t i = 0; i < num; i++) {
632 int status = pthread_create(read_threads + read_threads_num,
633 /* attr = */ NULL, plugin_read_thread,
634 /* arg = */ NULL);
635 if (status != 0) {
636 char errbuf[1024];
637 ERROR("plugin: start_read_threads: pthread_create failed "
638 "with status %i (%s).",
639 status, sstrerror(status, errbuf, sizeof(errbuf)));
640 return;
641 }
643 char name[THREAD_NAME_MAX];
644 ssnprintf(name, sizeof(name), "reader#%zu", read_threads_num);
645 set_thread_name(read_threads[read_threads_num], name);
647 read_threads_num++;
648 } /* for (i) */
649 } /* }}} void start_read_threads */
651 static void stop_read_threads(void) {
652 if (read_threads == NULL)
653 return;
655 INFO("collectd: Stopping %zu read threads.", read_threads_num);
657 pthread_mutex_lock(&read_lock);
658 read_loop = 0;
659 DEBUG("plugin: stop_read_threads: Signalling `read_cond'");
660 pthread_cond_broadcast(&read_cond);
661 pthread_mutex_unlock(&read_lock);
663 for (size_t i = 0; i < read_threads_num; i++) {
664 if (pthread_join(read_threads[i], NULL) != 0) {
665 ERROR("plugin: stop_read_threads: pthread_join failed.");
666 }
667 read_threads[i] = (pthread_t)0;
668 }
669 sfree(read_threads);
670 read_threads_num = 0;
671 } /* void stop_read_threads */
673 static void plugin_value_list_free(value_list_t *vl) /* {{{ */
674 {
675 if (vl == NULL)
676 return;
678 meta_data_destroy(vl->meta);
679 sfree(vl->values);
680 sfree(vl);
681 } /* }}} void plugin_value_list_free */
683 static value_list_t *
684 plugin_value_list_clone(value_list_t const *vl_orig) /* {{{ */
685 {
686 value_list_t *vl;
688 if (vl_orig == NULL)
689 return (NULL);
691 vl = malloc(sizeof(*vl));
692 if (vl == NULL)
693 return (NULL);
694 memcpy(vl, vl_orig, sizeof(*vl));
696 if (vl->host[0] == 0)
697 sstrncpy(vl->host, hostname_g, sizeof(vl->host));
699 vl->values = calloc(vl_orig->values_len, sizeof(*vl->values));
700 if (vl->values == NULL) {
701 plugin_value_list_free(vl);
702 return (NULL);
703 }
704 memcpy(vl->values, vl_orig->values,
705 vl_orig->values_len * sizeof(*vl->values));
707 vl->meta = meta_data_clone(vl->meta);
708 if ((vl_orig->meta != NULL) && (vl->meta == NULL)) {
709 plugin_value_list_free(vl);
710 return (NULL);
711 }
713 if (vl->time == 0)
714 vl->time = cdtime();
716 /* Fill in the interval from the thread context, if it is zero. */
717 if (vl->interval == 0) {
718 plugin_ctx_t ctx = plugin_get_ctx();
720 if (ctx.interval != 0)
721 vl->interval = ctx.interval;
722 else {
723 char name[6 * DATA_MAX_NAME_LEN];
724 FORMAT_VL(name, sizeof(name), vl);
725 ERROR("plugin_value_list_clone: Unable to determine "
726 "interval from context for "
727 "value list \"%s\". "
728 "This indicates a broken plugin. "
729 "Please report this problem to the "
730 "collectd mailing list or at "
731 "<http://collectd.org/bugs/>.",
732 name);
733 vl->interval = cf_get_default_interval();
734 }
735 }
737 return (vl);
738 } /* }}} value_list_t *plugin_value_list_clone */
740 static int plugin_write_enqueue(value_list_t const *vl) /* {{{ */
741 {
742 write_queue_t *q;
744 q = malloc(sizeof(*q));
745 if (q == NULL)
746 return (ENOMEM);
747 q->next = NULL;
749 q->vl = plugin_value_list_clone(vl);
750 if (q->vl == NULL) {
751 sfree(q);
752 return (ENOMEM);
753 }
755 /* Store context of caller (read plugin); otherwise, it would not be
756 * available to the write plugins when actually dispatching the
757 * value-list later on. */
758 q->ctx = plugin_get_ctx();
760 pthread_mutex_lock(&write_lock);
762 if (write_queue_tail == NULL) {
763 write_queue_head = q;
764 write_queue_tail = q;
765 write_queue_length = 1;
766 } else {
767 write_queue_tail->next = q;
768 write_queue_tail = q;
769 write_queue_length += 1;
770 }
772 pthread_cond_signal(&write_cond);
773 pthread_mutex_unlock(&write_lock);
775 return (0);
776 } /* }}} int plugin_write_enqueue */
778 static value_list_t *plugin_write_dequeue(void) /* {{{ */
779 {
780 write_queue_t *q;
781 value_list_t *vl;
783 pthread_mutex_lock(&write_lock);
785 while (write_loop && (write_queue_head == NULL))
786 pthread_cond_wait(&write_cond, &write_lock);
788 if (write_queue_head == NULL) {
789 pthread_mutex_unlock(&write_lock);
790 return (NULL);
791 }
793 q = write_queue_head;
794 write_queue_head = q->next;
795 write_queue_length -= 1;
796 if (write_queue_head == NULL) {
797 write_queue_tail = NULL;
798 assert(0 == write_queue_length);
799 }
801 pthread_mutex_unlock(&write_lock);
803 (void)plugin_set_ctx(q->ctx);
805 vl = q->vl;
806 sfree(q);
807 return (vl);
808 } /* }}} value_list_t *plugin_write_dequeue */
810 static void *plugin_write_thread(void __attribute__((unused)) * args) /* {{{ */
811 {
812 while (write_loop) {
813 value_list_t *vl = plugin_write_dequeue();
814 if (vl == NULL)
815 continue;
817 plugin_dispatch_values_internal(vl);
819 plugin_value_list_free(vl);
820 }
822 pthread_exit(NULL);
823 return ((void *)0);
824 } /* }}} void *plugin_write_thread */
826 static void start_write_threads(size_t num) /* {{{ */
827 {
828 if (write_threads != NULL)
829 return;
831 write_threads = (pthread_t *)calloc(num, sizeof(pthread_t));
832 if (write_threads == NULL) {
833 ERROR("plugin: start_write_threads: calloc failed.");
834 return;
835 }
837 write_threads_num = 0;
838 for (size_t i = 0; i < num; i++) {
839 int status = pthread_create(write_threads + write_threads_num,
840 /* attr = */ NULL, plugin_write_thread,
841 /* arg = */ NULL);
842 if (status != 0) {
843 char errbuf[1024];
844 ERROR("plugin: start_write_threads: pthread_create failed "
845 "with status %i (%s).",
846 status, sstrerror(status, errbuf, sizeof(errbuf)));
847 return;
848 }
850 char name[THREAD_NAME_MAX];
851 ssnprintf(name, sizeof(name), "writer#%zu", write_threads_num);
852 set_thread_name(write_threads[write_threads_num], name);
854 write_threads_num++;
855 } /* for (i) */
856 } /* }}} void start_write_threads */
858 static void stop_write_threads(void) /* {{{ */
859 {
860 write_queue_t *q;
861 size_t i;
863 if (write_threads == NULL)
864 return;
866 INFO("collectd: Stopping %zu write threads.", write_threads_num);
868 pthread_mutex_lock(&write_lock);
869 write_loop = 0;
870 DEBUG("plugin: stop_write_threads: Signalling `write_cond'");
871 pthread_cond_broadcast(&write_cond);
872 pthread_mutex_unlock(&write_lock);
874 for (i = 0; i < write_threads_num; i++) {
875 if (pthread_join(write_threads[i], NULL) != 0) {
876 ERROR("plugin: stop_write_threads: pthread_join failed.");
877 }
878 write_threads[i] = (pthread_t)0;
879 }
880 sfree(write_threads);
881 write_threads_num = 0;
883 pthread_mutex_lock(&write_lock);
884 i = 0;
885 for (q = write_queue_head; q != NULL;) {
886 write_queue_t *q1 = q;
887 plugin_value_list_free(q->vl);
888 q = q->next;
889 sfree(q1);
890 i++;
891 }
892 write_queue_head = NULL;
893 write_queue_tail = NULL;
894 write_queue_length = 0;
895 pthread_mutex_unlock(&write_lock);
897 if (i > 0) {
898 WARNING("plugin: %zu value list%s left after shutting down "
899 "the write threads.",
900 i, (i == 1) ? " was" : "s were");
901 }
902 } /* }}} void stop_write_threads */
904 /*
905 * Public functions
906 */
907 void plugin_set_dir(const char *dir) {
908 sfree(plugindir);
910 if (dir == NULL) {
911 plugindir = NULL;
912 return;
913 }
915 plugindir = strdup(dir);
916 if (plugindir == NULL)
917 ERROR("plugin_set_dir: strdup(\"%s\") failed", dir);
918 }
920 static _Bool plugin_is_loaded(char const *name) {
921 int status;
923 if (plugins_loaded == NULL)
924 plugins_loaded =
925 c_avl_create((int (*)(const void *, const void *))strcasecmp);
926 assert(plugins_loaded != NULL);
928 status = c_avl_get(plugins_loaded, name, /* ret_value = */ NULL);
929 return (status == 0);
930 }
932 static int plugin_mark_loaded(char const *name) {
933 char *name_copy;
934 int status;
936 name_copy = strdup(name);
937 if (name_copy == NULL)
938 return (ENOMEM);
940 status = c_avl_insert(plugins_loaded,
941 /* key = */ name_copy, /* value = */ NULL);
942 return (status);
943 }
945 static void plugin_free_loaded(void) {
946 void *key;
947 void *value;
949 if (plugins_loaded == NULL)
950 return;
952 while (c_avl_pick(plugins_loaded, &key, &value) == 0) {
953 sfree(key);
954 assert(value == NULL);
955 }
957 c_avl_destroy(plugins_loaded);
958 plugins_loaded = NULL;
959 }
961 #define BUFSIZE 512
962 int plugin_load(char const *plugin_name, _Bool global) {
963 DIR *dh;
964 const char *dir;
965 char filename[BUFSIZE] = "";
966 char typename[BUFSIZE];
967 int ret;
968 struct stat statbuf;
969 struct dirent *de;
970 int status;
972 if (plugin_name == NULL)
973 return (EINVAL);
975 /* Check if plugin is already loaded and don't do anything in this
976 * case. */
977 if (plugin_is_loaded(plugin_name))
978 return (0);
980 dir = plugin_get_dir();
981 ret = 1;
983 /*
984 * XXX: Magic at work:
985 *
986 * Some of the language bindings, for example the Python and Perl
987 * plugins, need to be able to export symbols to the scripts they run.
988 * For this to happen, the "Globals" flag needs to be set.
989 * Unfortunately, this technical detail is hard to explain to the
990 * average user and she shouldn't have to worry about this, ideally.
991 * So in order to save everyone's sanity use a different default for a
992 * handful of special plugins. --octo
993 */
994 if ((strcasecmp("perl", plugin_name) == 0) ||
995 (strcasecmp("python", plugin_name) == 0))
996 global = 1;
998 /* `cpu' should not match `cpufreq'. To solve this we add `.so' to the
999 * type when matching the filename */
1000 status = ssnprintf(typename, sizeof(typename), "%s.so", plugin_name);
1001 if ((status < 0) || ((size_t)status >= sizeof(typename))) {
1002 WARNING("plugin_load: Filename too long: \"%s.so\"", plugin_name);
1003 return (-1);
1004 }
1006 if ((dh = opendir(dir)) == NULL) {
1007 char errbuf[1024];
1008 ERROR("plugin_load: opendir (%s) failed: %s", dir,
1009 sstrerror(errno, errbuf, sizeof(errbuf)));
1010 return (-1);
1011 }
1013 while ((de = readdir(dh)) != NULL) {
1014 if (strcasecmp(de->d_name, typename))
1015 continue;
1017 status = ssnprintf(filename, sizeof(filename), "%s/%s", dir, de->d_name);
1018 if ((status < 0) || ((size_t)status >= sizeof(filename))) {
1019 WARNING("plugin_load: Filename too long: \"%s/%s\"", dir, de->d_name);
1020 continue;
1021 }
1023 if (lstat(filename, &statbuf) == -1) {
1024 char errbuf[1024];
1025 WARNING("plugin_load: stat (\"%s\") failed: %s", filename,
1026 sstrerror(errno, errbuf, sizeof(errbuf)));
1027 continue;
1028 } else if (!S_ISREG(statbuf.st_mode)) {
1029 /* don't follow symlinks */
1030 WARNING("plugin_load: %s is not a regular file.", filename);
1031 continue;
1032 }
1034 status = plugin_load_file(filename, global);
1035 if (status == 0) {
1036 /* success */
1037 plugin_mark_loaded(plugin_name);
1038 ret = 0;
1039 INFO("plugin_load: plugin \"%s\" successfully loaded.", plugin_name);
1040 break;
1041 } else {
1042 ERROR("plugin_load: Load plugin \"%s\" failed with "
1043 "status %i.",
1044 plugin_name, status);
1045 }
1046 }
1048 closedir(dh);
1050 if (filename[0] == 0)
1051 ERROR("plugin_load: Could not find plugin \"%s\" in %s", plugin_name, dir);
1053 return (ret);
1054 }
1056 /*
1057 * The `register_*' functions follow
1058 */
1059 int plugin_register_config(const char *name,
1060 int (*callback)(const char *key, const char *val),
1061 const char **keys, int keys_num) {
1062 cf_register(name, callback, keys, keys_num);
1063 return (0);
1064 } /* int plugin_register_config */
1066 int plugin_register_complex_config(const char *type,
1067 int (*callback)(oconfig_item_t *)) {
1068 return (cf_register_complex(type, callback));
1069 } /* int plugin_register_complex_config */
1071 int plugin_register_init(const char *name, int (*callback)(void)) {
1072 return (create_register_callback(&list_init, name, (void *)callback,
1073 /* user_data = */ NULL));
1074 } /* plugin_register_init */
1076 static int plugin_compare_read_func(const void *arg0, const void *arg1) {
1077 const read_func_t *rf0;
1078 const read_func_t *rf1;
1080 rf0 = arg0;
1081 rf1 = arg1;
1083 if (rf0->rf_next_read < rf1->rf_next_read)
1084 return (-1);
1085 else if (rf0->rf_next_read > rf1->rf_next_read)
1086 return (1);
1087 else
1088 return (0);
1089 } /* int plugin_compare_read_func */
1091 /* Add a read function to both, the heap and a linked list. The linked list if
1092 * used to look-up read functions, especially for the remove function. The heap
1093 * is used to determine which plugin to read next. */
1094 static int plugin_insert_read(read_func_t *rf) {
1095 int status;
1096 llentry_t *le;
1098 rf->rf_next_read = cdtime();
1099 rf->rf_effective_interval = rf->rf_interval;
1101 pthread_mutex_lock(&read_lock);
1103 if (read_list == NULL) {
1104 read_list = llist_create();
1105 if (read_list == NULL) {
1106 pthread_mutex_unlock(&read_lock);
1107 ERROR("plugin_insert_read: read_list failed.");
1108 return (-1);
1109 }
1110 }
1112 if (read_heap == NULL) {
1113 read_heap = c_heap_create(plugin_compare_read_func);
1114 if (read_heap == NULL) {
1115 pthread_mutex_unlock(&read_lock);
1116 ERROR("plugin_insert_read: c_heap_create failed.");
1117 return (-1);
1118 }
1119 }
1121 le = llist_search(read_list, rf->rf_name);
1122 if (le != NULL) {
1123 pthread_mutex_unlock(&read_lock);
1124 WARNING("The read function \"%s\" is already registered. "
1125 "Check for duplicate \"LoadPlugin\" lines "
1126 "in your configuration!",
1127 rf->rf_name);
1128 return (EINVAL);
1129 }
1131 le = llentry_create(rf->rf_name, rf);
1132 if (le == NULL) {
1133 pthread_mutex_unlock(&read_lock);
1134 ERROR("plugin_insert_read: llentry_create failed.");
1135 return (-1);
1136 }
1138 status = c_heap_insert(read_heap, rf);
1139 if (status != 0) {
1140 pthread_mutex_unlock(&read_lock);
1141 ERROR("plugin_insert_read: c_heap_insert failed.");
1142 llentry_destroy(le);
1143 return (-1);
1144 }
1146 /* This does not fail. */
1147 llist_append(read_list, le);
1149 /* Wake up all the read threads. */
1150 pthread_cond_broadcast(&read_cond);
1151 pthread_mutex_unlock(&read_lock);
1152 return (0);
1153 } /* int plugin_insert_read */
1155 int plugin_register_read(const char *name, int (*callback)(void)) {
1156 read_func_t *rf;
1157 int status;
1159 rf = calloc(1, sizeof(*rf));
1160 if (rf == NULL) {
1161 ERROR("plugin_register_read: calloc failed.");
1162 return (ENOMEM);
1163 }
1165 rf->rf_callback = (void *)callback;
1166 rf->rf_udata.data = NULL;
1167 rf->rf_udata.free_func = NULL;
1168 rf->rf_ctx = plugin_get_ctx();
1169 rf->rf_group[0] = '\0';
1170 rf->rf_name = strdup(name);
1171 rf->rf_type = RF_SIMPLE;
1172 rf->rf_interval = plugin_get_interval();
1174 status = plugin_insert_read(rf);
1175 if (status != 0) {
1176 sfree(rf->rf_name);
1177 sfree(rf);
1178 }
1180 return (status);
1181 } /* int plugin_register_read */
1183 int plugin_register_complex_read(const char *group, const char *name,
1184 plugin_read_cb callback, cdtime_t interval,
1185 user_data_t const *user_data) {
1186 read_func_t *rf;
1187 int status;
1189 rf = calloc(1, sizeof(*rf));
1190 if (rf == NULL) {
1191 ERROR("plugin_register_complex_read: calloc failed.");
1192 return (ENOMEM);
1193 }
1195 rf->rf_callback = (void *)callback;
1196 if (group != NULL)
1197 sstrncpy(rf->rf_group, group, sizeof(rf->rf_group));
1198 else
1199 rf->rf_group[0] = '\0';
1200 rf->rf_name = strdup(name);
1201 rf->rf_type = RF_COMPLEX;
1202 rf->rf_interval = (interval != 0) ? interval : plugin_get_interval();
1204 /* Set user data */
1205 if (user_data == NULL) {
1206 rf->rf_udata.data = NULL;
1207 rf->rf_udata.free_func = NULL;
1208 } else {
1209 rf->rf_udata = *user_data;
1210 }
1212 rf->rf_ctx = plugin_get_ctx();
1214 status = plugin_insert_read(rf);
1215 if (status != 0) {
1216 sfree(rf->rf_name);
1217 sfree(rf);
1218 }
1220 return (status);
1221 } /* int plugin_register_complex_read */
1223 int plugin_register_write(const char *name, plugin_write_cb callback,
1224 user_data_t const *ud) {
1225 return (create_register_callback(&list_write, name, (void *)callback, ud));
1226 } /* int plugin_register_write */
1228 static int plugin_flush_timeout_callback(user_data_t *ud) {
1229 flush_callback_t *cb = ud->data;
1231 return plugin_flush(cb->name, cb->timeout, /* identifier = */ NULL);
1232 } /* static int plugin_flush_callback */
1234 static void plugin_flush_timeout_callback_free(void *data) {
1235 flush_callback_t *cb = data;
1237 if (cb == NULL)
1238 return;
1240 sfree(cb->name);
1241 sfree(cb);
1242 } /* static void plugin_flush_callback_free */
1244 static char *plugin_flush_callback_name(const char *name) {
1245 const char *flush_prefix = "flush/";
1246 size_t prefix_size;
1247 char *flush_name;
1248 size_t name_size;
1250 prefix_size = strlen(flush_prefix);
1251 name_size = strlen(name);
1253 flush_name = malloc(name_size + prefix_size + 1);
1254 if (flush_name == NULL) {
1255 ERROR("plugin_flush_callback_name: malloc failed.");
1256 return (NULL);
1257 }
1259 sstrncpy(flush_name, flush_prefix, prefix_size + 1);
1260 sstrncpy(flush_name + prefix_size, name, name_size + 1);
1262 return flush_name;
1263 } /* static char *plugin_flush_callback_name */
1265 int plugin_register_flush(const char *name, plugin_flush_cb callback,
1266 user_data_t const *ud) {
1267 int status;
1268 plugin_ctx_t ctx = plugin_get_ctx();
1270 status = create_register_callback(&list_flush, name, (void *)callback, ud);
1271 if (status != 0)
1272 return status;
1274 if (ctx.flush_interval != 0) {
1275 char *flush_name;
1276 flush_callback_t *cb;
1278 flush_name = plugin_flush_callback_name(name);
1279 if (flush_name == NULL)
1280 return (-1);
1282 cb = malloc(sizeof(*cb));
1283 if (cb == NULL) {
1284 ERROR("plugin_register_flush: malloc failed.");
1285 sfree(flush_name);
1286 return (-1);
1287 }
1289 cb->name = strdup(name);
1290 if (cb->name == NULL) {
1291 ERROR("plugin_register_flush: strdup failed.");
1292 sfree(cb);
1293 sfree(flush_name);
1294 return (-1);
1295 }
1296 cb->timeout = ctx.flush_timeout;
1298 status = plugin_register_complex_read(
1299 /* group = */ "flush",
1300 /* name = */ flush_name,
1301 /* callback = */ plugin_flush_timeout_callback,
1302 /* interval = */ ctx.flush_interval,
1303 /* user data = */ &(user_data_t){
1304 .data = cb, .free_func = plugin_flush_timeout_callback_free,
1305 });
1307 sfree(flush_name);
1308 if (status != 0) {
1309 sfree(cb->name);
1310 sfree(cb);
1311 return status;
1312 }
1313 }
1315 return 0;
1316 } /* int plugin_register_flush */
1318 int plugin_register_missing(const char *name, plugin_missing_cb callback,
1319 user_data_t const *ud) {
1320 return (create_register_callback(&list_missing, name, (void *)callback, ud));
1321 } /* int plugin_register_missing */
1323 int plugin_register_shutdown(const char *name, int (*callback)(void)) {
1324 return (create_register_callback(&list_shutdown, name, (void *)callback,
1325 /* user_data = */ NULL));
1326 } /* int plugin_register_shutdown */
1328 static void plugin_free_data_sets(void) {
1329 void *key;
1330 void *value;
1332 if (data_sets == NULL)
1333 return;
1335 while (c_avl_pick(data_sets, &key, &value) == 0) {
1336 data_set_t *ds = value;
1337 /* key is a pointer to ds->type */
1339 sfree(ds->ds);
1340 sfree(ds);
1341 }
1343 c_avl_destroy(data_sets);
1344 data_sets = NULL;
1345 } /* void plugin_free_data_sets */
1347 int plugin_register_data_set(const data_set_t *ds) {
1348 data_set_t *ds_copy;
1350 if ((data_sets != NULL) && (c_avl_get(data_sets, ds->type, NULL) == 0)) {
1351 NOTICE("Replacing DS `%s' with another version.", ds->type);
1352 plugin_unregister_data_set(ds->type);
1353 } else if (data_sets == NULL) {
1354 data_sets = c_avl_create((int (*)(const void *, const void *))strcmp);
1355 if (data_sets == NULL)
1356 return (-1);
1357 }
1359 ds_copy = malloc(sizeof(*ds_copy));
1360 if (ds_copy == NULL)
1361 return (-1);
1362 memcpy(ds_copy, ds, sizeof(data_set_t));
1364 ds_copy->ds = malloc(sizeof(*ds_copy->ds) * ds->ds_num);
1365 if (ds_copy->ds == NULL) {
1366 sfree(ds_copy);
1367 return (-1);
1368 }
1370 for (size_t i = 0; i < ds->ds_num; i++)
1371 memcpy(ds_copy->ds + i, ds->ds + i, sizeof(data_source_t));
1373 return (c_avl_insert(data_sets, (void *)ds_copy->type, (void *)ds_copy));
1374 } /* int plugin_register_data_set */
1376 int plugin_register_log(const char *name, plugin_log_cb callback,
1377 user_data_t const *ud) {
1378 return (create_register_callback(&list_log, name, (void *)callback, ud));
1379 } /* int plugin_register_log */
1381 int plugin_register_notification(const char *name,
1382 plugin_notification_cb callback,
1383 user_data_t const *ud) {
1384 return (
1385 create_register_callback(&list_notification, name, (void *)callback, ud));
1386 } /* int plugin_register_log */
1388 int plugin_unregister_config(const char *name) {
1389 cf_unregister(name);
1390 return (0);
1391 } /* int plugin_unregister_config */
1393 int plugin_unregister_complex_config(const char *name) {
1394 cf_unregister_complex(name);
1395 return (0);
1396 } /* int plugin_unregister_complex_config */
1398 int plugin_unregister_init(const char *name) {
1399 return (plugin_unregister(list_init, name));
1400 }
1402 int plugin_unregister_read(const char *name) /* {{{ */
1403 {
1404 llentry_t *le;
1405 read_func_t *rf;
1407 if (name == NULL)
1408 return (-ENOENT);
1410 pthread_mutex_lock(&read_lock);
1412 if (read_list == NULL) {
1413 pthread_mutex_unlock(&read_lock);
1414 return (-ENOENT);
1415 }
1417 le = llist_search(read_list, name);
1418 if (le == NULL) {
1419 pthread_mutex_unlock(&read_lock);
1420 WARNING("plugin_unregister_read: No such read function: %s", name);
1421 return (-ENOENT);
1422 }
1424 llist_remove(read_list, le);
1426 rf = le->value;
1427 assert(rf != NULL);
1428 rf->rf_type = RF_REMOVE;
1430 pthread_mutex_unlock(&read_lock);
1432 llentry_destroy(le);
1434 DEBUG("plugin_unregister_read: Marked `%s' for removal.", name);
1436 return (0);
1437 } /* }}} int plugin_unregister_read */
1439 void plugin_log_available_writers(void) {
1440 log_list_callbacks(&list_write, "Available write targets:");
1441 }
1443 static int compare_read_func_group(llentry_t *e, void *ud) /* {{{ */
1444 {
1445 read_func_t *rf = e->value;
1446 char *group = ud;
1448 return strcmp(rf->rf_group, (const char *)group);
1449 } /* }}} int compare_read_func_group */
1451 int plugin_unregister_read_group(const char *group) /* {{{ */
1452 {
1453 llentry_t *le;
1454 read_func_t *rf;
1456 int found = 0;
1458 if (group == NULL)
1459 return (-ENOENT);
1461 pthread_mutex_lock(&read_lock);
1463 if (read_list == NULL) {
1464 pthread_mutex_unlock(&read_lock);
1465 return (-ENOENT);
1466 }
1468 while (42) {
1469 le = llist_search_custom(read_list, compare_read_func_group, (void *)group);
1471 if (le == NULL)
1472 break;
1474 ++found;
1476 llist_remove(read_list, le);
1478 rf = le->value;
1479 assert(rf != NULL);
1480 rf->rf_type = RF_REMOVE;
1482 llentry_destroy(le);
1484 DEBUG("plugin_unregister_read_group: "
1485 "Marked `%s' (group `%s') for removal.",
1486 rf->rf_name, group);
1487 }
1489 pthread_mutex_unlock(&read_lock);
1491 if (found == 0) {
1492 WARNING("plugin_unregister_read_group: No such "
1493 "group of read function: %s",
1494 group);
1495 return (-ENOENT);
1496 }
1498 return (0);
1499 } /* }}} int plugin_unregister_read_group */
1501 int plugin_unregister_write(const char *name) {
1502 return (plugin_unregister(list_write, name));
1503 }
1505 int plugin_unregister_flush(const char *name) {
1506 plugin_ctx_t ctx = plugin_get_ctx();
1508 if (ctx.flush_interval != 0) {
1509 char *flush_name;
1511 flush_name = plugin_flush_callback_name(name);
1512 if (flush_name != NULL) {
1513 plugin_unregister_read(flush_name);
1514 sfree(flush_name);
1515 }
1516 }
1518 return plugin_unregister(list_flush, name);
1519 }
1521 int plugin_unregister_missing(const char *name) {
1522 return (plugin_unregister(list_missing, name));
1523 }
1525 int plugin_unregister_shutdown(const char *name) {
1526 return (plugin_unregister(list_shutdown, name));
1527 }
1529 int plugin_unregister_data_set(const char *name) {
1530 data_set_t *ds;
1532 if (data_sets == NULL)
1533 return (-1);
1535 if (c_avl_remove(data_sets, name, NULL, (void *)&ds) != 0)
1536 return (-1);
1538 sfree(ds->ds);
1539 sfree(ds);
1541 return (0);
1542 } /* int plugin_unregister_data_set */
1544 int plugin_unregister_log(const char *name) {
1545 return (plugin_unregister(list_log, name));
1546 }
1548 int plugin_unregister_notification(const char *name) {
1549 return (plugin_unregister(list_notification, name));
1550 }
1552 int plugin_init_all(void) {
1553 char const *chain_name;
1554 llentry_t *le;
1555 int status;
1556 int ret = 0;
1558 /* Init the value cache */
1559 uc_init();
1561 if (IS_TRUE(global_option_get("CollectInternalStats")))
1562 record_statistics = 1;
1564 chain_name = global_option_get("PreCacheChain");
1565 pre_cache_chain = fc_chain_get_by_name(chain_name);
1567 chain_name = global_option_get("PostCacheChain");
1568 post_cache_chain = fc_chain_get_by_name(chain_name);
1570 write_limit_high = global_option_get_long("WriteQueueLimitHigh",
1571 /* default = */ 0);
1572 if (write_limit_high < 0) {
1573 ERROR("WriteQueueLimitHigh must be positive or zero.");
1574 write_limit_high = 0;
1575 }
1577 write_limit_low =
1578 global_option_get_long("WriteQueueLimitLow",
1579 /* default = */ write_limit_high / 2);
1580 if (write_limit_low < 0) {
1581 ERROR("WriteQueueLimitLow must be positive or zero.");
1582 write_limit_low = write_limit_high / 2;
1583 } else if (write_limit_low > write_limit_high) {
1584 ERROR("WriteQueueLimitLow must not be larger than "
1585 "WriteQueueLimitHigh.");
1586 write_limit_low = write_limit_high;
1587 }
1589 write_threads_num = global_option_get_long("WriteThreads",
1590 /* default = */ 5);
1591 if (write_threads_num < 1) {
1592 ERROR("WriteThreads must be positive.");
1593 write_threads_num = 5;
1594 }
1596 if ((list_init == NULL) && (read_heap == NULL))
1597 return ret;
1599 /* Calling all init callbacks before checking if read callbacks
1600 * are available allows the init callbacks to register the read
1601 * callback. */
1602 le = llist_head(list_init);
1603 while (le != NULL) {
1604 callback_func_t *cf;
1605 plugin_init_cb callback;
1606 plugin_ctx_t old_ctx;
1608 cf = le->value;
1609 old_ctx = plugin_set_ctx(cf->cf_ctx);
1610 callback = cf->cf_callback;
1611 status = (*callback)();
1612 plugin_set_ctx(old_ctx);
1614 if (status != 0) {
1615 ERROR("Initialization of plugin `%s' "
1616 "failed with status %i. "
1617 "Plugin will be unloaded.",
1618 le->key, status);
1619 /* Plugins that register read callbacks from the init
1620 * callback should take care of appropriate error
1621 * handling themselves. */
1622 /* FIXME: Unload _all_ functions */
1623 plugin_unregister_read(le->key);
1624 ret = -1;
1625 }
1627 le = le->next;
1628 }
1630 start_write_threads((size_t)write_threads_num);
1632 max_read_interval =
1633 global_option_get_time("MaxReadInterval", DEFAULT_MAX_READ_INTERVAL);
1635 /* Start read-threads */
1636 if (read_heap != NULL) {
1637 const char *rt;
1638 int num;
1640 rt = global_option_get("ReadThreads");
1641 num = atoi(rt);
1642 if (num != -1)
1643 start_read_threads((num > 0) ? ((size_t)num) : 5);
1644 }
1645 return ret;
1646 } /* void plugin_init_all */
1648 /* TODO: Rename this function. */
1649 void plugin_read_all(void) {
1650 if (record_statistics) {
1651 plugin_update_internal_statistics();
1652 }
1653 uc_check_timeout();
1655 return;
1656 } /* void plugin_read_all */
1658 /* Read function called when the `-T' command line argument is given. */
1659 int plugin_read_all_once(void) {
1660 int status;
1661 int return_status = 0;
1663 if (read_heap == NULL) {
1664 NOTICE("No read-functions are registered.");
1665 return (0);
1666 }
1668 while (42) {
1669 read_func_t *rf;
1670 plugin_ctx_t old_ctx;
1672 rf = c_heap_get_root(read_heap);
1673 if (rf == NULL)
1674 break;
1676 old_ctx = plugin_set_ctx(rf->rf_ctx);
1678 if (rf->rf_type == RF_SIMPLE) {
1679 int (*callback)(void);
1681 callback = rf->rf_callback;
1682 status = (*callback)();
1683 } else {
1684 plugin_read_cb callback;
1686 callback = rf->rf_callback;
1687 status = (*callback)(&rf->rf_udata);
1688 }
1690 plugin_set_ctx(old_ctx);
1692 if (status != 0) {
1693 NOTICE("read-function of plugin `%s' failed.", rf->rf_name);
1694 return_status = -1;
1695 }
1697 sfree(rf->rf_name);
1698 destroy_callback((void *)rf);
1699 }
1701 return (return_status);
1702 } /* int plugin_read_all_once */
1704 int plugin_write(const char *plugin, /* {{{ */
1705 const data_set_t *ds, const value_list_t *vl) {
1706 llentry_t *le;
1707 int status;
1709 if (vl == NULL)
1710 return (EINVAL);
1712 if (list_write == NULL)
1713 return (ENOENT);
1715 if (ds == NULL) {
1716 ds = plugin_get_ds(vl->type);
1717 if (ds == NULL) {
1718 ERROR("plugin_write: Unable to lookup type `%s'.", vl->type);
1719 return (ENOENT);
1720 }
1721 }
1723 if (plugin == NULL) {
1724 int success = 0;
1725 int failure = 0;
1727 le = llist_head(list_write);
1728 while (le != NULL) {
1729 callback_func_t *cf = le->value;
1730 plugin_write_cb callback;
1732 /* do not switch plugin context; rather keep the context (interval)
1733 * information of the calling read plugin */
1735 DEBUG("plugin: plugin_write: Writing values via %s.", le->key);
1736 callback = cf->cf_callback;
1737 status = (*callback)(ds, vl, &cf->cf_udata);
1738 if (status != 0)
1739 failure++;
1740 else
1741 success++;
1743 le = le->next;
1744 }
1746 if ((success == 0) && (failure != 0))
1747 status = -1;
1748 else
1749 status = 0;
1750 } else /* plugin != NULL */
1751 {
1752 callback_func_t *cf;
1753 plugin_write_cb callback;
1755 le = llist_head(list_write);
1756 while (le != NULL) {
1757 if (strcasecmp(plugin, le->key) == 0)
1758 break;
1760 le = le->next;
1761 }
1763 if (le == NULL)
1764 return (ENOENT);
1766 cf = le->value;
1768 /* do not switch plugin context; rather keep the context (interval)
1769 * information of the calling read plugin */
1771 DEBUG("plugin: plugin_write: Writing values via %s.", le->key);
1772 callback = cf->cf_callback;
1773 status = (*callback)(ds, vl, &cf->cf_udata);
1774 }
1776 return (status);
1777 } /* }}} int plugin_write */
1779 int plugin_flush(const char *plugin, cdtime_t timeout, const char *identifier) {
1780 llentry_t *le;
1782 if (list_flush == NULL)
1783 return (0);
1785 le = llist_head(list_flush);
1786 while (le != NULL) {
1787 callback_func_t *cf;
1788 plugin_flush_cb callback;
1789 plugin_ctx_t old_ctx;
1791 if ((plugin != NULL) && (strcmp(plugin, le->key) != 0)) {
1792 le = le->next;
1793 continue;
1794 }
1796 cf = le->value;
1797 old_ctx = plugin_set_ctx(cf->cf_ctx);
1798 callback = cf->cf_callback;
1800 (*callback)(timeout, identifier, &cf->cf_udata);
1802 plugin_set_ctx(old_ctx);
1804 le = le->next;
1805 }
1806 return (0);
1807 } /* int plugin_flush */
1809 int plugin_shutdown_all(void) {
1810 llentry_t *le;
1811 int ret = 0; // Assume success.
1813 destroy_all_callbacks(&list_init);
1815 stop_read_threads();
1817 pthread_mutex_lock(&read_lock);
1818 llist_destroy(read_list);
1819 read_list = NULL;
1820 pthread_mutex_unlock(&read_lock);
1822 destroy_read_heap();
1824 /* blocks until all write threads have shut down. */
1825 stop_write_threads();
1827 /* ask all plugins to write out the state they kept. */
1828 plugin_flush(/* plugin = */ NULL,
1829 /* timeout = */ 0,
1830 /* identifier = */ NULL);
1832 le = NULL;
1833 if (list_shutdown != NULL)
1834 le = llist_head(list_shutdown);
1836 while (le != NULL) {
1837 callback_func_t *cf;
1838 plugin_shutdown_cb callback;
1839 plugin_ctx_t old_ctx;
1841 cf = le->value;
1842 old_ctx = plugin_set_ctx(cf->cf_ctx);
1843 callback = cf->cf_callback;
1845 /* Advance the pointer before calling the callback allows
1846 * shutdown functions to unregister themselves. If done the
1847 * other way around the memory `le' points to will be freed
1848 * after callback returns. */
1849 le = le->next;
1851 if ((*callback)() != 0)
1852 ret = -1;
1854 plugin_set_ctx(old_ctx);
1855 }
1857 /* Write plugins which use the `user_data' pointer usually need the
1858 * same data available to the flush callback. If this is the case, set
1859 * the free_function to NULL when registering the flush callback and to
1860 * the real free function when registering the write callback. This way
1861 * the data isn't freed twice. */
1862 destroy_all_callbacks(&list_flush);
1863 destroy_all_callbacks(&list_missing);
1864 destroy_all_callbacks(&list_write);
1866 destroy_all_callbacks(&list_notification);
1867 destroy_all_callbacks(&list_shutdown);
1868 destroy_all_callbacks(&list_log);
1870 plugin_free_loaded();
1871 plugin_free_data_sets();
1872 return (ret);
1873 } /* void plugin_shutdown_all */
1875 int plugin_dispatch_missing(const value_list_t *vl) /* {{{ */
1876 {
1877 llentry_t *le;
1879 if (list_missing == NULL)
1880 return (0);
1882 le = llist_head(list_missing);
1883 while (le != NULL) {
1884 callback_func_t *cf;
1885 plugin_missing_cb callback;
1886 plugin_ctx_t old_ctx;
1887 int status;
1889 cf = le->value;
1890 old_ctx = plugin_set_ctx(cf->cf_ctx);
1891 callback = cf->cf_callback;
1893 status = (*callback)(vl, &cf->cf_udata);
1894 plugin_set_ctx(old_ctx);
1895 if (status != 0) {
1896 if (status < 0) {
1897 ERROR("plugin_dispatch_missing: Callback function \"%s\" "
1898 "failed with status %i.",
1899 le->key, status);
1900 return (status);
1901 } else {
1902 return (0);
1903 }
1904 }
1906 le = le->next;
1907 }
1908 return (0);
1909 } /* int }}} plugin_dispatch_missing */
1911 static int plugin_dispatch_values_internal(value_list_t *vl) {
1912 int status;
1913 static c_complain_t no_write_complaint = C_COMPLAIN_INIT_STATIC;
1915 data_set_t *ds;
1917 _Bool free_meta_data = 0;
1919 assert(vl != NULL);
1921 /* These fields are initialized by plugin_value_list_clone() if needed: */
1922 assert(vl->host[0] != 0);
1923 assert(vl->time != 0); /* The time is determined at _enqueue_ time. */
1924 assert(vl->interval != 0);
1926 if (vl->type[0] == 0 || vl->values == NULL || vl->values_len < 1) {
1927 ERROR("plugin_dispatch_values: Invalid value list "
1928 "from plugin %s.",
1929 vl->plugin);
1930 return (-1);
1931 }
1933 /* Free meta data only if the calling function didn't specify any. In
1934 * this case matches and targets may add some and the calling function
1935 * may not expect (and therefore free) that data. */
1936 if (vl->meta == NULL)
1937 free_meta_data = 1;
1939 if (list_write == NULL)
1940 c_complain_once(LOG_WARNING, &no_write_complaint,
1941 "plugin_dispatch_values: No write callback has been "
1942 "registered. Please load at least one output plugin, "
1943 "if you want the collected data to be stored.");
1945 if (data_sets == NULL) {
1946 ERROR("plugin_dispatch_values: No data sets registered. "
1947 "Could the types database be read? Check "
1948 "your `TypesDB' setting!");
1949 return (-1);
1950 }
1952 if (c_avl_get(data_sets, vl->type, (void *)&ds) != 0) {
1953 char ident[6 * DATA_MAX_NAME_LEN];
1955 FORMAT_VL(ident, sizeof(ident), vl);
1956 INFO("plugin_dispatch_values: Dataset not found: %s "
1957 "(from \"%s\"), check your types.db!",
1958 vl->type, ident);
1959 return (-1);
1960 }
1962 DEBUG("plugin_dispatch_values: time = %.3f; interval = %.3f; "
1963 "host = %s; "
1964 "plugin = %s; plugin_instance = %s; "
1965 "type = %s; type_instance = %s;",
1966 CDTIME_T_TO_DOUBLE(vl->time), CDTIME_T_TO_DOUBLE(vl->interval),
1967 vl->host, vl->plugin, vl->plugin_instance, vl->type, vl->type_instance);
1969 #if COLLECT_DEBUG
1970 assert(0 == strcmp(ds->type, vl->type));
1971 #else
1972 if (0 != strcmp(ds->type, vl->type))
1973 WARNING("plugin_dispatch_values: (ds->type = %s) != (vl->type = %s)",
1974 ds->type, vl->type);
1975 #endif
1977 #if COLLECT_DEBUG
1978 assert(ds->ds_num == vl->values_len);
1979 #else
1980 if (ds->ds_num != vl->values_len) {
1981 ERROR("plugin_dispatch_values: ds->type = %s: "
1982 "(ds->ds_num = %zu) != "
1983 "(vl->values_len = %zu)",
1984 ds->type, ds->ds_num, vl->values_len);
1985 return (-1);
1986 }
1987 #endif
1989 escape_slashes(vl->host, sizeof(vl->host));
1990 escape_slashes(vl->plugin, sizeof(vl->plugin));
1991 escape_slashes(vl->plugin_instance, sizeof(vl->plugin_instance));
1992 escape_slashes(vl->type, sizeof(vl->type));
1993 escape_slashes(vl->type_instance, sizeof(vl->type_instance));
1995 if (pre_cache_chain != NULL) {
1996 status = fc_process_chain(ds, vl, pre_cache_chain);
1997 if (status < 0) {
1998 WARNING("plugin_dispatch_values: Running the "
1999 "pre-cache chain failed with "
2000 "status %i (%#x).",
2001 status, status);
2002 } else if (status == FC_TARGET_STOP)
2003 return (0);
2004 }
2006 /* Update the value cache */
2007 uc_update(ds, vl);
2009 if (post_cache_chain != NULL) {
2010 status = fc_process_chain(ds, vl, post_cache_chain);
2011 if (status < 0) {
2012 WARNING("plugin_dispatch_values: Running the "
2013 "post-cache chain failed with "
2014 "status %i (%#x).",
2015 status, status);
2016 }
2017 } else
2018 fc_default_action(ds, vl);
2020 if ((free_meta_data != 0) && (vl->meta != NULL)) {
2021 meta_data_destroy(vl->meta);
2022 vl->meta = NULL;
2023 }
2025 return (0);
2026 } /* int plugin_dispatch_values_internal */
2028 static double get_drop_probability(void) /* {{{ */
2029 {
2030 long pos;
2031 long size;
2032 long wql;
2034 pthread_mutex_lock(&write_lock);
2035 wql = write_queue_length;
2036 pthread_mutex_unlock(&write_lock);
2038 if (wql < write_limit_low)
2039 return (0.0);
2040 if (wql >= write_limit_high)
2041 return (1.0);
2043 pos = 1 + wql - write_limit_low;
2044 size = 1 + write_limit_high - write_limit_low;
2046 return (((double)pos) / ((double)size));
2047 } /* }}} double get_drop_probability */
2049 static _Bool check_drop_value(void) /* {{{ */
2050 {
2051 static cdtime_t last_message_time = 0;
2052 static pthread_mutex_t last_message_lock = PTHREAD_MUTEX_INITIALIZER;
2054 double p;
2055 double q;
2056 int status;
2058 if (write_limit_high == 0)
2059 return (0);
2061 p = get_drop_probability();
2062 if (p == 0.0)
2063 return (0);
2065 status = pthread_mutex_trylock(&last_message_lock);
2066 if (status == 0) {
2067 cdtime_t now;
2069 now = cdtime();
2070 if ((now - last_message_time) > TIME_T_TO_CDTIME_T(1)) {
2071 last_message_time = now;
2072 ERROR("plugin_dispatch_values: Low water mark "
2073 "reached. Dropping %.0f%% of metrics.",
2074 100.0 * p);
2075 }
2076 pthread_mutex_unlock(&last_message_lock);
2077 }
2079 if (p == 1.0)
2080 return (1);
2082 q = cdrand_d();
2083 if (q > p)
2084 return (1);
2085 else
2086 return (0);
2087 } /* }}} _Bool check_drop_value */
2089 int plugin_dispatch_values(value_list_t const *vl) {
2090 int status;
2091 static pthread_mutex_t statistics_lock = PTHREAD_MUTEX_INITIALIZER;
2093 if (check_drop_value()) {
2094 if (record_statistics) {
2095 pthread_mutex_lock(&statistics_lock);
2096 stats_values_dropped++;
2097 pthread_mutex_unlock(&statistics_lock);
2098 }
2099 return (0);
2100 }
2102 status = plugin_write_enqueue(vl);
2103 if (status != 0) {
2104 char errbuf[1024];
2105 ERROR("plugin_dispatch_values: plugin_write_enqueue failed "
2106 "with status %i (%s).",
2107 status, sstrerror(status, errbuf, sizeof(errbuf)));
2108 return (status);
2109 }
2111 return (0);
2112 }
2114 __attribute__((sentinel)) int
2115 plugin_dispatch_multivalue(value_list_t const *template, /* {{{ */
2116 _Bool store_percentage, int store_type, ...) {
2117 value_list_t *vl;
2118 int failed = 0;
2119 gauge_t sum = 0.0;
2120 va_list ap;
2122 assert(template->values_len == 1);
2124 /* Calculate sum for Gauge to calculate percent if needed */
2125 if (DS_TYPE_GAUGE == store_type) {
2126 va_start(ap, store_type);
2127 while (42) {
2128 char const *name;
2129 gauge_t value;
2131 name = va_arg(ap, char const *);
2132 if (name == NULL)
2133 break;
2135 value = va_arg(ap, gauge_t);
2136 if (!isnan(value))
2137 sum += value;
2138 }
2139 va_end(ap);
2140 }
2142 vl = plugin_value_list_clone(template);
2143 /* plugin_value_list_clone makes sure vl->time is set to non-zero. */
2144 if (store_percentage)
2145 sstrncpy(vl->type, "percent", sizeof(vl->type));
2147 va_start(ap, store_type);
2148 while (42) {
2149 char const *name;
2150 int status;
2152 /* Set the type instance. */
2153 name = va_arg(ap, char const *);
2154 if (name == NULL)
2155 break;
2156 sstrncpy(vl->type_instance, name, sizeof(vl->type_instance));
2158 /* Set the value. */
2159 switch (store_type) {
2160 case DS_TYPE_GAUGE:
2161 vl->values[0].gauge = va_arg(ap, gauge_t);
2162 if (store_percentage)
2163 vl->values[0].gauge *= sum ? (100.0 / sum) : NAN;
2164 break;
2165 case DS_TYPE_ABSOLUTE:
2166 vl->values[0].absolute = va_arg(ap, absolute_t);
2167 break;
2168 case DS_TYPE_COUNTER:
2169 vl->values[0].counter = va_arg(ap, counter_t);
2170 break;
2171 case DS_TYPE_DERIVE:
2172 vl->values[0].derive = va_arg(ap, derive_t);
2173 break;
2174 default:
2175 ERROR("plugin_dispatch_multivalue: given store_type is incorrect.");
2176 failed++;
2177 }
2179 status = plugin_write_enqueue(vl);
2180 if (status != 0)
2181 failed++;
2182 }
2183 va_end(ap);
2185 plugin_value_list_free(vl);
2186 return (failed);
2187 } /* }}} int plugin_dispatch_multivalue */
2189 int plugin_dispatch_notification(const notification_t *notif) {
2190 llentry_t *le;
2191 /* Possible TODO: Add flap detection here */
2193 DEBUG("plugin_dispatch_notification: severity = %i; message = %s; "
2194 "time = %.3f; host = %s;",
2195 notif->severity, notif->message, CDTIME_T_TO_DOUBLE(notif->time),
2196 notif->host);
2198 /* Nobody cares for notifications */
2199 if (list_notification == NULL)
2200 return (-1);
2202 le = llist_head(list_notification);
2203 while (le != NULL) {
2204 callback_func_t *cf;
2205 plugin_notification_cb callback;
2206 int status;
2208 /* do not switch plugin context; rather keep the context
2209 * (interval) information of the calling plugin */
2211 cf = le->value;
2212 callback = cf->cf_callback;
2213 status = (*callback)(notif, &cf->cf_udata);
2214 if (status != 0) {
2215 WARNING("plugin_dispatch_notification: Notification "
2216 "callback %s returned %i.",
2217 le->key, status);
2218 }
2220 le = le->next;
2221 }
2223 return (0);
2224 } /* int plugin_dispatch_notification */
2226 void plugin_log(int level, const char *format, ...) {
2227 char msg[1024];
2228 va_list ap;
2229 llentry_t *le;
2231 #if !COLLECT_DEBUG
2232 if (level >= LOG_DEBUG)
2233 return;
2234 #endif
2236 va_start(ap, format);
2237 vsnprintf(msg, sizeof(msg), format, ap);
2238 msg[sizeof(msg) - 1] = '\0';
2239 va_end(ap);
2241 if (list_log == NULL) {
2242 fprintf(stderr, "%s\n", msg);
2243 return;
2244 }
2246 le = llist_head(list_log);
2247 while (le != NULL) {
2248 callback_func_t *cf;
2249 plugin_log_cb callback;
2251 cf = le->value;
2252 callback = cf->cf_callback;
2254 /* do not switch plugin context; rather keep the context
2255 * (interval) information of the calling plugin */
2257 (*callback)(level, msg, &cf->cf_udata);
2259 le = le->next;
2260 }
2261 } /* void plugin_log */
2263 int parse_log_severity(const char *severity) {
2264 int log_level = -1;
2266 if ((0 == strcasecmp(severity, "emerg")) ||
2267 (0 == strcasecmp(severity, "alert")) ||
2268 (0 == strcasecmp(severity, "crit")) || (0 == strcasecmp(severity, "err")))
2269 log_level = LOG_ERR;
2270 else if (0 == strcasecmp(severity, "warning"))
2271 log_level = LOG_WARNING;
2272 else if (0 == strcasecmp(severity, "notice"))
2273 log_level = LOG_NOTICE;
2274 else if (0 == strcasecmp(severity, "info"))
2275 log_level = LOG_INFO;
2276 #if COLLECT_DEBUG
2277 else if (0 == strcasecmp(severity, "debug"))
2278 log_level = LOG_DEBUG;
2279 #endif /* COLLECT_DEBUG */
2281 return (log_level);
2282 } /* int parse_log_severity */
2284 int parse_notif_severity(const char *severity) {
2285 int notif_severity = -1;
2287 if (strcasecmp(severity, "FAILURE") == 0)
2288 notif_severity = NOTIF_FAILURE;
2289 else if (strcmp(severity, "OKAY") == 0)
2290 notif_severity = NOTIF_OKAY;
2291 else if ((strcmp(severity, "WARNING") == 0) ||
2292 (strcmp(severity, "WARN") == 0))
2293 notif_severity = NOTIF_WARNING;
2295 return (notif_severity);
2296 } /* int parse_notif_severity */
2298 const data_set_t *plugin_get_ds(const char *name) {
2299 data_set_t *ds;
2301 if (data_sets == NULL) {
2302 ERROR("plugin_get_ds: No data sets are defined yet.");
2303 return (NULL);
2304 }
2306 if (c_avl_get(data_sets, name, (void *)&ds) != 0) {
2307 DEBUG("No such dataset registered: %s", name);
2308 return (NULL);
2309 }
2311 return (ds);
2312 } /* data_set_t *plugin_get_ds */
2314 static int plugin_notification_meta_add(notification_t *n, const char *name,
2315 enum notification_meta_type_e type,
2316 const void *value) {
2317 notification_meta_t *meta;
2318 notification_meta_t *tail;
2320 if ((n == NULL) || (name == NULL) || (value == NULL)) {
2321 ERROR("plugin_notification_meta_add: A pointer is NULL!");
2322 return (-1);
2323 }
2325 meta = calloc(1, sizeof(*meta));
2326 if (meta == NULL) {
2327 ERROR("plugin_notification_meta_add: calloc failed.");
2328 return (-1);
2329 }
2331 sstrncpy(meta->name, name, sizeof(meta->name));
2332 meta->type = type;
2334 switch (type) {
2335 case NM_TYPE_STRING: {
2336 meta->nm_value.nm_string = strdup((const char *)value);
2337 if (meta->nm_value.nm_string == NULL) {
2338 ERROR("plugin_notification_meta_add: strdup failed.");
2339 sfree(meta);
2340 return (-1);
2341 }
2342 break;
2343 }
2344 case NM_TYPE_SIGNED_INT: {
2345 meta->nm_value.nm_signed_int = *((int64_t *)value);
2346 break;
2347 }
2348 case NM_TYPE_UNSIGNED_INT: {
2349 meta->nm_value.nm_unsigned_int = *((uint64_t *)value);
2350 break;
2351 }
2352 case NM_TYPE_DOUBLE: {
2353 meta->nm_value.nm_double = *((double *)value);
2354 break;
2355 }
2356 case NM_TYPE_BOOLEAN: {
2357 meta->nm_value.nm_boolean = *((_Bool *)value);
2358 break;
2359 }
2360 default: {
2361 ERROR("plugin_notification_meta_add: Unknown type: %i", type);
2362 sfree(meta);
2363 return (-1);
2364 }
2365 } /* switch (type) */
2367 meta->next = NULL;
2368 tail = n->meta;
2369 while ((tail != NULL) && (tail->next != NULL))
2370 tail = tail->next;
2372 if (tail == NULL)
2373 n->meta = meta;
2374 else
2375 tail->next = meta;
2377 return (0);
2378 } /* int plugin_notification_meta_add */
2380 int plugin_notification_meta_add_string(notification_t *n, const char *name,
2381 const char *value) {
2382 return (plugin_notification_meta_add(n, name, NM_TYPE_STRING, value));
2383 }
2385 int plugin_notification_meta_add_signed_int(notification_t *n, const char *name,
2386 int64_t value) {
2387 return (plugin_notification_meta_add(n, name, NM_TYPE_SIGNED_INT, &value));
2388 }
2390 int plugin_notification_meta_add_unsigned_int(notification_t *n,
2391 const char *name,
2392 uint64_t value) {
2393 return (plugin_notification_meta_add(n, name, NM_TYPE_UNSIGNED_INT, &value));
2394 }
2396 int plugin_notification_meta_add_double(notification_t *n, const char *name,
2397 double value) {
2398 return (plugin_notification_meta_add(n, name, NM_TYPE_DOUBLE, &value));
2399 }
2401 int plugin_notification_meta_add_boolean(notification_t *n, const char *name,
2402 _Bool value) {
2403 return (plugin_notification_meta_add(n, name, NM_TYPE_BOOLEAN, &value));
2404 }
2406 int plugin_notification_meta_copy(notification_t *dst,
2407 const notification_t *src) {
2408 assert(dst != NULL);
2409 assert(src != NULL);
2410 assert(dst != src);
2411 assert((src->meta == NULL) || (src->meta != dst->meta));
2413 for (notification_meta_t *meta = src->meta; meta != NULL; meta = meta->next) {
2414 if (meta->type == NM_TYPE_STRING)
2415 plugin_notification_meta_add_string(dst, meta->name,
2416 meta->nm_value.nm_string);
2417 else if (meta->type == NM_TYPE_SIGNED_INT)
2418 plugin_notification_meta_add_signed_int(dst, meta->name,
2419 meta->nm_value.nm_signed_int);
2420 else if (meta->type == NM_TYPE_UNSIGNED_INT)
2421 plugin_notification_meta_add_unsigned_int(dst, meta->name,
2422 meta->nm_value.nm_unsigned_int);
2423 else if (meta->type == NM_TYPE_DOUBLE)
2424 plugin_notification_meta_add_double(dst, meta->name,
2425 meta->nm_value.nm_double);
2426 else if (meta->type == NM_TYPE_BOOLEAN)
2427 plugin_notification_meta_add_boolean(dst, meta->name,
2428 meta->nm_value.nm_boolean);
2429 }
2431 return (0);
2432 } /* int plugin_notification_meta_copy */
2434 int plugin_notification_meta_free(notification_meta_t *n) {
2435 notification_meta_t *this;
2436 notification_meta_t *next;
2438 if (n == NULL) {
2439 ERROR("plugin_notification_meta_free: n == NULL!");
2440 return (-1);
2441 }
2443 this = n;
2444 while (this != NULL) {
2445 next = this->next;
2447 if (this->type == NM_TYPE_STRING) {
2448 /* Assign to a temporary variable to work around nm_string's const
2449 * modifier. */
2450 void *tmp = (void *)this->nm_value.nm_string;
2452 sfree(tmp);
2453 this->nm_value.nm_string = NULL;
2454 }
2455 sfree(this);
2457 this = next;
2458 }
2460 return (0);
2461 } /* int plugin_notification_meta_free */
2463 static void plugin_ctx_destructor(void *ctx) {
2464 sfree(ctx);
2465 } /* void plugin_ctx_destructor */
2467 static plugin_ctx_t ctx_init = {/* interval = */ 0};
2469 static plugin_ctx_t *plugin_ctx_create(void) {
2470 plugin_ctx_t *ctx;
2472 ctx = malloc(sizeof(*ctx));
2473 if (ctx == NULL) {
2474 char errbuf[1024];
2475 ERROR("Failed to allocate plugin context: %s",
2476 sstrerror(errno, errbuf, sizeof(errbuf)));
2477 return NULL;
2478 }
2480 *ctx = ctx_init;
2481 assert(plugin_ctx_key_initialized);
2482 pthread_setspecific(plugin_ctx_key, ctx);
2483 DEBUG("Created new plugin context.");
2484 return (ctx);
2485 } /* int plugin_ctx_create */
2487 void plugin_init_ctx(void) {
2488 pthread_key_create(&plugin_ctx_key, plugin_ctx_destructor);
2489 plugin_ctx_key_initialized = 1;
2490 } /* void plugin_init_ctx */
2492 plugin_ctx_t plugin_get_ctx(void) {
2493 plugin_ctx_t *ctx;
2495 assert(plugin_ctx_key_initialized);
2496 ctx = pthread_getspecific(plugin_ctx_key);
2498 if (ctx == NULL) {
2499 ctx = plugin_ctx_create();
2500 /* this must no happen -- exit() instead? */
2501 if (ctx == NULL)
2502 return ctx_init;
2503 }
2505 return (*ctx);
2506 } /* plugin_ctx_t plugin_get_ctx */
2508 plugin_ctx_t plugin_set_ctx(plugin_ctx_t ctx) {
2509 plugin_ctx_t *c;
2510 plugin_ctx_t old;
2512 assert(plugin_ctx_key_initialized);
2513 c = pthread_getspecific(plugin_ctx_key);
2515 if (c == NULL) {
2516 c = plugin_ctx_create();
2517 /* this must no happen -- exit() instead? */
2518 if (c == NULL)
2519 return ctx_init;
2520 }
2522 old = *c;
2523 *c = ctx;
2525 return (old);
2526 } /* void plugin_set_ctx */
2528 cdtime_t plugin_get_interval(void) {
2529 cdtime_t interval;
2531 interval = plugin_get_ctx().interval;
2532 if (interval > 0)
2533 return interval;
2535 return cf_get_default_interval();
2536 } /* cdtime_t plugin_get_interval */
2538 typedef struct {
2539 plugin_ctx_t ctx;
2540 void *(*start_routine)(void *);
2541 void *arg;
2542 } plugin_thread_t;
2544 static void *plugin_thread_start(void *arg) {
2545 plugin_thread_t *plugin_thread = arg;
2547 void *(*start_routine)(void *) = plugin_thread->start_routine;
2548 void *plugin_arg = plugin_thread->arg;
2550 plugin_set_ctx(plugin_thread->ctx);
2552 sfree(plugin_thread);
2554 return start_routine(plugin_arg);
2555 } /* void *plugin_thread_start */
2557 int plugin_thread_create(pthread_t *thread, const pthread_attr_t *attr,
2558 void *(*start_routine)(void *), void *arg,
2559 char const *name) {
2560 plugin_thread_t *plugin_thread;
2562 plugin_thread = malloc(sizeof(*plugin_thread));
2563 if (plugin_thread == NULL)
2564 return ENOMEM;
2566 plugin_thread->ctx = plugin_get_ctx();
2567 plugin_thread->start_routine = start_routine;
2568 plugin_thread->arg = arg;
2570 int ret = pthread_create(thread, attr, plugin_thread_start, plugin_thread);
2571 if (ret != 0) {
2572 sfree(plugin_thread);
2573 return ret;
2574 }
2576 if (name != NULL)
2577 set_thread_name(*thread, name);
2579 return 0;
2580 } /* int plugin_thread_create */
2582 /* vim: set sw=8 ts=8 noet fdm=marker : */