Merge branch 'collectd-4.3' into collectd-4.4
[collectd.git] / src / plugin.c
1 /**
2  * collectd - src/plugin.c
3  * Copyright (C) 2005-2008  Florian octo Forster
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Authors:
19  *   Florian octo Forster <octo at verplant.org>
20  *   Sebastian Harl <sh at tokkee.org>
21  **/
22
23 #include "collectd.h"
24
25 #include <ltdl.h>
26
27 #if HAVE_PTHREAD_H
28 # include <pthread.h>
29 #endif
30
31 #include "common.h"
32 #include "plugin.h"
33 #include "configfile.h"
34 #include "utils_avltree.h"
35 #include "utils_llist.h"
36 #include "utils_cache.h"
37 #include "utils_threshold.h"
38
39 /*
40  * Private structures
41  */
42 struct read_func_s
43 {
44         int wait_time;
45         int wait_left;
46         int (*callback) (void);
47         enum { DONE = 0, TODO = 1, ACTIVE = 2 } needs_read;
48 };
49 typedef struct read_func_s read_func_t;
50
51 /*
52  * Private variables
53  */
54 static llist_t *list_init;
55 static llist_t *list_read;
56 static llist_t *list_write;
57 static llist_t *list_flush;
58 static llist_t *list_shutdown;
59 static llist_t *list_log;
60 static llist_t *list_notification;
61
62 static c_avl_tree_t *data_sets;
63
64 static char *plugindir = NULL;
65
66 static int             read_loop = 1;
67 static pthread_mutex_t read_lock = PTHREAD_MUTEX_INITIALIZER;
68 static pthread_cond_t  read_cond = PTHREAD_COND_INITIALIZER;
69 static pthread_t      *read_threads = NULL;
70 static int             read_threads_num = 0;
71
72 /*
73  * Static functions
74  */
75 static const char *plugin_get_dir (void)
76 {
77         if (plugindir == NULL)
78                 return (PLUGINDIR);
79         else
80                 return (plugindir);
81 }
82
83 static int register_callback (llist_t **list, const char *name, void *callback)
84 {
85         llentry_t *le;
86         char *key;
87
88         if ((*list == NULL)
89                         && ((*list = llist_create ()) == NULL))
90                 return (-1);
91
92         le = llist_search (*list, name);
93         if (le == NULL)
94         {
95                 key = strdup (name);
96                 if (key == NULL)
97                         return (-1);
98
99                 le = llentry_create (key, callback);
100                 if (le == NULL)
101                 {
102                         free (key);
103                         return (-1);
104                 }
105
106                 llist_append (*list, le);
107         }
108         else
109         {
110                 le->value = callback;
111         }
112
113         return (0);
114 } /* int register_callback */
115
116 static int plugin_unregister (llist_t *list, const char *name)
117 {
118         llentry_t *e;
119
120         e = llist_search (list, name);
121
122         if (e == NULL)
123                 return (-1);
124
125         llist_remove (list, e);
126         free (e->key);
127         llentry_destroy (e);
128
129         return (0);
130 } /* int plugin_unregister */
131
132 /*
133  * (Try to) load the shared object `file'. Won't complain if it isn't a shared
134  * object, but it will bitch about a shared object not having a
135  * ``module_register'' symbol..
136  */
137 static int plugin_load_file (char *file)
138 {
139         lt_dlhandle dlh;
140         void (*reg_handle) (void);
141
142         DEBUG ("file = %s", file);
143
144         lt_dlinit ();
145         lt_dlerror (); /* clear errors */
146
147         if ((dlh = lt_dlopen (file)) == NULL)
148         {
149                 const char *error = lt_dlerror ();
150
151                 ERROR ("lt_dlopen (%s) failed: %s", file, error);
152                 fprintf (stderr, "lt_dlopen (%s) failed: %s\n", file, error);
153                 return (1);
154         }
155
156         if ((reg_handle = (void (*) (void)) lt_dlsym (dlh, "module_register")) == NULL)
157         {
158                 WARNING ("Couldn't find symbol `module_register' in `%s': %s\n",
159                                 file, lt_dlerror ());
160                 lt_dlclose (dlh);
161                 return (-1);
162         }
163
164         (*reg_handle) ();
165
166         return (0);
167 }
168
169 static void *plugin_read_thread (void *args)
170 {
171         llentry_t   *le;
172         read_func_t *rf;
173         int          status;
174         int          done;
175
176         pthread_mutex_lock (&read_lock);
177
178         while (read_loop != 0)
179         {
180                 le = llist_head (list_read);
181                 done = 0;
182
183                 while ((read_loop != 0) && (le != NULL))
184                 {
185                         rf = (read_func_t *) le->value;
186
187                         if (rf->needs_read != TODO)
188                         {
189                                 le = le->next;
190                                 continue;
191                         }
192
193                         /* We will do this read function */
194                         rf->needs_read = ACTIVE;
195
196                         DEBUG ("[thread #%5lu] plugin: plugin_read_thread: Handling %s",
197                                         (unsigned long int) pthread_self (), le->key);
198                         pthread_mutex_unlock (&read_lock);
199
200                         status = rf->callback ();
201                         done++;
202
203                         if (status != 0)
204                         {
205                                 if (rf->wait_time < interval_g)
206                                         rf->wait_time = interval_g;
207                                 rf->wait_left = rf->wait_time;
208                                 rf->wait_time = rf->wait_time * 2;
209                                 if (rf->wait_time > 86400)
210                                         rf->wait_time = 86400;
211
212                                 NOTICE ("read-function of plugin `%s' "
213                                                 "failed. Will suspend it for %i "
214                                                 "seconds.", le->key, rf->wait_left);
215                         }
216                         else
217                         {
218                                 rf->wait_left = 0;
219                                 rf->wait_time = interval_g;
220                         }
221
222                         pthread_mutex_lock (&read_lock);
223
224                         rf->needs_read = DONE;
225                         le = le->next;
226                 } /* while (le != NULL) */
227
228                 if ((read_loop != 0) && (done == 0))
229                 {
230                         DEBUG ("[thread #%5lu] plugin: plugin_read_thread: Waiting on read_cond.",
231                                         (unsigned long int) pthread_self ());
232                         pthread_cond_wait (&read_cond, &read_lock);
233                 }
234         } /* while (read_loop) */
235
236         pthread_mutex_unlock (&read_lock);
237
238         pthread_exit (NULL);
239         return ((void *) 0);
240 } /* void *plugin_read_thread */
241
242 static void start_threads (int num)
243 {
244         int i;
245
246         if (read_threads != NULL)
247                 return;
248
249         read_threads = (pthread_t *) calloc (num, sizeof (pthread_t));
250         if (read_threads == NULL)
251         {
252                 ERROR ("plugin: start_threads: calloc failed.");
253                 return;
254         }
255
256         read_threads_num = 0;
257         for (i = 0; i < num; i++)
258         {
259                 if (pthread_create (read_threads + read_threads_num, NULL,
260                                         plugin_read_thread, NULL) == 0)
261                 {
262                         read_threads_num++;
263                 }
264                 else
265                 {
266                         ERROR ("plugin: start_threads: pthread_create failed.");
267                         return;
268                 }
269         } /* for (i) */
270 } /* void start_threads */
271
272 static void stop_threads (void)
273 {
274         int i;
275
276         pthread_mutex_lock (&read_lock);
277         read_loop = 0;
278         DEBUG ("plugin: stop_threads: Signalling `read_cond'");
279         pthread_cond_broadcast (&read_cond);
280         pthread_mutex_unlock (&read_lock);
281
282         for (i = 0; i < read_threads_num; i++)
283         {
284                 if (pthread_join (read_threads[i], NULL) != 0)
285                 {
286                         ERROR ("plugin: stop_threads: pthread_join failed.");
287                 }
288                 read_threads[i] = (pthread_t) 0;
289         }
290         sfree (read_threads);
291         read_threads_num = 0;
292 } /* void stop_threads */
293
294 /*
295  * Public functions
296  */
297 void plugin_set_dir (const char *dir)
298 {
299         if (plugindir != NULL)
300                 free (plugindir);
301
302         if (dir == NULL)
303                 plugindir = NULL;
304         else if ((plugindir = strdup (dir)) == NULL)
305         {
306                 char errbuf[1024];
307                 ERROR ("strdup failed: %s",
308                                 sstrerror (errno, errbuf, sizeof (errbuf)));
309         }
310 }
311
312 #define BUFSIZE 512
313 int plugin_load (const char *type)
314 {
315         DIR  *dh;
316         const char *dir;
317         char  filename[BUFSIZE] = "";
318         char  typename[BUFSIZE];
319         int   typename_len;
320         int   ret;
321         struct stat    statbuf;
322         struct dirent *de;
323
324         DEBUG ("type = %s", type);
325
326         dir = plugin_get_dir ();
327         ret = 1;
328
329         /* `cpu' should not match `cpufreq'. To solve this we add `.so' to the
330          * type when matching the filename */
331         if (snprintf (typename, BUFSIZE, "%s.so", type) >= BUFSIZE)
332         {
333                 WARNING ("snprintf: truncated: `%s.so'", type);
334                 return (-1);
335         }
336         typename_len = strlen (typename);
337
338         if ((dh = opendir (dir)) == NULL)
339         {
340                 char errbuf[1024];
341                 ERROR ("opendir (%s): %s", dir,
342                                 sstrerror (errno, errbuf, sizeof (errbuf)));
343                 return (-1);
344         }
345
346         while ((de = readdir (dh)) != NULL)
347         {
348                 if (strncasecmp (de->d_name, typename, typename_len))
349                         continue;
350
351                 if (snprintf (filename, BUFSIZE, "%s/%s", dir, de->d_name) >= BUFSIZE)
352                 {
353                         WARNING ("snprintf: truncated: `%s/%s'", dir, de->d_name);
354                         continue;
355                 }
356
357                 if (lstat (filename, &statbuf) == -1)
358                 {
359                         char errbuf[1024];
360                         WARNING ("stat %s: %s", filename,
361                                         sstrerror (errno, errbuf, sizeof (errbuf)));
362                         continue;
363                 }
364                 else if (!S_ISREG (statbuf.st_mode))
365                 {
366                         /* don't follow symlinks */
367                         continue;
368                 }
369
370                 if (plugin_load_file (filename) == 0)
371                 {
372                         /* success */
373                         ret = 0;
374                         break;
375                 }
376                 else
377                 {
378                         fprintf (stderr, "Unable to load plugin %s.\n", type);
379                 }
380         }
381
382         closedir (dh);
383
384         if (filename[0] == '\0')
385                 fprintf (stderr, "Could not find plugin %s.\n", type);
386
387         return (ret);
388 }
389
390 /*
391  * The `register_*' functions follow
392  */
393 int plugin_register_config (const char *name,
394                 int (*callback) (const char *key, const char *val),
395                 const char **keys, int keys_num)
396 {
397         cf_register (name, callback, keys, keys_num);
398         return (0);
399 } /* int plugin_register_config */
400
401 int plugin_register_complex_config (const char *type,
402                 int (*callback) (oconfig_item_t *))
403 {
404         return (cf_register_complex (type, callback));
405 } /* int plugin_register_complex_config */
406
407 int plugin_register_init (const char *name,
408                 int (*callback) (void))
409 {
410         return (register_callback (&list_init, name, (void *) callback));
411 } /* plugin_register_init */
412
413 int plugin_register_read (const char *name,
414                 int (*callback) (void))
415 {
416         read_func_t *rf;
417
418         rf = (read_func_t *) malloc (sizeof (read_func_t));
419         if (rf == NULL)
420         {
421                 char errbuf[1024];
422                 ERROR ("plugin_register_read: malloc failed: %s",
423                                 sstrerror (errno, errbuf, sizeof (errbuf)));
424                 return (-1);
425         }
426
427         memset (rf, '\0', sizeof (read_func_t));
428         rf->wait_time = interval_g;
429         rf->wait_left = 0;
430         rf->callback = callback;
431         rf->needs_read = DONE;
432
433         return (register_callback (&list_read, name, (void *) rf));
434 } /* int plugin_register_read */
435
436 int plugin_register_write (const char *name,
437                 int (*callback) (const data_set_t *ds, const value_list_t *vl))
438 {
439         return (register_callback (&list_write, name, (void *) callback));
440 } /* int plugin_register_write */
441
442 int plugin_register_flush (const char *name, int (*callback) (const int))
443 {
444         return (register_callback (&list_flush, name, (void *) callback));
445 } /* int plugin_register_flush */
446
447 int plugin_register_shutdown (char *name,
448                 int (*callback) (void))
449 {
450         return (register_callback (&list_shutdown, name, (void *) callback));
451 } /* int plugin_register_shutdown */
452
453 int plugin_register_data_set (const data_set_t *ds)
454 {
455         data_set_t *ds_copy;
456         int i;
457
458         if ((data_sets != NULL)
459                         && (c_avl_get (data_sets, ds->type, NULL) == 0))
460         {
461                 NOTICE ("Replacing DS `%s' with another version.", ds->type);
462                 plugin_unregister_data_set (ds->type);
463         }
464         else if (data_sets == NULL)
465         {
466                 data_sets = c_avl_create ((int (*) (const void *, const void *)) strcmp);
467                 if (data_sets == NULL)
468                         return (-1);
469         }
470
471         ds_copy = (data_set_t *) malloc (sizeof (data_set_t));
472         if (ds_copy == NULL)
473                 return (-1);
474         memcpy(ds_copy, ds, sizeof (data_set_t));
475
476         ds_copy->ds = (data_source_t *) malloc (sizeof (data_source_t)
477                         * ds->ds_num);
478         if (ds_copy->ds == NULL)
479         {
480                 free (ds_copy);
481                 return (-1);
482         }
483
484         for (i = 0; i < ds->ds_num; i++)
485                 memcpy (ds_copy->ds + i, ds->ds + i, sizeof (data_source_t));
486
487         return (c_avl_insert (data_sets, (void *) ds_copy->type, (void *) ds_copy));
488 } /* int plugin_register_data_set */
489
490 int plugin_register_log (char *name,
491                 void (*callback) (int priority, const char *msg))
492 {
493         return (register_callback (&list_log, name, (void *) callback));
494 } /* int plugin_register_log */
495
496 int plugin_register_notification (const char *name,
497                 int (*callback) (const notification_t *notif))
498 {
499         return (register_callback (&list_notification, name, (void *) callback));
500 } /* int plugin_register_log */
501
502 int plugin_unregister_config (const char *name)
503 {
504         cf_unregister (name);
505         return (0);
506 } /* int plugin_unregister_config */
507
508 int plugin_unregister_complex_config (const char *name)
509 {
510         cf_unregister_complex (name);
511         return (0);
512 } /* int plugin_unregister_complex_config */
513
514 int plugin_unregister_init (const char *name)
515 {
516         return (plugin_unregister (list_init, name));
517 }
518
519 int plugin_unregister_read (const char *name)
520 {
521         llentry_t *e;
522
523         e = llist_search (list_read, name);
524
525         if (e == NULL)
526                 return (-1);
527
528         llist_remove (list_read, e);
529         free (e->value);
530         free (e->key);
531         llentry_destroy (e);
532
533         return (0);
534 }
535
536 int plugin_unregister_write (const char *name)
537 {
538         return (plugin_unregister (list_write, name));
539 }
540
541 int plugin_unregister_flush (const char *name)
542 {
543         return (plugin_unregister (list_flush, name));
544 }
545
546 int plugin_unregister_shutdown (const char *name)
547 {
548         return (plugin_unregister (list_shutdown, name));
549 }
550
551 int plugin_unregister_data_set (const char *name)
552 {
553         data_set_t *ds;
554
555         if (data_sets == NULL)
556                 return (-1);
557
558         if (c_avl_remove (data_sets, name, NULL, (void *) &ds) != 0)
559                 return (-1);
560
561         sfree (ds->ds);
562         sfree (ds);
563
564         return (0);
565 } /* int plugin_unregister_data_set */
566
567 int plugin_unregister_log (const char *name)
568 {
569         return (plugin_unregister (list_log, name));
570 }
571
572 int plugin_unregister_notification (const char *name)
573 {
574         return (plugin_unregister (list_notification, name));
575 }
576
577 void plugin_init_all (void)
578 {
579         int (*callback) (void);
580         llentry_t *le;
581         int status;
582
583         /* Init the value cache */
584         uc_init ();
585
586         if ((list_init == NULL) && (list_read == NULL))
587                 return;
588
589         /* Calling all init callbacks before checking if read callbacks
590          * are available allows the init callbacks to register the read
591          * callback. */
592         le = llist_head (list_init);
593         while (le != NULL)
594         {
595                 callback = (int (*) (void)) le->value;
596                 status = (*callback) ();
597
598                 if (status != 0)
599                 {
600                         ERROR ("Initialization of plugin `%s' "
601                                         "failed with status %i. "
602                                         "Plugin will be unloaded.",
603                                         le->key, status);
604                         /* Plugins that register read callbacks from the init
605                          * callback should take care of appropriate error
606                          * handling themselves. */
607                         /* FIXME: Unload _all_ functions */
608                         plugin_unregister_read (le->key);
609                 }
610
611                 le = le->next;
612         }
613
614         /* Start read-threads */
615         if (list_read != NULL)
616         {
617                 const char *rt;
618                 int num;
619                 rt = global_option_get ("ReadThreads");
620                 num = atoi (rt);
621                 start_threads ((num > 0) ? num : 5);
622         }
623 } /* void plugin_init_all */
624
625 void plugin_read_all (void)
626 {
627         llentry_t   *le;
628         read_func_t *rf;
629
630         uc_check_timeout ();
631
632         if (list_read == NULL)
633                 return;
634
635         pthread_mutex_lock (&read_lock);
636
637         le = llist_head (list_read);
638         while (le != NULL)
639         {
640                 rf = (read_func_t *) le->value;
641
642                 if (rf->needs_read != DONE)
643                 {
644                         le = le->next;
645                         continue;
646                 }
647
648                 if (rf->wait_left > 0)
649                         rf->wait_left -= interval_g;
650
651                 if (rf->wait_left <= 0)
652                 {
653                         rf->needs_read = TODO;
654                 }
655
656                 le = le->next;
657         }
658
659         DEBUG ("plugin: plugin_read_all: Signalling `read_cond'");
660         pthread_cond_broadcast (&read_cond);
661         pthread_mutex_unlock (&read_lock);
662 } /* void plugin_read_all */
663
664 int plugin_flush_one (int timeout, const char *name)
665 {
666         int (*callback) (int);
667         llentry_t *le;
668         int status;
669
670         if (list_flush == NULL)
671                 return (-1);
672
673         le = llist_search (list_flush, name);
674         if (le == NULL)
675                 return (-1);
676         callback = (int (*) (int)) le->value;
677
678         status = (*callback) (timeout);
679
680         return (status);
681 } /* int plugin_flush_ont */
682
683 void plugin_flush_all (int timeout)
684 {
685         int (*callback) (int);
686         llentry_t *le;
687
688         if (list_flush == NULL)
689                 return;
690
691         le = llist_head (list_flush);
692         while (le != NULL)
693         {
694                 callback = (int (*) (int)) le->value;
695                 le = le->next;
696
697                 (*callback) (timeout);
698         }
699 } /* void plugin_flush_all */
700
701 void plugin_shutdown_all (void)
702 {
703         int (*callback) (void);
704         llentry_t *le;
705
706         stop_threads ();
707
708         if (list_shutdown == NULL)
709                 return;
710
711         le = llist_head (list_shutdown);
712         while (le != NULL)
713         {
714                 callback = (int (*) (void)) le->value;
715
716                 /* Advance the pointer before calling the callback allows
717                  * shutdown functions to unregister themselves. If done the
718                  * other way around the memory `le' points to will be freed
719                  * after callback returns. */
720                 le = le->next;
721
722                 (*callback) ();
723         }
724 } /* void plugin_shutdown_all */
725
726 int plugin_dispatch_values (const char *name, value_list_t *vl)
727 {
728         int (*callback) (const data_set_t *, const value_list_t *);
729         data_set_t *ds;
730         llentry_t *le;
731
732         if (list_write == NULL)
733         {
734                 ERROR ("plugin_dispatch_values: No write callback has been "
735                                 "registered. Please load at least one plugin "
736                                 "that provides a write function.");
737                 return (-1);
738         }
739
740         if (data_sets == NULL)
741         {
742                 ERROR ("plugin_dispatch_values: No data sets registered. "
743                                 "Could the types database be read? Check "
744                                 "your `TypesDB' setting!");
745                 return (-1);
746         }
747
748         if (c_avl_get (data_sets, name, (void *) &ds) != 0)
749         {
750                 INFO ("plugin_dispatch_values: Dataset not found: %s", name);
751                 return (-1);
752         }
753
754         DEBUG ("plugin_dispatch_values: time = %u; interval = %i; "
755                         "host = %s; "
756                         "plugin = %s; plugin_instance = %s; "
757                         "type = %s; type_instance = %s;",
758                         (unsigned int) vl->time, vl->interval,
759                         vl->host,
760                         vl->plugin, vl->plugin_instance,
761                         ds->type, vl->type_instance);
762
763 #if COLLECT_DEBUG
764         assert (ds->ds_num == vl->values_len);
765 #else
766         if (ds->ds_num != vl->values_len)
767         {
768                 ERROR ("plugin_dispatch_values: ds->type = %s: "
769                                 "(ds->ds_num = %i) != "
770                                 "(vl->values_len = %i)",
771                                 ds->type, ds->ds_num, vl->values_len);
772                 return (-1);
773         }
774 #endif
775
776         escape_slashes (vl->host, sizeof (vl->host));
777         escape_slashes (vl->plugin, sizeof (vl->plugin));
778         escape_slashes (vl->plugin_instance, sizeof (vl->plugin_instance));
779         escape_slashes (vl->type_instance, sizeof (vl->type_instance));
780
781         /* Update the value cache */
782         uc_update (ds, vl);
783         ut_check_threshold (ds, vl);
784
785         le = llist_head (list_write);
786         while (le != NULL)
787         {
788                 callback = (int (*) (const data_set_t *, const value_list_t *)) le->value;
789                 (*callback) (ds, vl);
790
791                 le = le->next;
792         }
793
794         return (0);
795 } /* int plugin_dispatch_values */
796
797 int plugin_dispatch_notification (const notification_t *notif)
798 {
799         int (*callback) (const notification_t *);
800         llentry_t *le;
801         /* Possible TODO: Add flap detection here */
802
803         DEBUG ("plugin_dispatch_notification: severity = %i; message = %s; "
804                         "time = %u; host = %s;",
805                         notif->severity, notif->message,
806                         (unsigned int) notif->time, notif->host);
807
808         /* Nobody cares for notifications */
809         if (list_notification == NULL)
810                 return (-1);
811
812         le = llist_head (list_notification);
813         while (le != NULL)
814         {
815                 callback = (int (*) (const notification_t *)) le->value;
816                 (*callback) (notif);
817
818                 le = le->next;
819         }
820
821         return (0);
822 } /* int plugin_dispatch_notification */
823
824 void plugin_log (int level, const char *format, ...)
825 {
826         char msg[512];
827         va_list ap;
828
829         void (*callback) (int, const char *);
830         llentry_t *le;
831
832         if (list_log == NULL)
833                 return;
834
835 #if !COLLECT_DEBUG
836         if (level >= LOG_DEBUG)
837                 return;
838 #endif
839
840         va_start (ap, format);
841         vsnprintf (msg, 512, format, ap);
842         msg[511] = '\0';
843         va_end (ap);
844
845         le = llist_head (list_log);
846         while (le != NULL)
847         {
848                 callback = (void (*) (int, const char *)) le->value;
849                 (*callback) (level, msg);
850
851                 le = le->next;
852         }
853 } /* void plugin_log */
854
855 const data_set_t *plugin_get_ds (const char *name)
856 {
857         data_set_t *ds;
858
859         if (c_avl_get (data_sets, name, (void *) &ds) != 0)
860         {
861                 DEBUG ("No such dataset registered: %s", name);
862                 return (NULL);
863         }
864
865         return (ds);
866 } /* data_set_t *plugin_get_ds */