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