Add support to set the thread name.
[collectd.git] / src / daemon / plugin.c
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  **/
27
28 #define _GNU_SOURCE 
29 #include "collectd.h"
30
31 #include "common.h"
32 #include "plugin.h"
33 #include "configfile.h"
34 #include "filter_chain.h"
35 #include "utils_avltree.h"
36 #include "utils_cache.h"
37 #include "utils_complain.h"
38 #include "utils_llist.h"
39 #include "utils_heap.h"
40 #include "utils_time.h"
41 #include "utils_random.h"
42
43 #include <ltdl.h>
44
45 /*
46  * Private structures
47  */
48 struct callback_func_s
49 {
50         void *cf_callback;
51         user_data_t cf_udata;
52         plugin_ctx_t cf_ctx;
53 };
54 typedef struct callback_func_s callback_func_t;
55
56 #define RF_SIMPLE  0
57 #define RF_COMPLEX 1
58 #define RF_REMOVE  65535
59 struct read_func_s
60 {
61         /* `read_func_t' "inherits" from `callback_func_t'.
62          * The `rf_super' member MUST be the first one in this structure! */
63 #define rf_callback rf_super.cf_callback
64 #define rf_udata rf_super.cf_udata
65 #define rf_ctx rf_super.cf_ctx
66         callback_func_t rf_super;
67         char rf_group[DATA_MAX_NAME_LEN];
68         char *rf_name;
69         int rf_type;
70         cdtime_t rf_interval;
71         cdtime_t rf_effective_interval;
72         cdtime_t rf_next_read;
73 };
74 typedef struct read_func_s read_func_t;
75
76 struct write_queue_s;
77 typedef struct write_queue_s write_queue_t;
78 struct write_queue_s
79 {
80         value_list_t *vl;
81         plugin_ctx_t ctx;
82         write_queue_t *next;
83 };
84
85 struct flush_callback_s {
86         char *name;
87         cdtime_t timeout;
88 };
89 typedef struct flush_callback_s flush_callback_t;
90
91 /*
92  * Private variables
93  */
94 static c_avl_tree_t *plugins_loaded = NULL;
95
96 static llist_t *list_init;
97 static llist_t *list_write;
98 static llist_t *list_flush;
99 static llist_t *list_missing;
100 static llist_t *list_shutdown;
101 static llist_t *list_log;
102 static llist_t *list_notification;
103
104 static fc_chain_t *pre_cache_chain = NULL;
105 static fc_chain_t *post_cache_chain = NULL;
106
107 static c_avl_tree_t *data_sets;
108
109 static char *plugindir = NULL;
110
111 #ifndef DEFAULT_MAX_READ_INTERVAL
112 # define DEFAULT_MAX_READ_INTERVAL TIME_T_TO_CDTIME_T_STATIC (86400)
113 #endif
114 static c_heap_t       *read_heap = NULL;
115 static llist_t        *read_list;
116 static int             read_loop = 1;
117 static pthread_mutex_t read_lock = PTHREAD_MUTEX_INITIALIZER;
118 static pthread_cond_t  read_cond = PTHREAD_COND_INITIALIZER;
119 static pthread_t      *read_threads = NULL;
120 static int             read_threads_num = 0;
121 static cdtime_t        max_read_interval = DEFAULT_MAX_READ_INTERVAL;
122
123 static write_queue_t  *write_queue_head;
124 static write_queue_t  *write_queue_tail;
125 static long            write_queue_length = 0;
126 static _Bool           write_loop = 1;
127 static pthread_mutex_t write_lock = PTHREAD_MUTEX_INITIALIZER;
128 static pthread_cond_t  write_cond = PTHREAD_COND_INITIALIZER;
129 static pthread_t      *write_threads = NULL;
130 static size_t          write_threads_num = 0;
131
132 static pthread_key_t   plugin_ctx_key;
133 static _Bool           plugin_ctx_key_initialized = 0;
134
135 static long            write_limit_high = 0;
136 static long            write_limit_low = 0;
137
138 static derive_t        stats_values_dropped = 0;
139 static _Bool           record_statistics = 0;
140
141 /*
142  * Static functions
143  */
144 static int plugin_dispatch_values_internal (value_list_t *vl);
145
146 static const char *plugin_get_dir (void)
147 {
148         if (plugindir == NULL)
149                 return (PLUGINDIR);
150         else
151                 return (plugindir);
152 }
153
154 static void plugin_update_internal_statistics (void) { /* {{{ */
155
156         gauge_t copy_write_queue_length = (gauge_t) write_queue_length;
157
158         /* Initialize `vl' */
159         value_list_t vl = VALUE_LIST_INIT;
160         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
161         sstrncpy (vl.plugin, "collectd", sizeof (vl.plugin));
162
163         /* Write queue */
164         sstrncpy (vl.plugin_instance, "write_queue",
165                         sizeof (vl.plugin_instance));
166
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);
173
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);
180
181         /* Cache */
182         sstrncpy (vl.plugin_instance, "cache",
183                         sizeof (vl.plugin_instance));
184
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);
191
192         return;
193 } /* }}} void plugin_update_internal_statistics */
194
195 static void destroy_callback (callback_func_t *cf) /* {{{ */
196 {
197         if (cf == NULL)
198                 return;
199
200         if ((cf->cf_udata.data != NULL) && (cf->cf_udata.free_func != NULL))
201         {
202                 cf->cf_udata.free_func (cf->cf_udata.data);
203                 cf->cf_udata.data = NULL;
204                 cf->cf_udata.free_func = NULL;
205         }
206         sfree (cf);
207 } /* }}} void destroy_callback */
208
209 static void destroy_all_callbacks (llist_t **list) /* {{{ */
210 {
211         llentry_t *le;
212
213         if (*list == NULL)
214                 return;
215
216         le = llist_head (*list);
217         while (le != NULL)
218         {
219                 llentry_t *le_next;
220
221                 le_next = le->next;
222
223                 sfree (le->key);
224                 destroy_callback (le->value);
225                 le->value = NULL;
226
227                 le = le_next;
228         }
229
230         llist_destroy (*list);
231         *list = NULL;
232 } /* }}} void destroy_all_callbacks */
233
234 static void destroy_read_heap (void) /* {{{ */
235 {
236         if (read_heap == NULL)
237                 return;
238
239         while (42)
240         {
241                 read_func_t *rf;
242
243                 rf = c_heap_get_root (read_heap);
244                 if (rf == NULL)
245                         break;
246                 sfree (rf->rf_name);
247                 destroy_callback ((callback_func_t *) rf);
248         }
249
250         c_heap_destroy (read_heap);
251         read_heap = NULL;
252 } /* }}} void destroy_read_heap */
253
254 static int register_callback (llist_t **list, /* {{{ */
255                 const char *name, callback_func_t *cf)
256 {
257         llentry_t *le;
258         char *key;
259
260         if (*list == NULL)
261         {
262                 *list = llist_create ();
263                 if (*list == NULL)
264                 {
265                         ERROR ("plugin: register_callback: "
266                                         "llist_create failed.");
267                         destroy_callback (cf);
268                         return (-1);
269                 }
270         }
271
272         key = strdup (name);
273         if (key == NULL)
274         {
275                 ERROR ("plugin: register_callback: strdup failed.");
276                 destroy_callback (cf);
277                 return (-1);
278         }
279
280         le = llist_search (*list, name);
281         if (le == NULL)
282         {
283                 le = llentry_create (key, cf);
284                 if (le == NULL)
285                 {
286                         ERROR ("plugin: register_callback: "
287                                         "llentry_create failed.");
288                         sfree (key);
289                         destroy_callback (cf);
290                         return (-1);
291                 }
292
293                 llist_append (*list, le);
294         }
295         else
296         {
297                 callback_func_t *old_cf;
298
299                 old_cf = le->value;
300                 le->value = cf;
301
302                 WARNING ("plugin: register_callback: "
303                                 "a callback named `%s' already exists - "
304                                 "overwriting the old entry!", name);
305
306                 destroy_callback (old_cf);
307                 sfree (key);
308         }
309
310         return (0);
311 } /* }}} int register_callback */
312
313 static void log_list_callbacks (llist_t **list, /* {{{ */
314                                 const char *comment)
315 {
316         char *str;
317         int len;
318         int i;
319         llentry_t *le;
320         int n;
321         char **keys;
322
323         n = llist_size(*list);
324         if (n == 0)
325         {
326                 INFO("%s [none]", comment);
327                 return;
328         }
329
330         keys = calloc(n, sizeof(char*));
331
332         if (keys == NULL)
333         {
334                 ERROR("%s: failed to allocate memory for list of callbacks",
335                       comment);
336
337                 return;
338         }
339
340         for (le = llist_head (*list), i = 0, len = 0;
341              le != NULL;
342              le = le->next, i++)
343         {
344                 keys[i] = le->key;
345                 len += strlen(le->key) + 6;
346         }
347         str = malloc(len + 10);
348         if (str == NULL)
349         {
350                 ERROR("%s: failed to allocate memory for list of callbacks",
351                       comment);
352         }
353         else
354         {
355                 *str = '\0';
356                 strjoin(str, len, keys, n, "', '");
357                 INFO("%s ['%s']", comment, str);
358                 sfree (str);
359         }
360         sfree (keys);
361 } /* }}} void log_list_callbacks */
362
363 static int create_register_callback (llist_t **list, /* {{{ */
364                 const char *name, void *callback, user_data_t const *ud)
365 {
366         callback_func_t *cf;
367
368         cf = calloc (1, sizeof (*cf));
369         if (cf == NULL)
370         {
371                 ERROR ("plugin: create_register_callback: calloc failed.");
372                 return (-1);
373         }
374
375         cf->cf_callback = callback;
376         if (ud == NULL)
377         {
378                 cf->cf_udata.data = NULL;
379                 cf->cf_udata.free_func = NULL;
380         }
381         else
382         {
383                 cf->cf_udata = *ud;
384         }
385
386         cf->cf_ctx = plugin_get_ctx ();
387
388         return (register_callback (list, name, cf));
389 } /* }}} int create_register_callback */
390
391 static int plugin_unregister (llist_t *list, const char *name) /* {{{ */
392 {
393         llentry_t *e;
394
395         if (list == NULL)
396                 return (-1);
397
398         e = llist_search (list, name);
399         if (e == NULL)
400                 return (-1);
401
402         llist_remove (list, e);
403
404         sfree (e->key);
405         destroy_callback (e->value);
406
407         llentry_destroy (e);
408
409         return (0);
410 } /* }}} int plugin_unregister */
411
412 /*
413  * (Try to) load the shared object `file'. Won't complain if it isn't a shared
414  * object, but it will bitch about a shared object not having a
415  * ``module_register'' symbol..
416  */
417 static int plugin_load_file (char *file, uint32_t flags)
418 {
419         lt_dlhandle dlh;
420         void (*reg_handle) (void);
421
422         lt_dlinit ();
423         lt_dlerror (); /* clear errors */
424
425 #if LIBTOOL_VERSION == 2
426         if (flags & PLUGIN_FLAGS_GLOBAL) {
427                 lt_dladvise advise;
428                 lt_dladvise_init(&advise);
429                 lt_dladvise_global(&advise);
430                 dlh = lt_dlopenadvise(file, advise);
431                 lt_dladvise_destroy(&advise);
432         } else {
433                 dlh = lt_dlopen (file);
434         }
435 #else /* if LIBTOOL_VERSION == 1 */
436         if (flags & PLUGIN_FLAGS_GLOBAL)
437                 WARNING ("plugin_load_file: The global flag is not supported, "
438                                 "libtool 2 is required for this.");
439         dlh = lt_dlopen (file);
440 #endif
441
442         if (dlh == NULL)
443         {
444                 char errbuf[1024] = "";
445
446                 ssnprintf (errbuf, sizeof (errbuf),
447                                 "lt_dlopen (\"%s\") failed: %s. "
448                                 "The most common cause for this problem is "
449                                 "missing dependencies. Use ldd(1) to check "
450                                 "the dependencies of the plugin "
451                                 "/ shared object.",
452                                 file, lt_dlerror ());
453
454                 ERROR ("%s", errbuf);
455                 /* Make sure this is printed to STDERR in any case, but also
456                  * make sure it's printed only once. */
457                 if (list_log != NULL)
458                         fprintf (stderr, "ERROR: %s\n", errbuf);
459
460                 return (1);
461         }
462
463         if ((reg_handle = (void (*) (void)) lt_dlsym (dlh, "module_register")) == NULL)
464         {
465                 WARNING ("Couldn't find symbol \"module_register\" in \"%s\": %s\n",
466                                 file, lt_dlerror ());
467                 lt_dlclose (dlh);
468                 return (-1);
469         }
470
471         (*reg_handle) ();
472
473         return (0);
474 }
475
476 static void *plugin_read_thread (void __attribute__((unused)) *args)
477 {
478         while (read_loop != 0)
479         {
480                 read_func_t *rf;
481                 plugin_ctx_t old_ctx;
482                 cdtime_t start;
483                 cdtime_t now;
484                 cdtime_t elapsed;
485                 int status;
486                 int rf_type;
487                 int rc;
488
489                 /* Get the read function that needs to be read next.
490                  * We don't need to hold "read_lock" for the heap, but we need
491                  * to call c_heap_get_root() and pthread_cond_wait() in the
492                  * same protected block. */
493                 pthread_mutex_lock (&read_lock);
494                 rf = c_heap_get_root (read_heap);
495                 if (rf == NULL)
496                 {
497                         pthread_cond_wait (&read_cond, &read_lock);
498                         pthread_mutex_unlock (&read_lock);
499                         continue;
500                 }
501                 pthread_mutex_unlock (&read_lock);
502
503                 if (rf->rf_interval == 0)
504                 {
505                         /* this should not happen, because the interval is set
506                          * for each plugin when loading it
507                          * XXX: issue a warning? */
508                         rf->rf_interval = plugin_get_interval ();
509                         rf->rf_effective_interval = rf->rf_interval;
510
511                         rf->rf_next_read = cdtime ();
512                 }
513
514                 /* sleep until this entry is due,
515                  * using pthread_cond_timedwait */
516                 pthread_mutex_lock (&read_lock);
517                 /* In pthread_cond_timedwait, spurious wakeups are possible
518                  * (and really happen, at least on NetBSD with > 1 CPU), thus
519                  * we need to re-evaluate the condition every time
520                  * pthread_cond_timedwait returns. */
521                 rc = 0;
522                 while ((read_loop != 0)
523                                 && (cdtime () < rf->rf_next_read)
524                                 && rc == 0)
525                 {
526                         rc = pthread_cond_timedwait (&read_cond, &read_lock,
527                                 &CDTIME_T_TO_TIMESPEC (rf->rf_next_read));
528                 }
529
530                 /* Must hold `read_lock' when accessing `rf->rf_type'. */
531                 rf_type = rf->rf_type;
532                 pthread_mutex_unlock (&read_lock);
533
534                 /* Check if we're supposed to stop.. This may have interrupted
535                  * the sleep, too. */
536                 if (read_loop == 0)
537                 {
538                         /* Insert `rf' again, so it can be free'd correctly */
539                         c_heap_insert (read_heap, rf);
540                         break;
541                 }
542
543                 /* The entry has been marked for deletion. The linked list
544                  * entry has already been removed by `plugin_unregister_read'.
545                  * All we have to do here is free the `read_func_t' and
546                  * continue. */
547                 if (rf_type == RF_REMOVE)
548                 {
549                         DEBUG ("plugin_read_thread: Destroying the `%s' "
550                                         "callback.", rf->rf_name);
551                         sfree (rf->rf_name);
552                         destroy_callback ((callback_func_t *) rf);
553                         rf = NULL;
554                         continue;
555                 }
556
557                 DEBUG ("plugin_read_thread: Handling `%s'.", rf->rf_name);
558
559                 start = cdtime ();
560
561                 old_ctx = plugin_set_ctx (rf->rf_ctx);
562
563                 if (rf_type == RF_SIMPLE)
564                 {
565                         int (*callback) (void);
566
567                         callback = rf->rf_callback;
568                         status = (*callback) ();
569                 }
570                 else
571                 {
572                         plugin_read_cb callback;
573
574                         assert (rf_type == RF_COMPLEX);
575
576                         callback = rf->rf_callback;
577                         status = (*callback) (&rf->rf_udata);
578                 }
579
580                 plugin_set_ctx (old_ctx);
581
582                 /* If the function signals failure, we will increase the
583                  * intervals in which it will be called. */
584                 if (status != 0)
585                 {
586                         rf->rf_effective_interval *= 2;
587                         if (rf->rf_effective_interval > max_read_interval)
588                                 rf->rf_effective_interval = max_read_interval;
589
590                         NOTICE ("read-function of plugin `%s' failed. "
591                                         "Will suspend it for %.3f seconds.",
592                                         rf->rf_name,
593                                         CDTIME_T_TO_DOUBLE (rf->rf_effective_interval));
594                 }
595                 else
596                 {
597                         /* Success: Restore the interval, if it was changed. */
598                         rf->rf_effective_interval = rf->rf_interval;
599                 }
600
601                 /* update the ``next read due'' field */
602                 now = cdtime ();
603
604                 /* calculate the time spent in the read function */
605                 elapsed = (now - start);
606
607                 if (elapsed > rf->rf_effective_interval)
608                         WARNING ("plugin_read_thread: read-function of the `%s' plugin took %.3f "
609                                 "seconds, which is above its read interval (%.3f seconds). You might "
610                                 "want to adjust the `Interval' or `ReadThreads' settings.",
611                                 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed),
612                                 CDTIME_T_TO_DOUBLE(rf->rf_effective_interval));
613
614                 DEBUG ("plugin_read_thread: read-function of the `%s' plugin took "
615                                 "%.6f seconds.",
616                                 rf->rf_name, CDTIME_T_TO_DOUBLE(elapsed));
617
618                 DEBUG ("plugin_read_thread: Effective interval of the "
619                                 "`%s' plugin is %.3f seconds.",
620                                 rf->rf_name,
621                                 CDTIME_T_TO_DOUBLE (rf->rf_effective_interval));
622
623                 /* Calculate the next (absolute) time at which this function
624                  * should be called. */
625                 rf->rf_next_read += rf->rf_effective_interval;
626
627                 /* Check, if `rf_next_read' is in the past. */
628                 if (rf->rf_next_read < now)
629                 {
630                         /* `rf_next_read' is in the past. Insert `now'
631                          * so this value doesn't trail off into the
632                          * past too much. */
633                         rf->rf_next_read = now;
634                 }
635
636                 DEBUG ("plugin_read_thread: Next read of the `%s' plugin at %.3f.",
637                                 rf->rf_name,
638                                 CDTIME_T_TO_DOUBLE (rf->rf_next_read));
639
640                 /* Re-insert this read function into the heap again. */
641                 c_heap_insert (read_heap, rf);
642         } /* while (read_loop) */
643
644         pthread_exit (NULL);
645         return ((void *) 0);
646 } /* void *plugin_read_thread */
647
648 static void start_read_threads (int num)
649 {
650         if (read_threads != NULL)
651                 return;
652
653         read_threads = (pthread_t *) calloc (num, sizeof (pthread_t));
654         if (read_threads == NULL)
655         {
656                 ERROR ("plugin: start_read_threads: calloc failed.");
657                 return;
658         }
659
660         read_threads_num = 0;
661         for (int i = 0; i < num; i++)
662         {
663                 if (pthread_create (read_threads + read_threads_num, NULL,
664                                         plugin_read_thread, NULL) == 0)
665                 {
666 #if defined(HAVE_PTHREAD_SETNAME_NP) || defined(HAVE_PTHREAD_SET_NAME_NP)
667                         char thread_name[16];
668                         sstrncpy (thread_name, "plugin reader", sizeof(thread_name));
669 # if defined(HAVE_PTHREAD_SETNAME_NP)
670                         pthread_setname_np (*(read_threads + read_threads_num),
671                                 thread_name);
672 # elif defined(HAVE_PTHREAD_SET_NAME_NP)
673                         pthread_set_name_np (*(read_threads + read_threads_num),
674                                 thread_name);
675 # endif
676 #endif
677                         read_threads_num++;
678                 }
679                 else
680                 {
681                         ERROR ("plugin: start_read_threads: pthread_create failed.");
682                         return;
683                 }
684         } /* for (i) */
685 } /* void start_read_threads */
686
687 static void stop_read_threads (void)
688 {
689         if (read_threads == NULL)
690                 return;
691
692         INFO ("collectd: Stopping %i read threads.", read_threads_num);
693
694         pthread_mutex_lock (&read_lock);
695         read_loop = 0;
696         DEBUG ("plugin: stop_read_threads: Signalling `read_cond'");
697         pthread_cond_broadcast (&read_cond);
698         pthread_mutex_unlock (&read_lock);
699
700         for (int i = 0; i < read_threads_num; i++)
701         {
702                 if (pthread_join (read_threads[i], NULL) != 0)
703                 {
704                         ERROR ("plugin: stop_read_threads: pthread_join failed.");
705                 }
706                 read_threads[i] = (pthread_t) 0;
707         }
708         sfree (read_threads);
709         read_threads_num = 0;
710 } /* void stop_read_threads */
711
712 static void plugin_value_list_free (value_list_t *vl) /* {{{ */
713 {
714         if (vl == NULL)
715                 return;
716
717         meta_data_destroy (vl->meta);
718         sfree (vl->values);
719         sfree (vl);
720 } /* }}} void plugin_value_list_free */
721
722 static value_list_t *plugin_value_list_clone (value_list_t const *vl_orig) /* {{{ */
723 {
724         value_list_t *vl;
725
726         if (vl_orig == NULL)
727                 return (NULL);
728
729         vl = malloc (sizeof (*vl));
730         if (vl == NULL)
731                 return (NULL);
732         memcpy (vl, vl_orig, sizeof (*vl));
733
734         if (vl->host[0] == 0)
735                 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
736
737         vl->values = calloc (vl_orig->values_len, sizeof (*vl->values));
738         if (vl->values == NULL)
739         {
740                 plugin_value_list_free (vl);
741                 return (NULL);
742         }
743         memcpy (vl->values, vl_orig->values,
744                         vl_orig->values_len * sizeof (*vl->values));
745
746         vl->meta = meta_data_clone (vl->meta);
747         if ((vl_orig->meta != NULL) && (vl->meta == NULL))
748         {
749                 plugin_value_list_free (vl);
750                 return (NULL);
751         }
752
753         if (vl->time == 0)
754                 vl->time = cdtime ();
755
756         /* Fill in the interval from the thread context, if it is zero. */
757         if (vl->interval == 0)
758         {
759                 plugin_ctx_t ctx = plugin_get_ctx ();
760
761                 if (ctx.interval != 0)
762                         vl->interval = ctx.interval;
763                 else
764                 {
765                         char name[6 * DATA_MAX_NAME_LEN];
766                         FORMAT_VL (name, sizeof (name), vl);
767                         ERROR ("plugin_value_list_clone: Unable to determine "
768                                         "interval from context for "
769                                         "value list \"%s\". "
770                                         "This indicates a broken plugin. "
771                                         "Please report this problem to the "
772                                         "collectd mailing list or at "
773                                         "<http://collectd.org/bugs/>.", name);
774                         vl->interval = cf_get_default_interval ();
775                 }
776         }
777
778         return (vl);
779 } /* }}} value_list_t *plugin_value_list_clone */
780
781 static int plugin_write_enqueue (value_list_t const *vl) /* {{{ */
782 {
783         write_queue_t *q;
784
785         q = malloc (sizeof (*q));
786         if (q == NULL)
787                 return (ENOMEM);
788         q->next = NULL;
789
790         q->vl = plugin_value_list_clone (vl);
791         if (q->vl == NULL)
792         {
793                 sfree (q);
794                 return (ENOMEM);
795         }
796
797         /* Store context of caller (read plugin); otherwise, it would not be
798          * available to the write plugins when actually dispatching the
799          * value-list later on. */
800         q->ctx = plugin_get_ctx ();
801
802         pthread_mutex_lock (&write_lock);
803
804         if (write_queue_tail == NULL)
805         {
806                 write_queue_head = q;
807                 write_queue_tail = q;
808                 write_queue_length = 1;
809         }
810         else
811         {
812                 write_queue_tail->next = q;
813                 write_queue_tail = q;
814                 write_queue_length += 1;
815         }
816
817         pthread_cond_signal (&write_cond);
818         pthread_mutex_unlock (&write_lock);
819
820         return (0);
821 } /* }}} int plugin_write_enqueue */
822
823 static value_list_t *plugin_write_dequeue (void) /* {{{ */
824 {
825         write_queue_t *q;
826         value_list_t *vl;
827
828         pthread_mutex_lock (&write_lock);
829
830         while (write_loop && (write_queue_head == NULL))
831                 pthread_cond_wait (&write_cond, &write_lock);
832
833         if (write_queue_head == NULL)
834         {
835                 pthread_mutex_unlock (&write_lock);
836                 return (NULL);
837         }
838
839         q = write_queue_head;
840         write_queue_head = q->next;
841         write_queue_length -= 1;
842         if (write_queue_head == NULL) {
843                 write_queue_tail = NULL;
844                 assert(0 == write_queue_length);
845                 }
846
847         pthread_mutex_unlock (&write_lock);
848
849         (void) plugin_set_ctx (q->ctx);
850
851         vl = q->vl;
852         sfree (q);
853         return (vl);
854 } /* }}} value_list_t *plugin_write_dequeue */
855
856 static void *plugin_write_thread (void __attribute__((unused)) *args) /* {{{ */
857 {
858         while (write_loop)
859         {
860                 value_list_t *vl = plugin_write_dequeue ();
861                 if (vl == NULL)
862                         continue;
863
864                 plugin_dispatch_values_internal (vl);
865
866                 plugin_value_list_free (vl);
867         }
868
869         pthread_exit (NULL);
870         return ((void *) 0);
871 } /* }}} void *plugin_write_thread */
872
873 static void start_write_threads (size_t num) /* {{{ */
874 {
875         if (write_threads != NULL)
876                 return;
877
878         write_threads = (pthread_t *) calloc (num, sizeof (pthread_t));
879         if (write_threads == NULL)
880         {
881                 ERROR ("plugin: start_write_threads: calloc failed.");
882                 return;
883         }
884
885         write_threads_num = 0;
886         for (size_t i = 0; i < num; i++)
887         {
888                 int status;
889
890                 status = pthread_create (write_threads + write_threads_num,
891                                 /* attr = */ NULL,
892                                 plugin_write_thread,
893                                 /* arg = */ NULL);
894                 if (status != 0)
895                 {
896                         char errbuf[1024];
897                         ERROR ("plugin: start_write_threads: pthread_create failed "
898                                         "with status %i (%s).", status,
899                                         sstrerror (status, errbuf, sizeof (errbuf)));
900                         return;
901                 } else {
902 #if defined(HAVE_PTHREAD_SETNAME_NP) || defined(HAVE_PTHREAD_SET_NAME_NP)
903                         char thread_name[16];
904                         sstrncpy (thread_name, "plugin writer", sizeof(thread_name));
905 # if defined(HAVE_PTHREAD_SETNAME_NP)
906                         pthread_setname_np (*(write_threads + write_threads_num),
907                                 thread_name);
908 # elif defined(HAVE_PTHREAD_SET_NAME_NP)
909                         pthread_set_name_np (*(write_threads + write_threads_num),
910                                 thread_name);
911 # endif
912 #endif
913                         write_threads_num++;
914                 }
915         } /* for (i) */
916 } /* }}} void start_write_threads */
917
918 static void stop_write_threads (void) /* {{{ */
919 {
920         write_queue_t *q;
921         size_t i;
922
923         if (write_threads == NULL)
924                 return;
925
926         INFO ("collectd: Stopping %zu write threads.", write_threads_num);
927
928         pthread_mutex_lock (&write_lock);
929         write_loop = 0;
930         DEBUG ("plugin: stop_write_threads: Signalling `write_cond'");
931         pthread_cond_broadcast (&write_cond);
932         pthread_mutex_unlock (&write_lock);
933
934         for (i = 0; i < write_threads_num; i++)
935         {
936                 if (pthread_join (write_threads[i], NULL) != 0)
937                 {
938                         ERROR ("plugin: stop_write_threads: pthread_join failed.");
939                 }
940                 write_threads[i] = (pthread_t) 0;
941         }
942         sfree (write_threads);
943         write_threads_num = 0;
944
945         pthread_mutex_lock (&write_lock);
946         i = 0;
947         for (q = write_queue_head; q != NULL; )
948         {
949                 write_queue_t *q1 = q;
950                 plugin_value_list_free (q->vl);
951                 q = q->next;
952                 sfree (q1);
953                 i++;
954         }
955         write_queue_head = NULL;
956         write_queue_tail = NULL;
957         write_queue_length = 0;
958         pthread_mutex_unlock (&write_lock);
959
960         if (i > 0)
961         {
962                 WARNING ("plugin: %zu value list%s left after shutting down "
963                                 "the write threads.",
964                                 i, (i == 1) ? " was" : "s were");
965         }
966 } /* }}} void stop_write_threads */
967
968 /*
969  * Public functions
970  */
971 void plugin_set_dir (const char *dir)
972 {
973         sfree (plugindir);
974
975         if (dir == NULL)
976         {
977                 plugindir = NULL;
978                 return;
979         }
980
981         plugindir = strdup (dir);
982         if (plugindir == NULL)
983                 ERROR ("plugin_set_dir: strdup(\"%s\") failed", dir);
984 }
985
986 static _Bool plugin_is_loaded (char const *name)
987 {
988         int status;
989
990         if (plugins_loaded == NULL)
991                 plugins_loaded = c_avl_create ((int (*) (const void *, const void *)) strcasecmp);
992         assert (plugins_loaded != NULL);
993
994         status = c_avl_get (plugins_loaded, name, /* ret_value = */ NULL);
995         return (status == 0);
996 }
997
998 static int plugin_mark_loaded (char const *name)
999 {
1000         char *name_copy;
1001         int status;
1002
1003         name_copy = strdup (name);
1004         if (name_copy == NULL)
1005                 return (ENOMEM);
1006
1007         status = c_avl_insert (plugins_loaded,
1008                         /* key = */ name_copy, /* value = */ NULL);
1009         return (status);
1010 }
1011
1012 static void plugin_free_loaded (void)
1013 {
1014         void *key;
1015         void *value;
1016
1017         if (plugins_loaded == NULL)
1018                 return;
1019
1020         while (c_avl_pick (plugins_loaded, &key, &value) == 0)
1021         {
1022                 sfree (key);
1023                 assert (value == NULL);
1024         }
1025
1026         c_avl_destroy (plugins_loaded);
1027         plugins_loaded = NULL;
1028 }
1029
1030 #define BUFSIZE 512
1031 int plugin_load (char const *plugin_name, uint32_t flags)
1032 {
1033         DIR  *dh;
1034         const char *dir;
1035         char  filename[BUFSIZE] = "";
1036         char  typename[BUFSIZE];
1037         int   ret;
1038         struct stat    statbuf;
1039         struct dirent *de;
1040         int status;
1041
1042         if (plugin_name == NULL)
1043                 return (EINVAL);
1044
1045         /* Check if plugin is already loaded and don't do anything in this
1046          * case. */
1047         if (plugin_is_loaded (plugin_name))
1048                 return (0);
1049
1050         dir = plugin_get_dir ();
1051         ret = 1;
1052
1053         /*
1054          * XXX: Magic at work:
1055          *
1056          * Some of the language bindings, for example the Python and Perl
1057          * plugins, need to be able to export symbols to the scripts they run.
1058          * For this to happen, the "Globals" flag needs to be set.
1059          * Unfortunately, this technical detail is hard to explain to the
1060          * average user and she shouldn't have to worry about this, ideally.
1061          * So in order to save everyone's sanity use a different default for a
1062          * handful of special plugins. --octo
1063          */
1064         if ((strcasecmp ("perl", plugin_name) == 0)
1065                         || (strcasecmp ("python", plugin_name) == 0))
1066                 flags |= PLUGIN_FLAGS_GLOBAL;
1067
1068         /* `cpu' should not match `cpufreq'. To solve this we add `.so' to the
1069          * type when matching the filename */
1070         status = ssnprintf (typename, sizeof (typename), "%s.so", plugin_name);
1071         if ((status < 0) || ((size_t) status >= sizeof (typename)))
1072         {
1073                 WARNING ("plugin_load: Filename too long: \"%s.so\"", plugin_name);
1074                 return (-1);
1075         }
1076
1077         if ((dh = opendir (dir)) == NULL)
1078         {
1079                 char errbuf[1024];
1080                 ERROR ("plugin_load: opendir (%s) failed: %s", dir,
1081                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1082                 return (-1);
1083         }
1084
1085         while ((de = readdir (dh)) != NULL)
1086         {
1087                 if (strcasecmp (de->d_name, typename))
1088                         continue;
1089
1090                 status = ssnprintf (filename, sizeof (filename),
1091                                 "%s/%s", dir, de->d_name);
1092                 if ((status < 0) || ((size_t) status >= sizeof (filename)))
1093                 {
1094                         WARNING ("plugin_load: Filename too long: \"%s/%s\"",
1095                                         dir, de->d_name);
1096                         continue;
1097                 }
1098
1099                 if (lstat (filename, &statbuf) == -1)
1100                 {
1101                         char errbuf[1024];
1102                         WARNING ("plugin_load: stat (\"%s\") failed: %s",
1103                                         filename,
1104                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1105                         continue;
1106                 }
1107                 else if (!S_ISREG (statbuf.st_mode))
1108                 {
1109                         /* don't follow symlinks */
1110                         WARNING ("plugin_load: %s is not a regular file.",
1111                                         filename);
1112                         continue;
1113                 }
1114
1115                 status = plugin_load_file (filename, flags);
1116                 if (status == 0)
1117                 {
1118                         /* success */
1119                         plugin_mark_loaded (plugin_name);
1120                         ret = 0;
1121                         INFO ("plugin_load: plugin \"%s\" successfully loaded.", plugin_name);
1122                         break;
1123                 }
1124                 else
1125                 {
1126                         ERROR ("plugin_load: Load plugin \"%s\" failed with "
1127                                         "status %i.", plugin_name, status);
1128                 }
1129         }
1130
1131         closedir (dh);
1132
1133         if (filename[0] == 0)
1134                 ERROR ("plugin_load: Could not find plugin \"%s\" in %s",
1135                                 plugin_name, dir);
1136
1137         return (ret);
1138 }
1139
1140 /*
1141  * The `register_*' functions follow
1142  */
1143 int plugin_register_config (const char *name,
1144                 int (*callback) (const char *key, const char *val),
1145                 const char **keys, int keys_num)
1146 {
1147         cf_register (name, callback, keys, keys_num);
1148         return (0);
1149 } /* int plugin_register_config */
1150
1151 int plugin_register_complex_config (const char *type,
1152                 int (*callback) (oconfig_item_t *))
1153 {
1154         return (cf_register_complex (type, callback));
1155 } /* int plugin_register_complex_config */
1156
1157 int plugin_register_init (const char *name,
1158                 int (*callback) (void))
1159 {
1160         return (create_register_callback (&list_init, name, (void *) callback,
1161                                 /* user_data = */ NULL));
1162 } /* plugin_register_init */
1163
1164 static int plugin_compare_read_func (const void *arg0, const void *arg1)
1165 {
1166         const read_func_t *rf0;
1167         const read_func_t *rf1;
1168
1169         rf0 = arg0;
1170         rf1 = arg1;
1171
1172         if (rf0->rf_next_read < rf1->rf_next_read)
1173                 return (-1);
1174         else if (rf0->rf_next_read > rf1->rf_next_read)
1175                 return (1);
1176         else
1177                 return (0);
1178 } /* int plugin_compare_read_func */
1179
1180 /* Add a read function to both, the heap and a linked list. The linked list if
1181  * used to look-up read functions, especially for the remove function. The heap
1182  * is used to determine which plugin to read next. */
1183 static int plugin_insert_read (read_func_t *rf)
1184 {
1185         int status;
1186         llentry_t *le;
1187
1188         rf->rf_next_read = cdtime ();
1189         rf->rf_effective_interval = rf->rf_interval;
1190
1191         pthread_mutex_lock (&read_lock);
1192
1193         if (read_list == NULL)
1194         {
1195                 read_list = llist_create ();
1196                 if (read_list == NULL)
1197                 {
1198                         pthread_mutex_unlock (&read_lock);
1199                         ERROR ("plugin_insert_read: read_list failed.");
1200                         return (-1);
1201                 }
1202         }
1203
1204         if (read_heap == NULL)
1205         {
1206                 read_heap = c_heap_create (plugin_compare_read_func);
1207                 if (read_heap == NULL)
1208                 {
1209                         pthread_mutex_unlock (&read_lock);
1210                         ERROR ("plugin_insert_read: c_heap_create failed.");
1211                         return (-1);
1212                 }
1213         }
1214
1215         le = llist_search (read_list, rf->rf_name);
1216         if (le != NULL)
1217         {
1218                 pthread_mutex_unlock (&read_lock);
1219                 WARNING ("The read function \"%s\" is already registered. "
1220                                 "Check for duplicate \"LoadPlugin\" lines "
1221                                 "in your configuration!",
1222                                 rf->rf_name);
1223                 return (EINVAL);
1224         }
1225
1226         le = llentry_create (rf->rf_name, rf);
1227         if (le == NULL)
1228         {
1229                 pthread_mutex_unlock (&read_lock);
1230                 ERROR ("plugin_insert_read: llentry_create failed.");
1231                 return (-1);
1232         }
1233
1234         status = c_heap_insert (read_heap, rf);
1235         if (status != 0)
1236         {
1237                 pthread_mutex_unlock (&read_lock);
1238                 ERROR ("plugin_insert_read: c_heap_insert failed.");
1239                 llentry_destroy (le);
1240                 return (-1);
1241         }
1242
1243         /* This does not fail. */
1244         llist_append (read_list, le);
1245
1246         /* Wake up all the read threads. */
1247         pthread_cond_broadcast (&read_cond);
1248         pthread_mutex_unlock (&read_lock);
1249         return (0);
1250 } /* int plugin_insert_read */
1251
1252 int plugin_register_read (const char *name,
1253                 int (*callback) (void))
1254 {
1255         read_func_t *rf;
1256         int status;
1257
1258         rf = calloc (1, sizeof (*rf));
1259         if (rf == NULL)
1260         {
1261                 ERROR ("plugin_register_read: calloc failed.");
1262                 return (ENOMEM);
1263         }
1264
1265         rf->rf_callback = (void *) callback;
1266         rf->rf_udata.data = NULL;
1267         rf->rf_udata.free_func = NULL;
1268         rf->rf_ctx = plugin_get_ctx ();
1269         rf->rf_group[0] = '\0';
1270         rf->rf_name = strdup (name);
1271         rf->rf_type = RF_SIMPLE;
1272         rf->rf_interval = plugin_get_interval ();
1273
1274         status = plugin_insert_read (rf);
1275         if (status != 0) {
1276                 sfree (rf->rf_name);
1277                 sfree (rf);
1278         }
1279
1280         return (status);
1281 } /* int plugin_register_read */
1282
1283 int plugin_register_complex_read (const char *group, const char *name,
1284                 plugin_read_cb callback,
1285                 cdtime_t interval,
1286                 user_data_t const *user_data)
1287 {
1288         read_func_t *rf;
1289         int status;
1290
1291         rf = calloc (1,sizeof (*rf));
1292         if (rf == NULL)
1293         {
1294                 ERROR ("plugin_register_complex_read: calloc failed.");
1295                 return (ENOMEM);
1296         }
1297
1298         rf->rf_callback = (void *) callback;
1299         if (group != NULL)
1300                 sstrncpy (rf->rf_group, group, sizeof (rf->rf_group));
1301         else
1302                 rf->rf_group[0] = '\0';
1303         rf->rf_name = strdup (name);
1304         rf->rf_type = RF_COMPLEX;
1305         rf->rf_interval = (interval != 0) ? interval : plugin_get_interval ();
1306
1307         /* Set user data */
1308         if (user_data == NULL)
1309         {
1310                 rf->rf_udata.data = NULL;
1311                 rf->rf_udata.free_func = NULL;
1312         }
1313         else
1314         {
1315                 rf->rf_udata = *user_data;
1316         }
1317
1318         rf->rf_ctx = plugin_get_ctx ();
1319
1320         status = plugin_insert_read (rf);
1321         if (status != 0) {
1322                 sfree (rf->rf_name);
1323                 sfree (rf);
1324         }
1325
1326         return (status);
1327 } /* int plugin_register_complex_read */
1328
1329 int plugin_register_write (const char *name,
1330                 plugin_write_cb callback, user_data_t const *ud)
1331 {
1332         return (create_register_callback (&list_write, name,
1333                                 (void *) callback, ud));
1334 } /* int plugin_register_write */
1335
1336 static int plugin_flush_timeout_callback (user_data_t *ud)
1337 {
1338         flush_callback_t *cb = ud->data;
1339
1340         return plugin_flush (cb->name, cb->timeout, /* identifier = */ NULL);
1341 } /* static int plugin_flush_callback */
1342
1343 static void plugin_flush_timeout_callback_free (void *data)
1344 {
1345         flush_callback_t *cb = data;
1346
1347         if (cb == NULL) return;
1348
1349         sfree (cb->name);
1350         sfree (cb);
1351 } /* static void plugin_flush_callback_free */
1352
1353 static char *plugin_flush_callback_name (const char *name)
1354 {
1355         const char *flush_prefix = "flush/";
1356         size_t prefix_size;
1357         char *flush_name;
1358         size_t name_size;
1359
1360         prefix_size = strlen(flush_prefix);
1361         name_size = strlen(name);
1362
1363         flush_name = malloc (name_size + prefix_size + 1);
1364         if (flush_name == NULL)
1365         {
1366                 ERROR ("plugin_flush_callback_name: malloc failed.");
1367                 return (NULL);
1368         }
1369
1370         sstrncpy (flush_name, flush_prefix, prefix_size + 1);
1371         sstrncpy (flush_name + prefix_size, name, name_size + 1);
1372
1373         return flush_name;
1374 } /* static char *plugin_flush_callback_name */
1375
1376 int plugin_register_flush (const char *name,
1377                 plugin_flush_cb callback, user_data_t const *ud)
1378 {
1379         int status;
1380         plugin_ctx_t ctx = plugin_get_ctx ();
1381
1382         status = create_register_callback (&list_flush, name,
1383                 (void *) callback, ud);
1384         if (status != 0)
1385                 return status;
1386
1387         if (ctx.flush_interval != 0)
1388         {
1389                 char *flush_name;
1390                 flush_callback_t *cb;
1391
1392                 flush_name = plugin_flush_callback_name (name);
1393                 if (flush_name == NULL)
1394                         return (-1);
1395
1396                 cb = malloc(sizeof (*cb));
1397                 if (cb == NULL)
1398                 {
1399                         ERROR ("plugin_register_flush: malloc failed.");
1400                         sfree (flush_name);
1401                         return (-1);
1402                 }
1403
1404                 cb->name = strdup (name);
1405                 if (cb->name == NULL)
1406                 {
1407                         ERROR ("plugin_register_flush: strdup failed.");
1408                         sfree (cb);
1409                         sfree (flush_name);
1410                         return (-1);
1411                 }
1412                 cb->timeout = ctx.flush_timeout;
1413
1414                 status = plugin_register_complex_read (
1415                         /* group     = */ "flush",
1416                         /* name      = */ flush_name,
1417                         /* callback  = */ plugin_flush_timeout_callback,
1418                         /* interval  = */ ctx.flush_interval,
1419                         /* user data = */ &(user_data_t) {
1420                                 .data = cb,
1421                                 .free_func = plugin_flush_timeout_callback_free,
1422                         });
1423
1424                 sfree (flush_name);
1425                 if (status != 0)
1426                 {
1427                         sfree (cb->name);
1428                         sfree (cb);
1429                         return status;
1430                 }
1431         }
1432
1433         return 0;
1434 } /* int plugin_register_flush */
1435
1436 int plugin_register_missing (const char *name,
1437                 plugin_missing_cb callback, user_data_t const *ud)
1438 {
1439         return (create_register_callback (&list_missing, name,
1440                                 (void *) callback, ud));
1441 } /* int plugin_register_missing */
1442
1443 int plugin_register_shutdown (const char *name,
1444                 int (*callback) (void))
1445 {
1446         return (create_register_callback (&list_shutdown, name,
1447                                 (void *) callback, /* user_data = */ NULL));
1448 } /* int plugin_register_shutdown */
1449
1450 static void plugin_free_data_sets (void)
1451 {
1452         void *key;
1453         void *value;
1454
1455         if (data_sets == NULL)
1456                 return;
1457
1458         while (c_avl_pick (data_sets, &key, &value) == 0)
1459         {
1460                 data_set_t *ds = value;
1461                 /* key is a pointer to ds->type */
1462
1463                 sfree (ds->ds);
1464                 sfree (ds);
1465         }
1466
1467         c_avl_destroy (data_sets);
1468         data_sets = NULL;
1469 } /* void plugin_free_data_sets */
1470
1471 int plugin_register_data_set (const data_set_t *ds)
1472 {
1473         data_set_t *ds_copy;
1474
1475         if ((data_sets != NULL)
1476                         && (c_avl_get (data_sets, ds->type, NULL) == 0))
1477         {
1478                 NOTICE ("Replacing DS `%s' with another version.", ds->type);
1479                 plugin_unregister_data_set (ds->type);
1480         }
1481         else if (data_sets == NULL)
1482         {
1483                 data_sets = c_avl_create ((int (*) (const void *, const void *)) strcmp);
1484                 if (data_sets == NULL)
1485                         return (-1);
1486         }
1487
1488         ds_copy = malloc (sizeof (*ds_copy));
1489         if (ds_copy == NULL)
1490                 return (-1);
1491         memcpy(ds_copy, ds, sizeof (data_set_t));
1492
1493         ds_copy->ds = malloc (sizeof (*ds_copy->ds)
1494                         * ds->ds_num);
1495         if (ds_copy->ds == NULL)
1496         {
1497                 sfree (ds_copy);
1498                 return (-1);
1499         }
1500
1501         for (size_t i = 0; i < ds->ds_num; i++)
1502                 memcpy (ds_copy->ds + i, ds->ds + i, sizeof (data_source_t));
1503
1504         return (c_avl_insert (data_sets, (void *) ds_copy->type, (void *) ds_copy));
1505 } /* int plugin_register_data_set */
1506
1507 int plugin_register_log (const char *name,
1508                 plugin_log_cb callback, user_data_t const *ud)
1509 {
1510         return (create_register_callback (&list_log, name,
1511                                 (void *) callback, ud));
1512 } /* int plugin_register_log */
1513
1514 int plugin_register_notification (const char *name,
1515                 plugin_notification_cb callback, user_data_t const *ud)
1516 {
1517         return (create_register_callback (&list_notification, name,
1518                                 (void *) callback, ud));
1519 } /* int plugin_register_log */
1520
1521 int plugin_unregister_config (const char *name)
1522 {
1523         cf_unregister (name);
1524         return (0);
1525 } /* int plugin_unregister_config */
1526
1527 int plugin_unregister_complex_config (const char *name)
1528 {
1529         cf_unregister_complex (name);
1530         return (0);
1531 } /* int plugin_unregister_complex_config */
1532
1533 int plugin_unregister_init (const char *name)
1534 {
1535         return (plugin_unregister (list_init, name));
1536 }
1537
1538 int plugin_unregister_read (const char *name) /* {{{ */
1539 {
1540         llentry_t *le;
1541         read_func_t *rf;
1542
1543         if (name == NULL)
1544                 return (-ENOENT);
1545
1546         pthread_mutex_lock (&read_lock);
1547
1548         if (read_list == NULL)
1549         {
1550                 pthread_mutex_unlock (&read_lock);
1551                 return (-ENOENT);
1552         }
1553
1554         le = llist_search (read_list, name);
1555         if (le == NULL)
1556         {
1557                 pthread_mutex_unlock (&read_lock);
1558                 WARNING ("plugin_unregister_read: No such read function: %s",
1559                                 name);
1560                 return (-ENOENT);
1561         }
1562
1563         llist_remove (read_list, le);
1564
1565         rf = le->value;
1566         assert (rf != NULL);
1567         rf->rf_type = RF_REMOVE;
1568
1569         pthread_mutex_unlock (&read_lock);
1570
1571         llentry_destroy (le);
1572
1573         DEBUG ("plugin_unregister_read: Marked `%s' for removal.", name);
1574
1575         return (0);
1576 } /* }}} int plugin_unregister_read */
1577
1578 void plugin_log_available_writers (void)
1579 {
1580         log_list_callbacks (&list_write, "Available write targets:");
1581 }
1582
1583 static int compare_read_func_group (llentry_t *e, void *ud) /* {{{ */
1584 {
1585         read_func_t *rf    = e->value;
1586         char        *group = ud;
1587
1588         return strcmp (rf->rf_group, (const char *)group);
1589 } /* }}} int compare_read_func_group */
1590
1591 int plugin_unregister_read_group (const char *group) /* {{{ */
1592 {
1593         llentry_t *le;
1594         read_func_t *rf;
1595
1596         int found = 0;
1597
1598         if (group == NULL)
1599                 return (-ENOENT);
1600
1601         pthread_mutex_lock (&read_lock);
1602
1603         if (read_list == NULL)
1604         {
1605                 pthread_mutex_unlock (&read_lock);
1606                 return (-ENOENT);
1607         }
1608
1609         while (42)
1610         {
1611                 le = llist_search_custom (read_list,
1612                                 compare_read_func_group, (void *)group);
1613
1614                 if (le == NULL)
1615                         break;
1616
1617                 ++found;
1618
1619                 llist_remove (read_list, le);
1620
1621                 rf = le->value;
1622                 assert (rf != NULL);
1623                 rf->rf_type = RF_REMOVE;
1624
1625                 llentry_destroy (le);
1626
1627                 DEBUG ("plugin_unregister_read_group: "
1628                                 "Marked `%s' (group `%s') for removal.",
1629                                 rf->rf_name, group);
1630         }
1631
1632         pthread_mutex_unlock (&read_lock);
1633
1634         if (found == 0)
1635         {
1636                 WARNING ("plugin_unregister_read_group: No such "
1637                                 "group of read function: %s", group);
1638                 return (-ENOENT);
1639         }
1640
1641         return (0);
1642 } /* }}} int plugin_unregister_read_group */
1643
1644 int plugin_unregister_write (const char *name)
1645 {
1646         return (plugin_unregister (list_write, name));
1647 }
1648
1649 int plugin_unregister_flush (const char *name)
1650 {
1651         plugin_ctx_t ctx = plugin_get_ctx ();
1652
1653         if (ctx.flush_interval != 0)
1654         {
1655                 char *flush_name;
1656
1657                 flush_name = plugin_flush_callback_name (name);
1658                 if (flush_name != NULL)
1659                 {
1660                         plugin_unregister_read(flush_name);
1661                         sfree (flush_name);
1662                 }
1663         }
1664
1665         return plugin_unregister (list_flush, name);
1666 }
1667
1668 int plugin_unregister_missing (const char *name)
1669 {
1670         return (plugin_unregister (list_missing, name));
1671 }
1672
1673 int plugin_unregister_shutdown (const char *name)
1674 {
1675         return (plugin_unregister (list_shutdown, name));
1676 }
1677
1678 int plugin_unregister_data_set (const char *name)
1679 {
1680         data_set_t *ds;
1681
1682         if (data_sets == NULL)
1683                 return (-1);
1684
1685         if (c_avl_remove (data_sets, name, NULL, (void *) &ds) != 0)
1686                 return (-1);
1687
1688         sfree (ds->ds);
1689         sfree (ds);
1690
1691         return (0);
1692 } /* int plugin_unregister_data_set */
1693
1694 int plugin_unregister_log (const char *name)
1695 {
1696         return (plugin_unregister (list_log, name));
1697 }
1698
1699 int plugin_unregister_notification (const char *name)
1700 {
1701         return (plugin_unregister (list_notification, name));
1702 }
1703
1704 int plugin_init_all (void)
1705 {
1706         char const *chain_name;
1707         llentry_t *le;
1708         int status;
1709         int ret = 0;
1710
1711         /* Init the value cache */
1712         uc_init ();
1713
1714         if (IS_TRUE (global_option_get ("CollectInternalStats")))
1715                 record_statistics = 1;
1716
1717         chain_name = global_option_get ("PreCacheChain");
1718         pre_cache_chain = fc_chain_get_by_name (chain_name);
1719
1720         chain_name = global_option_get ("PostCacheChain");
1721         post_cache_chain = fc_chain_get_by_name (chain_name);
1722
1723         write_limit_high = global_option_get_long ("WriteQueueLimitHigh",
1724                         /* default = */ 0);
1725         if (write_limit_high < 0)
1726         {
1727                 ERROR ("WriteQueueLimitHigh must be positive or zero.");
1728                 write_limit_high = 0;
1729         }
1730
1731         write_limit_low = global_option_get_long ("WriteQueueLimitLow",
1732                         /* default = */ write_limit_high / 2);
1733         if (write_limit_low < 0)
1734         {
1735                 ERROR ("WriteQueueLimitLow must be positive or zero.");
1736                 write_limit_low = write_limit_high / 2;
1737         }
1738         else if (write_limit_low > write_limit_high)
1739         {
1740                 ERROR ("WriteQueueLimitLow must not be larger than "
1741                                 "WriteQueueLimitHigh.");
1742                 write_limit_low = write_limit_high;
1743         }
1744
1745         write_threads_num = global_option_get_long ("WriteThreads",
1746                         /* default = */ 5);
1747         if (write_threads_num < 1)
1748         {
1749                 ERROR ("WriteThreads must be positive.");
1750                 write_threads_num = 5;
1751         }
1752
1753         if ((list_init == NULL) && (read_heap == NULL))
1754                 return ret;
1755
1756         /* Calling all init callbacks before checking if read callbacks
1757          * are available allows the init callbacks to register the read
1758          * callback. */
1759         le = llist_head (list_init);
1760         while (le != NULL)
1761         {
1762                 callback_func_t *cf;
1763                 plugin_init_cb callback;
1764                 plugin_ctx_t old_ctx;
1765
1766                 cf = le->value;
1767                 old_ctx = plugin_set_ctx (cf->cf_ctx);
1768                 callback = cf->cf_callback;
1769                 status = (*callback) ();
1770                 plugin_set_ctx (old_ctx);
1771
1772                 if (status != 0)
1773                 {
1774                         ERROR ("Initialization of plugin `%s' "
1775                                         "failed with status %i. "
1776                                         "Plugin will be unloaded.",
1777                                         le->key, status);
1778                         /* Plugins that register read callbacks from the init
1779                          * callback should take care of appropriate error
1780                          * handling themselves. */
1781                         /* FIXME: Unload _all_ functions */
1782                         plugin_unregister_read (le->key);
1783                         ret = -1;
1784                 }
1785
1786                 le = le->next;
1787         }
1788
1789         start_write_threads ((size_t) write_threads_num);
1790
1791         max_read_interval = global_option_get_time ("MaxReadInterval",
1792                         DEFAULT_MAX_READ_INTERVAL);
1793
1794         /* Start read-threads */
1795         if (read_heap != NULL)
1796         {
1797                 const char *rt;
1798                 int num;
1799
1800                 rt = global_option_get ("ReadThreads");
1801                 num = atoi (rt);
1802                 if (num != -1)
1803                         start_read_threads ((num > 0) ? num : 5);
1804         }
1805         return ret;
1806 } /* void plugin_init_all */
1807
1808 /* TODO: Rename this function. */
1809 void plugin_read_all (void)
1810 {
1811         if(record_statistics) {
1812                 plugin_update_internal_statistics ();
1813         }
1814         uc_check_timeout ();
1815
1816         return;
1817 } /* void plugin_read_all */
1818
1819 /* Read function called when the `-T' command line argument is given. */
1820 int plugin_read_all_once (void)
1821 {
1822         int status;
1823         int return_status = 0;
1824
1825         if (read_heap == NULL)
1826         {
1827                 NOTICE ("No read-functions are registered.");
1828                 return (0);
1829         }
1830
1831         while (42)
1832         {
1833                 read_func_t *rf;
1834                 plugin_ctx_t old_ctx;
1835
1836                 rf = c_heap_get_root (read_heap);
1837                 if (rf == NULL)
1838                         break;
1839
1840                 old_ctx = plugin_set_ctx (rf->rf_ctx);
1841
1842                 if (rf->rf_type == RF_SIMPLE)
1843                 {
1844                         int (*callback) (void);
1845
1846                         callback = rf->rf_callback;
1847                         status = (*callback) ();
1848                 }
1849                 else
1850                 {
1851                         plugin_read_cb callback;
1852
1853                         callback = rf->rf_callback;
1854                         status = (*callback) (&rf->rf_udata);
1855                 }
1856
1857                 plugin_set_ctx (old_ctx);
1858
1859                 if (status != 0)
1860                 {
1861                         NOTICE ("read-function of plugin `%s' failed.",
1862                                         rf->rf_name);
1863                         return_status = -1;
1864                 }
1865
1866                 sfree (rf->rf_name);
1867                 destroy_callback ((void *) rf);
1868         }
1869
1870         return (return_status);
1871 } /* int plugin_read_all_once */
1872
1873 int plugin_write (const char *plugin, /* {{{ */
1874                 const data_set_t *ds, const value_list_t *vl)
1875 {
1876   llentry_t *le;
1877   int status;
1878
1879   if (vl == NULL)
1880     return (EINVAL);
1881
1882   if (list_write == NULL)
1883     return (ENOENT);
1884
1885   if (ds == NULL)
1886   {
1887     ds = plugin_get_ds (vl->type);
1888     if (ds == NULL)
1889     {
1890       ERROR ("plugin_write: Unable to lookup type `%s'.", vl->type);
1891       return (ENOENT);
1892     }
1893   }
1894
1895   if (plugin == NULL)
1896   {
1897     int success = 0;
1898     int failure = 0;
1899
1900     le = llist_head (list_write);
1901     while (le != NULL)
1902     {
1903       callback_func_t *cf = le->value;
1904       plugin_write_cb callback;
1905
1906       /* do not switch plugin context; rather keep the context (interval)
1907        * information of the calling read plugin */
1908
1909       DEBUG ("plugin: plugin_write: Writing values via %s.", le->key);
1910       callback = cf->cf_callback;
1911       status = (*callback) (ds, vl, &cf->cf_udata);
1912       if (status != 0)
1913         failure++;
1914       else
1915         success++;
1916
1917       le = le->next;
1918     }
1919
1920     if ((success == 0) && (failure != 0))
1921       status = -1;
1922     else
1923       status = 0;
1924   }
1925   else /* plugin != NULL */
1926   {
1927     callback_func_t *cf;
1928     plugin_write_cb callback;
1929
1930     le = llist_head (list_write);
1931     while (le != NULL)
1932     {
1933       if (strcasecmp (plugin, le->key) == 0)
1934         break;
1935
1936       le = le->next;
1937     }
1938
1939     if (le == NULL)
1940       return (ENOENT);
1941
1942     cf = le->value;
1943
1944     /* do not switch plugin context; rather keep the context (interval)
1945      * information of the calling read plugin */
1946
1947     DEBUG ("plugin: plugin_write: Writing values via %s.", le->key);
1948     callback = cf->cf_callback;
1949     status = (*callback) (ds, vl, &cf->cf_udata);
1950   }
1951
1952   return (status);
1953 } /* }}} int plugin_write */
1954
1955 int plugin_flush (const char *plugin, cdtime_t timeout, const char *identifier)
1956 {
1957   llentry_t *le;
1958
1959   if (list_flush == NULL)
1960     return (0);
1961
1962   le = llist_head (list_flush);
1963   while (le != NULL)
1964   {
1965     callback_func_t *cf;
1966     plugin_flush_cb callback;
1967     plugin_ctx_t old_ctx;
1968
1969     if ((plugin != NULL)
1970         && (strcmp (plugin, le->key) != 0))
1971     {
1972       le = le->next;
1973       continue;
1974     }
1975
1976     cf = le->value;
1977     old_ctx = plugin_set_ctx (cf->cf_ctx);
1978     callback = cf->cf_callback;
1979
1980     (*callback) (timeout, identifier, &cf->cf_udata);
1981
1982     plugin_set_ctx (old_ctx);
1983
1984     le = le->next;
1985   }
1986   return (0);
1987 } /* int plugin_flush */
1988
1989 int plugin_shutdown_all (void)
1990 {
1991         llentry_t *le;
1992         int ret = 0;  // Assume success.
1993
1994         destroy_all_callbacks (&list_init);
1995
1996         stop_read_threads ();
1997
1998         pthread_mutex_lock (&read_lock);
1999         llist_destroy (read_list);
2000         read_list = NULL;
2001         pthread_mutex_unlock (&read_lock);
2002
2003         destroy_read_heap ();
2004
2005         /* blocks until all write threads have shut down. */
2006         stop_write_threads ();
2007
2008         /* ask all plugins to write out the state they kept. */
2009         plugin_flush (/* plugin = */ NULL,
2010                         /* timeout = */ 0,
2011                         /* identifier = */ NULL);
2012
2013         le = NULL;
2014         if (list_shutdown != NULL)
2015                 le = llist_head (list_shutdown);
2016
2017         while (le != NULL)
2018         {
2019                 callback_func_t *cf;
2020                 plugin_shutdown_cb callback;
2021                 plugin_ctx_t old_ctx;
2022
2023                 cf = le->value;
2024                 old_ctx = plugin_set_ctx (cf->cf_ctx);
2025                 callback = cf->cf_callback;
2026
2027                 /* Advance the pointer before calling the callback allows
2028                  * shutdown functions to unregister themselves. If done the
2029                  * other way around the memory `le' points to will be freed
2030                  * after callback returns. */
2031                 le = le->next;
2032
2033                 if ((*callback) () != 0)
2034                         ret = -1;
2035
2036                 plugin_set_ctx (old_ctx);
2037         }
2038
2039         /* Write plugins which use the `user_data' pointer usually need the
2040          * same data available to the flush callback. If this is the case, set
2041          * the free_function to NULL when registering the flush callback and to
2042          * the real free function when registering the write callback. This way
2043          * the data isn't freed twice. */
2044         destroy_all_callbacks (&list_flush);
2045         destroy_all_callbacks (&list_missing);
2046         destroy_all_callbacks (&list_write);
2047
2048         destroy_all_callbacks (&list_notification);
2049         destroy_all_callbacks (&list_shutdown);
2050         destroy_all_callbacks (&list_log);
2051
2052         plugin_free_loaded ();
2053         plugin_free_data_sets ();
2054         return (ret);
2055 } /* void plugin_shutdown_all */
2056
2057 int plugin_dispatch_missing (const value_list_t *vl) /* {{{ */
2058 {
2059   llentry_t *le;
2060
2061   if (list_missing == NULL)
2062     return (0);
2063
2064   le = llist_head (list_missing);
2065   while (le != NULL)
2066   {
2067     callback_func_t *cf;
2068     plugin_missing_cb callback;
2069     plugin_ctx_t old_ctx;
2070     int status;
2071
2072     cf = le->value;
2073     old_ctx = plugin_set_ctx (cf->cf_ctx);
2074     callback = cf->cf_callback;
2075
2076     status = (*callback) (vl, &cf->cf_udata);
2077     plugin_set_ctx (old_ctx);
2078     if (status != 0)
2079     {
2080       if (status < 0)
2081       {
2082         ERROR ("plugin_dispatch_missing: Callback function \"%s\" "
2083             "failed with status %i.",
2084             le->key, status);
2085         return (status);
2086       }
2087       else
2088       {
2089         return (0);
2090       }
2091     }
2092
2093     le = le->next;
2094   }
2095   return (0);
2096 } /* int }}} plugin_dispatch_missing */
2097
2098 static int plugin_dispatch_values_internal (value_list_t *vl)
2099 {
2100         int status;
2101         static c_complain_t no_write_complaint = C_COMPLAIN_INIT_STATIC;
2102
2103         data_set_t *ds;
2104
2105         _Bool free_meta_data = 0;
2106
2107         assert (vl != NULL);
2108
2109         /* These fields are initialized by plugin_value_list_clone() if needed: */
2110         assert (vl->host[0] != 0);
2111         assert (vl->time != 0); /* The time is determined at _enqueue_ time. */
2112         assert (vl->interval != 0);
2113
2114         if (vl->type[0] == 0 || vl->values == NULL || vl->values_len < 1)
2115         {
2116                 ERROR ("plugin_dispatch_values: Invalid value list "
2117                                 "from plugin %s.", vl->plugin);
2118                 return (-1);
2119         }
2120
2121         /* Free meta data only if the calling function didn't specify any. In
2122          * this case matches and targets may add some and the calling function
2123          * may not expect (and therefore free) that data. */
2124         if (vl->meta == NULL)
2125                 free_meta_data = 1;
2126
2127         if (list_write == NULL)
2128                 c_complain_once (LOG_WARNING, &no_write_complaint,
2129                                 "plugin_dispatch_values: No write callback has been "
2130                                 "registered. Please load at least one output plugin, "
2131                                 "if you want the collected data to be stored.");
2132
2133         if (data_sets == NULL)
2134         {
2135                 ERROR ("plugin_dispatch_values: No data sets registered. "
2136                                 "Could the types database be read? Check "
2137                                 "your `TypesDB' setting!");
2138                 return (-1);
2139         }
2140
2141         if (c_avl_get (data_sets, vl->type, (void *) &ds) != 0)
2142         {
2143                 char ident[6 * DATA_MAX_NAME_LEN];
2144
2145                 FORMAT_VL (ident, sizeof (ident), vl);
2146                 INFO ("plugin_dispatch_values: Dataset not found: %s "
2147                                 "(from \"%s\"), check your types.db!",
2148                                 vl->type, ident);
2149                 return (-1);
2150         }
2151
2152         DEBUG ("plugin_dispatch_values: time = %.3f; interval = %.3f; "
2153                         "host = %s; "
2154                         "plugin = %s; plugin_instance = %s; "
2155                         "type = %s; type_instance = %s;",
2156                         CDTIME_T_TO_DOUBLE (vl->time),
2157                         CDTIME_T_TO_DOUBLE (vl->interval),
2158                         vl->host,
2159                         vl->plugin, vl->plugin_instance,
2160                         vl->type, vl->type_instance);
2161
2162 #if COLLECT_DEBUG
2163         assert (0 == strcmp (ds->type, vl->type));
2164 #else
2165         if (0 != strcmp (ds->type, vl->type))
2166                 WARNING ("plugin_dispatch_values: (ds->type = %s) != (vl->type = %s)",
2167                                 ds->type, vl->type);
2168 #endif
2169
2170 #if COLLECT_DEBUG
2171         assert (ds->ds_num == vl->values_len);
2172 #else
2173         if (ds->ds_num != vl->values_len)
2174         {
2175                 ERROR ("plugin_dispatch_values: ds->type = %s: "
2176                                 "(ds->ds_num = %zu) != "
2177                                 "(vl->values_len = %zu)",
2178                                 ds->type, ds->ds_num, vl->values_len);
2179                 return (-1);
2180         }
2181 #endif
2182
2183         escape_slashes (vl->host, sizeof (vl->host));
2184         escape_slashes (vl->plugin, sizeof (vl->plugin));
2185         escape_slashes (vl->plugin_instance, sizeof (vl->plugin_instance));
2186         escape_slashes (vl->type, sizeof (vl->type));
2187         escape_slashes (vl->type_instance, sizeof (vl->type_instance));
2188
2189         if (pre_cache_chain != NULL)
2190         {
2191                 status = fc_process_chain (ds, vl, pre_cache_chain);
2192                 if (status < 0)
2193                 {
2194                         WARNING ("plugin_dispatch_values: Running the "
2195                                         "pre-cache chain failed with "
2196                                         "status %i (%#x).",
2197                                         status, status);
2198                 }
2199                 else if (status == FC_TARGET_STOP)
2200                         return (0);
2201         }
2202
2203         /* Update the value cache */
2204         uc_update (ds, vl);
2205
2206         if (post_cache_chain != NULL)
2207         {
2208                 status = fc_process_chain (ds, vl, post_cache_chain);
2209                 if (status < 0)
2210                 {
2211                         WARNING ("plugin_dispatch_values: Running the "
2212                                         "post-cache chain failed with "
2213                                         "status %i (%#x).",
2214                                         status, status);
2215                 }
2216         }
2217         else
2218                 fc_default_action (ds, vl);
2219
2220         if ((free_meta_data != 0) && (vl->meta != NULL))
2221         {
2222                 meta_data_destroy (vl->meta);
2223                 vl->meta = NULL;
2224         }
2225
2226         return (0);
2227 } /* int plugin_dispatch_values_internal */
2228
2229 static double get_drop_probability (void) /* {{{ */
2230 {
2231         long pos;
2232         long size;
2233         long wql;
2234
2235         pthread_mutex_lock (&write_lock);
2236         wql = write_queue_length;
2237         pthread_mutex_unlock (&write_lock);
2238
2239         if (wql < write_limit_low)
2240                 return (0.0);
2241         if (wql >= write_limit_high)
2242                 return (1.0);
2243
2244         pos = 1 + wql - write_limit_low;
2245         size = 1 + write_limit_high - write_limit_low;
2246
2247         return (((double) pos) / ((double) size));
2248 } /* }}} double get_drop_probability */
2249
2250 static _Bool check_drop_value (void) /* {{{ */
2251 {
2252         static cdtime_t last_message_time = 0;
2253         static pthread_mutex_t last_message_lock = PTHREAD_MUTEX_INITIALIZER;
2254
2255         double p;
2256         double q;
2257         int status;
2258
2259         if (write_limit_high == 0)
2260                 return (0);
2261
2262         p = get_drop_probability ();
2263         if (p == 0.0)
2264                 return (0);
2265
2266         status = pthread_mutex_trylock (&last_message_lock);
2267         if (status == 0)
2268         {
2269                 cdtime_t now;
2270
2271                 now = cdtime ();
2272                 if ((now - last_message_time) > TIME_T_TO_CDTIME_T (1))
2273                 {
2274                         last_message_time = now;
2275                         ERROR ("plugin_dispatch_values: Low water mark "
2276                                         "reached. Dropping %.0f%% of metrics.",
2277                                         100.0 * p);
2278                 }
2279                 pthread_mutex_unlock (&last_message_lock);
2280         }
2281
2282         if (p == 1.0)
2283                 return (1);
2284
2285         q = cdrand_d ();
2286         if (q > p)
2287                 return (1);
2288         else
2289                 return (0);
2290 } /* }}} _Bool check_drop_value */
2291
2292 int plugin_dispatch_values (value_list_t const *vl)
2293 {
2294         int status;
2295         static pthread_mutex_t statistics_lock = PTHREAD_MUTEX_INITIALIZER;
2296
2297         if (check_drop_value ()) {
2298                 if(record_statistics) {
2299                         pthread_mutex_lock(&statistics_lock);
2300                         stats_values_dropped++;
2301                         pthread_mutex_unlock(&statistics_lock);
2302                 }
2303                 return (0);
2304         }
2305
2306         status = plugin_write_enqueue (vl);
2307         if (status != 0)
2308         {
2309                 char errbuf[1024];
2310                 ERROR ("plugin_dispatch_values: plugin_write_enqueue failed "
2311                                 "with status %i (%s).", status,
2312                                 sstrerror (status, errbuf, sizeof (errbuf)));
2313                 return (status);
2314         }
2315
2316         return (0);
2317 }
2318
2319 __attribute__((sentinel))
2320 int plugin_dispatch_multivalue (value_list_t const *template, /* {{{ */
2321                 _Bool store_percentage, int store_type, ...)
2322 {
2323         value_list_t *vl;
2324         int failed = 0;
2325         gauge_t sum = 0.0;
2326         va_list ap;
2327
2328         assert (template->values_len == 1);
2329
2330         /* Calculate sum for Gauge to calculate percent if needed */
2331         if (DS_TYPE_GAUGE == store_type)        {
2332                 va_start (ap, store_type);
2333                 while (42)
2334                 {
2335                         char const *name;
2336                         gauge_t value;
2337
2338                         name = va_arg (ap, char const *);
2339                         if (name == NULL)
2340                                 break;
2341
2342                         value = va_arg (ap, gauge_t);
2343                         if (!isnan (value))
2344                                 sum += value;
2345                 }
2346                 va_end (ap);
2347         }
2348
2349
2350         vl = plugin_value_list_clone (template);
2351         /* plugin_value_list_clone makes sure vl->time is set to non-zero. */
2352         if (store_percentage)
2353                 sstrncpy (vl->type, "percent", sizeof (vl->type));
2354
2355         va_start (ap, store_type);
2356         while (42)
2357         {
2358                 char const *name;
2359                 int status;
2360
2361                 /* Set the type instance. */
2362                 name = va_arg (ap, char const *);
2363                 if (name == NULL)
2364                         break;
2365                 sstrncpy (vl->type_instance, name, sizeof (vl->type_instance));
2366
2367                 /* Set the value. */
2368                 switch (store_type)
2369                 {
2370                 case DS_TYPE_GAUGE:
2371                         vl->values[0].gauge = va_arg (ap, gauge_t);
2372                         if (store_percentage)
2373                                 vl->values[0].gauge *= sum ? (100.0 / sum) : NAN;
2374                         break;
2375                 case DS_TYPE_ABSOLUTE:
2376                         vl->values[0].absolute = va_arg (ap, absolute_t);
2377                         break;
2378                 case DS_TYPE_COUNTER:
2379                         vl->values[0].counter  = va_arg (ap, counter_t);
2380                         break;
2381                 case DS_TYPE_DERIVE:
2382                         vl->values[0].derive   = va_arg (ap, derive_t);
2383                         break;
2384                 default:
2385                         ERROR ("plugin_dispatch_multivalue: given store_type is incorrect.");
2386                         failed++;
2387                 }
2388
2389
2390                 status = plugin_write_enqueue (vl);
2391                 if (status != 0)
2392                         failed++;
2393         }
2394         va_end (ap);
2395
2396         plugin_value_list_free (vl);
2397         return (failed);
2398 } /* }}} int plugin_dispatch_multivalue */
2399
2400 int plugin_dispatch_notification (const notification_t *notif)
2401 {
2402         llentry_t *le;
2403         /* Possible TODO: Add flap detection here */
2404
2405         DEBUG ("plugin_dispatch_notification: severity = %i; message = %s; "
2406                         "time = %.3f; host = %s;",
2407                         notif->severity, notif->message,
2408                         CDTIME_T_TO_DOUBLE (notif->time), notif->host);
2409
2410         /* Nobody cares for notifications */
2411         if (list_notification == NULL)
2412                 return (-1);
2413
2414         le = llist_head (list_notification);
2415         while (le != NULL)
2416         {
2417                 callback_func_t *cf;
2418                 plugin_notification_cb callback;
2419                 int status;
2420
2421                 /* do not switch plugin context; rather keep the context
2422                  * (interval) information of the calling plugin */
2423
2424                 cf = le->value;
2425                 callback = cf->cf_callback;
2426                 status = (*callback) (notif, &cf->cf_udata);
2427                 if (status != 0)
2428                 {
2429                         WARNING ("plugin_dispatch_notification: Notification "
2430                                         "callback %s returned %i.",
2431                                         le->key, status);
2432                 }
2433
2434                 le = le->next;
2435         }
2436
2437         return (0);
2438 } /* int plugin_dispatch_notification */
2439
2440 void plugin_log (int level, const char *format, ...)
2441 {
2442         char msg[1024];
2443         va_list ap;
2444         llentry_t *le;
2445
2446 #if !COLLECT_DEBUG
2447         if (level >= LOG_DEBUG)
2448                 return;
2449 #endif
2450
2451         va_start (ap, format);
2452         vsnprintf (msg, sizeof (msg), format, ap);
2453         msg[sizeof (msg) - 1] = '\0';
2454         va_end (ap);
2455
2456         if (list_log == NULL)
2457         {
2458                 fprintf (stderr, "%s\n", msg);
2459                 return;
2460         }
2461
2462         le = llist_head (list_log);
2463         while (le != NULL)
2464         {
2465                 callback_func_t *cf;
2466                 plugin_log_cb callback;
2467
2468                 cf = le->value;
2469                 callback = cf->cf_callback;
2470
2471                 /* do not switch plugin context; rather keep the context
2472                  * (interval) information of the calling plugin */
2473
2474                 (*callback) (level, msg, &cf->cf_udata);
2475
2476                 le = le->next;
2477         }
2478 } /* void plugin_log */
2479
2480 int parse_log_severity (const char *severity)
2481 {
2482         int log_level = -1;
2483
2484         if ((0 == strcasecmp (severity, "emerg"))
2485                         || (0 == strcasecmp (severity, "alert"))
2486                         || (0 == strcasecmp (severity, "crit"))
2487                         || (0 == strcasecmp (severity, "err")))
2488                 log_level = LOG_ERR;
2489         else if (0 == strcasecmp (severity, "warning"))
2490                 log_level = LOG_WARNING;
2491         else if (0 == strcasecmp (severity, "notice"))
2492                 log_level = LOG_NOTICE;
2493         else if (0 == strcasecmp (severity, "info"))
2494                 log_level = LOG_INFO;
2495 #if COLLECT_DEBUG
2496         else if (0 == strcasecmp (severity, "debug"))
2497                 log_level = LOG_DEBUG;
2498 #endif /* COLLECT_DEBUG */
2499
2500         return (log_level);
2501 } /* int parse_log_severity */
2502
2503 int parse_notif_severity (const char *severity)
2504 {
2505         int notif_severity = -1;
2506
2507         if (strcasecmp (severity, "FAILURE") == 0)
2508                 notif_severity = NOTIF_FAILURE;
2509         else if (strcmp (severity, "OKAY") == 0)
2510                 notif_severity = NOTIF_OKAY;
2511         else if ((strcmp (severity, "WARNING") == 0)
2512                         || (strcmp (severity, "WARN") == 0))
2513                 notif_severity = NOTIF_WARNING;
2514
2515         return (notif_severity);
2516 } /* int parse_notif_severity */
2517
2518 const data_set_t *plugin_get_ds (const char *name)
2519 {
2520         data_set_t *ds;
2521
2522         if (data_sets == NULL)
2523         {
2524                 ERROR ("plugin_get_ds: No data sets are defined yet.");
2525                 return (NULL);
2526         }
2527
2528         if (c_avl_get (data_sets, name, (void *) &ds) != 0)
2529         {
2530                 DEBUG ("No such dataset registered: %s", name);
2531                 return (NULL);
2532         }
2533
2534         return (ds);
2535 } /* data_set_t *plugin_get_ds */
2536
2537 static int plugin_notification_meta_add (notification_t *n,
2538     const char *name,
2539     enum notification_meta_type_e type,
2540     const void *value)
2541 {
2542   notification_meta_t *meta;
2543   notification_meta_t *tail;
2544
2545   if ((n == NULL) || (name == NULL) || (value == NULL))
2546   {
2547     ERROR ("plugin_notification_meta_add: A pointer is NULL!");
2548     return (-1);
2549   }
2550
2551   meta = calloc (1, sizeof (*meta));
2552   if (meta == NULL)
2553   {
2554     ERROR ("plugin_notification_meta_add: calloc failed.");
2555     return (-1);
2556   }
2557
2558   sstrncpy (meta->name, name, sizeof (meta->name));
2559   meta->type = type;
2560
2561   switch (type)
2562   {
2563     case NM_TYPE_STRING:
2564     {
2565       meta->nm_value.nm_string = strdup ((const char *) value);
2566       if (meta->nm_value.nm_string == NULL)
2567       {
2568         ERROR ("plugin_notification_meta_add: strdup failed.");
2569         sfree (meta);
2570         return (-1);
2571       }
2572       break;
2573     }
2574     case NM_TYPE_SIGNED_INT:
2575     {
2576       meta->nm_value.nm_signed_int = *((int64_t *) value);
2577       break;
2578     }
2579     case NM_TYPE_UNSIGNED_INT:
2580     {
2581       meta->nm_value.nm_unsigned_int = *((uint64_t *) value);
2582       break;
2583     }
2584     case NM_TYPE_DOUBLE:
2585     {
2586       meta->nm_value.nm_double = *((double *) value);
2587       break;
2588     }
2589     case NM_TYPE_BOOLEAN:
2590     {
2591       meta->nm_value.nm_boolean = *((_Bool *) value);
2592       break;
2593     }
2594     default:
2595     {
2596       ERROR ("plugin_notification_meta_add: Unknown type: %i", type);
2597       sfree (meta);
2598       return (-1);
2599     }
2600   } /* switch (type) */
2601
2602   meta->next = NULL;
2603   tail = n->meta;
2604   while ((tail != NULL) && (tail->next != NULL))
2605     tail = tail->next;
2606
2607   if (tail == NULL)
2608     n->meta = meta;
2609   else
2610     tail->next = meta;
2611
2612   return (0);
2613 } /* int plugin_notification_meta_add */
2614
2615 int plugin_notification_meta_add_string (notification_t *n,
2616     const char *name,
2617     const char *value)
2618 {
2619   return (plugin_notification_meta_add (n, name, NM_TYPE_STRING, value));
2620 }
2621
2622 int plugin_notification_meta_add_signed_int (notification_t *n,
2623     const char *name,
2624     int64_t value)
2625 {
2626   return (plugin_notification_meta_add (n, name, NM_TYPE_SIGNED_INT, &value));
2627 }
2628
2629 int plugin_notification_meta_add_unsigned_int (notification_t *n,
2630     const char *name,
2631     uint64_t value)
2632 {
2633   return (plugin_notification_meta_add (n, name, NM_TYPE_UNSIGNED_INT, &value));
2634 }
2635
2636 int plugin_notification_meta_add_double (notification_t *n,
2637     const char *name,
2638     double value)
2639 {
2640   return (plugin_notification_meta_add (n, name, NM_TYPE_DOUBLE, &value));
2641 }
2642
2643 int plugin_notification_meta_add_boolean (notification_t *n,
2644     const char *name,
2645     _Bool value)
2646 {
2647   return (plugin_notification_meta_add (n, name, NM_TYPE_BOOLEAN, &value));
2648 }
2649
2650 int plugin_notification_meta_copy (notification_t *dst,
2651     const notification_t *src)
2652 {
2653   assert (dst != NULL);
2654   assert (src != NULL);
2655   assert (dst != src);
2656   assert ((src->meta == NULL) || (src->meta != dst->meta));
2657
2658   for (notification_meta_t *meta = src->meta; meta != NULL; meta = meta->next)
2659   {
2660     if (meta->type == NM_TYPE_STRING)
2661       plugin_notification_meta_add_string (dst, meta->name,
2662           meta->nm_value.nm_string);
2663     else if (meta->type == NM_TYPE_SIGNED_INT)
2664       plugin_notification_meta_add_signed_int (dst, meta->name,
2665           meta->nm_value.nm_signed_int);
2666     else if (meta->type == NM_TYPE_UNSIGNED_INT)
2667       plugin_notification_meta_add_unsigned_int (dst, meta->name,
2668           meta->nm_value.nm_unsigned_int);
2669     else if (meta->type == NM_TYPE_DOUBLE)
2670       plugin_notification_meta_add_double (dst, meta->name,
2671           meta->nm_value.nm_double);
2672     else if (meta->type == NM_TYPE_BOOLEAN)
2673       plugin_notification_meta_add_boolean (dst, meta->name,
2674           meta->nm_value.nm_boolean);
2675   }
2676
2677   return (0);
2678 } /* int plugin_notification_meta_copy */
2679
2680 int plugin_notification_meta_free (notification_meta_t *n)
2681 {
2682   notification_meta_t *this;
2683   notification_meta_t *next;
2684
2685   if (n == NULL)
2686   {
2687     ERROR ("plugin_notification_meta_free: n == NULL!");
2688     return (-1);
2689   }
2690
2691   this = n;
2692   while (this != NULL)
2693   {
2694     next = this->next;
2695
2696     if (this->type == NM_TYPE_STRING)
2697     {
2698       /* Assign to a temporary variable to work around nm_string's const
2699        * modifier. */
2700       void *tmp = (void *) this->nm_value.nm_string;
2701
2702       sfree (tmp);
2703       this->nm_value.nm_string = NULL;
2704     }
2705     sfree (this);
2706
2707     this = next;
2708   }
2709
2710   return (0);
2711 } /* int plugin_notification_meta_free */
2712
2713 static void plugin_ctx_destructor (void *ctx)
2714 {
2715         sfree (ctx);
2716 } /* void plugin_ctx_destructor */
2717
2718 static plugin_ctx_t ctx_init = { /* interval = */ 0 };
2719
2720 static plugin_ctx_t *plugin_ctx_create (void)
2721 {
2722         plugin_ctx_t *ctx;
2723
2724         ctx = malloc (sizeof (*ctx));
2725         if (ctx == NULL) {
2726                 char errbuf[1024];
2727                 ERROR ("Failed to allocate plugin context: %s",
2728                                 sstrerror (errno, errbuf, sizeof (errbuf)));
2729                 return NULL;
2730         }
2731
2732         *ctx = ctx_init;
2733         assert (plugin_ctx_key_initialized);
2734         pthread_setspecific (plugin_ctx_key, ctx);
2735         DEBUG("Created new plugin context.");
2736         return (ctx);
2737 } /* int plugin_ctx_create */
2738
2739 void plugin_init_ctx (void)
2740 {
2741         pthread_key_create (&plugin_ctx_key, plugin_ctx_destructor);
2742         plugin_ctx_key_initialized = 1;
2743 } /* void plugin_init_ctx */
2744
2745 plugin_ctx_t plugin_get_ctx (void)
2746 {
2747         plugin_ctx_t *ctx;
2748
2749         assert (plugin_ctx_key_initialized);
2750         ctx = pthread_getspecific (plugin_ctx_key);
2751
2752         if (ctx == NULL) {
2753                 ctx = plugin_ctx_create ();
2754                 /* this must no happen -- exit() instead? */
2755                 if (ctx == NULL)
2756                         return ctx_init;
2757         }
2758
2759         return (*ctx);
2760 } /* plugin_ctx_t plugin_get_ctx */
2761
2762 plugin_ctx_t plugin_set_ctx (plugin_ctx_t ctx)
2763 {
2764         plugin_ctx_t *c;
2765         plugin_ctx_t old;
2766
2767         assert (plugin_ctx_key_initialized);
2768         c = pthread_getspecific (plugin_ctx_key);
2769
2770         if (c == NULL) {
2771                 c = plugin_ctx_create ();
2772                 /* this must no happen -- exit() instead? */
2773                 if (c == NULL)
2774                         return ctx_init;
2775         }
2776
2777         old = *c;
2778         *c = ctx;
2779
2780         return (old);
2781 } /* void plugin_set_ctx */
2782
2783 cdtime_t plugin_get_interval (void)
2784 {
2785         cdtime_t interval;
2786
2787         interval = plugin_get_ctx().interval;
2788         if (interval > 0)
2789                 return interval;
2790
2791         return cf_get_default_interval ();
2792 } /* cdtime_t plugin_get_interval */
2793
2794 typedef struct {
2795         plugin_ctx_t ctx;
2796         void *(*start_routine) (void *);
2797         void *arg;
2798 } plugin_thread_t;
2799
2800 static void *plugin_thread_start (void *arg)
2801 {
2802         plugin_thread_t *plugin_thread = arg;
2803
2804         void *(*start_routine) (void *) = plugin_thread->start_routine;
2805         void *plugin_arg = plugin_thread->arg;
2806
2807         plugin_set_ctx (plugin_thread->ctx);
2808
2809         sfree (plugin_thread);
2810
2811         return start_routine (plugin_arg);
2812 } /* void *plugin_thread_start */
2813
2814 int plugin_thread_create (pthread_t *thread, const pthread_attr_t *attr,
2815                 void *(*start_routine) (void *), void *arg, char *name)
2816 {
2817         plugin_thread_t *plugin_thread;
2818         int ret;
2819
2820         plugin_thread = malloc (sizeof (*plugin_thread));
2821         if (plugin_thread == NULL)
2822                 return -1;
2823
2824         plugin_thread->ctx           = plugin_get_ctx ();
2825         plugin_thread->start_routine = start_routine;
2826         plugin_thread->arg           = arg;
2827
2828         ret = pthread_create (thread, attr,
2829                         plugin_thread_start, plugin_thread);
2830
2831         if (ret == 0 && name != NULL) {
2832 #if defined(HAVE_PTHREAD_SETNAME_NP) || defined(HAVE_PTHREAD_SET_NAME_NP)
2833                 char thread_name[16];
2834                 sstrncpy (thread_name, name, sizeof(thread_name));
2835 # if defined(HAVE_PTHREAD_SETNAME_NP)
2836                 pthread_setname_np (*thread, thread_name);
2837 # elif defined(HAVE_PTHREAD_SET_NAME_NP)
2838                 pthread_set_name_np (*thread, thread_name);
2839 # endif
2840 #endif
2841         }
2842
2843         return ret;
2844 } /* int plugin_thread_create */
2845
2846 /* vim: set sw=8 ts=8 noet fdm=marker : */