0d9474a05fad59e3f5dc1c0fa89039f4fce64eb6
[collectd.git] / src / perl.c
1 /**
2  * collectd - src/perl.c
3  * Copyright (C) 2007  Sebastian Harl
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  * Author:
19  *   Sebastian Harl <sh at tokkee.org>
20  **/
21
22 /*
23  * This plugin embeds a Perl interpreter into collectd and provides an
24  * interface for collectd plugins written in perl.
25  */
26
27 /* do not automatically get the thread specific perl interpreter */
28 #define PERL_NO_GET_CONTEXT
29
30 #include "collectd.h"
31
32 #include "configfile.h"
33
34 #include <EXTERN.h>
35 #include <perl.h>
36
37 #include <XSUB.h>
38
39 /* Some versions of Perl define their own version of DEBUG... :-/ */
40 #ifdef DEBUG
41 # undef DEBUG
42 #endif /* DEBUG */
43
44 /* ... while we want the definition found in plugin.h. */
45 #include "plugin.h"
46 #include "common.h"
47
48 #include <pthread.h>
49
50 #if !defined(USE_ITHREADS)
51 # error "Perl does not support ithreads!"
52 #endif /* !defined(USE_ITHREADS) */
53
54 /* clear the Perl sub's stack frame
55  * (this should only be used inside an XSUB) */
56 #define CLEAR_STACK_FRAME PL_stack_sp = PL_stack_base + *PL_markstack_ptr
57
58 #define PLUGIN_INIT     0
59 #define PLUGIN_READ     1
60 #define PLUGIN_WRITE    2
61 #define PLUGIN_SHUTDOWN 3
62 #define PLUGIN_LOG      4
63
64 #define PLUGIN_TYPES    5
65
66 #define PLUGIN_DATASET  255
67
68 #define log_debug(...) DEBUG ("perl: " __VA_ARGS__)
69 #define log_info(...) INFO ("perl: " __VA_ARGS__)
70 #define log_warn(...) WARNING ("perl: " __VA_ARGS__)
71 #define log_err(...) ERROR ("perl: " __VA_ARGS__)
72
73 /* this is defined in DynaLoader.a */
74 void boot_DynaLoader (PerlInterpreter *, CV *);
75
76 static XS (Collectd_plugin_register_ds);
77 static XS (Collectd_plugin_unregister_ds);
78 static XS (Collectd_plugin_dispatch_values);
79 static XS (Collectd_plugin_log);
80 static XS (Collectd_call_by_name);
81
82 /*
83  * private data types
84  */
85
86 typedef struct c_ithread_s {
87         /* the thread's Perl interpreter */
88         PerlInterpreter *interp;
89
90         /* double linked list of threads */
91         struct c_ithread_s *prev;
92         struct c_ithread_s *next;
93 } c_ithread_t;
94
95 typedef struct {
96         c_ithread_t *head;
97         c_ithread_t *tail;
98
99 #if COLLECT_DEBUG
100         /* some usage stats */
101         int number_of_threads;
102 #endif /* COLLECT_DEBUG */
103
104         pthread_mutex_t mutex;
105 } c_ithread_list_t;
106
107 /*
108  * private variables
109  */
110
111 /* if perl_threads != NULL perl_threads->head must
112  * point to the "base" thread */
113 static c_ithread_list_t *perl_threads = NULL;
114
115 /* the key used to store each pthread's ithread */
116 static pthread_key_t perl_thr_key;
117
118 static int    perl_argc = 0;
119 static char **perl_argv = NULL;
120
121 static char base_name[DATA_MAX_NAME_LEN] = "";
122
123 static struct {
124         char name[64];
125         XS ((*f));
126 } api[] =
127 {
128         { "Collectd::plugin_register_data_set",   Collectd_plugin_register_ds },
129         { "Collectd::plugin_unregister_data_set", Collectd_plugin_unregister_ds },
130         { "Collectd::plugin_dispatch_values",     Collectd_plugin_dispatch_values },
131         { "Collectd::plugin_log",                 Collectd_plugin_log },
132         { "Collectd::call_by_name",               Collectd_call_by_name },
133         { "", NULL }
134 };
135
136 struct {
137         char name[64];
138         int  value;
139 } constants[] =
140 {
141         { "Collectd::TYPE_INIT",       PLUGIN_INIT },
142         { "Collectd::TYPE_READ",       PLUGIN_READ },
143         { "Collectd::TYPE_WRITE",      PLUGIN_WRITE },
144         { "Collectd::TYPE_SHUTDOWN",   PLUGIN_SHUTDOWN },
145         { "Collectd::TYPE_LOG",        PLUGIN_LOG },
146         { "Collectd::TYPE_DATASET",    PLUGIN_DATASET },
147         { "Collectd::DS_TYPE_COUNTER", DS_TYPE_COUNTER },
148         { "Collectd::DS_TYPE_GAUGE",   DS_TYPE_GAUGE },
149         { "Collectd::LOG_ERR",         LOG_ERR },
150         { "Collectd::LOG_WARNING",     LOG_WARNING },
151         { "Collectd::LOG_NOTICE",      LOG_NOTICE },
152         { "Collectd::LOG_INFO",        LOG_INFO },
153         { "Collectd::LOG_DEBUG",       LOG_DEBUG },
154         { "", 0 }
155 };
156
157 /*
158  * Helper functions for data type conversion.
159  */
160
161 /*
162  * data source:
163  * [
164  *   {
165  *     name => $ds_name,
166  *     type => $ds_type,
167  *     min  => $ds_min,
168  *     max  => $ds_max
169  *   },
170  *   ...
171  * ]
172  */
173 static int hv2data_source (pTHX_ HV *hash, data_source_t *ds)
174 {
175         SV **tmp = NULL;
176
177         if ((NULL == hash) || (NULL == ds))
178                 return -1;
179
180         if (NULL != (tmp = hv_fetch (hash, "name", 4, 0))) {
181                 strncpy (ds->name, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
182                 ds->name[DATA_MAX_NAME_LEN - 1] = '\0';
183         }
184         else {
185                 log_err ("hv2data_source: No DS name given.");
186                 return -1;
187         }
188
189         if (NULL != (tmp = hv_fetch (hash, "type", 4, 0))) {
190                 ds->type = SvIV (*tmp);
191
192                 if ((DS_TYPE_COUNTER != ds->type) && (DS_TYPE_GAUGE != ds->type)) {
193                         log_err ("hv2data_source: Invalid DS type.");
194                         return -1;
195                 }
196         }
197         else {
198                 ds->type = DS_TYPE_COUNTER;
199         }
200
201         if (NULL != (tmp = hv_fetch (hash, "min", 3, 0)))
202                 ds->min = SvNV (*tmp);
203         else
204                 ds->min = NAN;
205
206         if (NULL != (tmp = hv_fetch (hash, "max", 3, 0)))
207                 ds->max = SvNV (*tmp);
208         else
209                 ds->max = NAN;
210         return 0;
211 } /* static data_source_t *hv2data_source (HV *) */
212
213 static int av2value (pTHX_ char *name, AV *array, value_t *value, int len)
214 {
215         const data_set_t *ds;
216
217         int i = 0;
218
219         if ((NULL == name) || (NULL == array) || (NULL == value))
220                 return -1;
221
222         if (av_len (array) < len - 1)
223                 len = av_len (array) + 1;
224
225         if (0 >= len)
226                 return -1;
227
228         ds = plugin_get_ds (name);
229         if (NULL == ds) {
230                 log_err ("av2value: Unknown dataset \"%s\"", name);
231                 return -1;
232         }
233
234         if (ds->ds_num < len) {
235                 log_warn ("av2value: Value length exceeds data set length.");
236                 len = ds->ds_num;
237         }
238
239         for (i = 0; i < len; ++i) {
240                 SV **tmp = av_fetch (array, i, 0);
241
242                 if (NULL != tmp) {
243                         if (DS_TYPE_COUNTER == ds->ds[i].type)
244                                 value[i].counter = SvIV (*tmp);
245                         else
246                                 value[i].gauge = SvNV (*tmp);
247                 }
248                 else {
249                         return -1;
250                 }
251         }
252         return len;
253 } /* static int av2value (char *, AV *, value_t *, int) */
254
255 static int data_set2av (pTHX_ data_set_t *ds, AV *array)
256 {
257         int i = 0;
258
259         if ((NULL == ds) || (NULL == array))
260                 return -1;
261
262         av_extend (array, ds->ds_num);
263
264         for (i = 0; i < ds->ds_num; ++i) {
265                 HV *source = newHV ();
266
267                 if (NULL == hv_store (source, "name", 4,
268                                 newSVpv (ds->ds[i].name, 0), 0))
269                         return -1;
270
271                 if (NULL == hv_store (source, "type", 4, newSViv (ds->ds[i].type), 0))
272                         return -1;
273
274                 if (! isnan (ds->ds[i].min))
275                         if (NULL == hv_store (source, "min", 3,
276                                         newSVnv (ds->ds[i].min), 0))
277                                 return -1;
278
279                 if (! isnan (ds->ds[i].max))
280                         if (NULL == hv_store (source, "max", 3,
281                                         newSVnv (ds->ds[i].max), 0))
282                                 return -1;
283
284                 if (NULL == av_store (array, i, newRV_noinc ((SV *)source)))
285                         return -1;
286         }
287         return 0;
288 } /* static int data_set2av (data_set_t *, AV *) */
289
290 static int value_list2hv (pTHX_ value_list_t *vl, data_set_t *ds, HV *hash)
291 {
292         AV *values = NULL;
293
294         int i   = 0;
295         int len = 0;
296
297         if ((NULL == vl) || (NULL == ds) || (NULL == hash))
298                 return -1;
299
300         len = vl->values_len;
301
302         if (ds->ds_num < len) {
303                 log_warn ("value2av: Value length exceeds data set length.");
304                 len = ds->ds_num;
305         }
306
307         values = newAV ();
308         av_extend (values, len - 1);
309
310         for (i = 0; i < len; ++i) {
311                 SV *val = NULL;
312
313                 if (DS_TYPE_COUNTER == ds->ds[i].type)
314                         val = newSViv (vl->values[i].counter);
315                 else
316                         val = newSVnv (vl->values[i].gauge);
317
318                 if (NULL == av_store (values, i, val)) {
319                         av_undef (values);
320                         return -1;
321                 }
322         }
323
324         if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0))
325                 return -1;
326
327         if (0 != vl->time)
328                 if (NULL == hv_store (hash, "time", 4, newSViv (vl->time), 0))
329                         return -1;
330
331         if ('\0' != vl->host[0])
332                 if (NULL == hv_store (hash, "host", 4, newSVpv (vl->host, 0), 0))
333                         return -1;
334
335         if ('\0' != vl->plugin[0])
336                 if (NULL == hv_store (hash, "plugin", 6, newSVpv (vl->plugin, 0), 0))
337                         return -1;
338
339         if ('\0' != vl->plugin_instance[0])
340                 if (NULL == hv_store (hash, "plugin_instance", 15,
341                                 newSVpv (vl->plugin_instance, 0), 0))
342                         return -1;
343
344         if ('\0' != vl->type_instance[0])
345                 if (NULL == hv_store (hash, "type_instance", 13,
346                                 newSVpv (vl->type_instance, 0), 0))
347                         return -1;
348         return 0;
349 } /* static int value2av (value_list_t *, data_set_t *, HV *) */
350
351 /*
352  * Internal functions.
353  */
354
355 static char *get_module_name (char *buf, size_t buf_len, const char *module) {
356         int status = 0;
357         if (base_name[0] == '\0')
358                 status = snprintf (buf, buf_len, "%s", module);
359         else
360                 status = snprintf (buf, buf_len, "%s::%s", base_name, module);
361         if ((status < 0) || (status >= buf_len))
362                 return (NULL);
363         buf[buf_len - 1] = '\0';
364         return (buf);
365 } /* char *get_module_name */
366
367 /*
368  * Add a plugin's data set definition.
369  */
370 static int pplugin_register_data_set (pTHX_ char *name, AV *dataset)
371 {
372         int len = -1;
373         int i   = 0;
374
375         data_source_t *ds  = NULL;
376         data_set_t    *set = NULL;
377
378         if ((NULL == name) || (NULL == dataset))
379                 return -1;
380
381         len = av_len (dataset);
382
383         if (-1 == len)
384                 return -1;
385
386         ds  = (data_source_t *)smalloc ((len + 1) * sizeof (data_source_t));
387         set = (data_set_t *)smalloc (sizeof (data_set_t));
388
389         for (i = 0; i <= len; ++i) {
390                 SV **elem = av_fetch (dataset, i, 0);
391
392                 if (NULL == elem)
393                         return -1;
394
395                 if (! (SvROK (*elem) && (SVt_PVHV == SvTYPE (SvRV (*elem))))) {
396                         log_err ("pplugin_register_data_set: Invalid data source.");
397                         return -1;
398                 }
399
400                 if (-1 == hv2data_source (aTHX_ (HV *)SvRV (*elem), &ds[i]))
401                         return -1;
402
403                 log_debug ("pplugin_register_data_set: "
404                                 "DS.name = \"%s\", DS.type = %i, DS.min = %f, DS.max = %f",
405                                 ds[i].name, ds[i].type, ds[i].min, ds[i].max);
406         }
407
408         strncpy (set->type, name, DATA_MAX_NAME_LEN);
409         set->type[DATA_MAX_NAME_LEN - 1] = '\0';
410
411         set->ds_num = len + 1;
412         set->ds = ds;
413         return plugin_register_data_set (set);
414 } /* static int pplugin_register_data_set (char *, SV *) */
415
416 /*
417  * Remove a plugin's data set definition.
418  */
419 static int pplugin_unregister_data_set (char *name)
420 {
421         if (NULL == name)
422                 return 0;
423         return plugin_unregister_data_set (name);
424 } /* static int pplugin_unregister_data_set (char *) */
425
426 /*
427  * Submit the values to the write functions.
428  *
429  * value list:
430  * {
431  *   values => [ @values ],
432  *   time   => $time,
433  *   host   => $host,
434  *   plugin => $plugin,
435  *   plugin_instance => $pinstance,
436  *   type_instance   => $tinstance,
437  * }
438  */
439 static int pplugin_dispatch_values (pTHX_ char *name, HV *values)
440 {
441         value_list_t list = VALUE_LIST_INIT;
442         value_t      *val = NULL;
443
444         SV **tmp = NULL;
445
446         int ret = 0;
447
448         if ((NULL == name) || (NULL == values))
449                 return -1;
450
451         if ((NULL == (tmp = hv_fetch (values, "values", 6, 0)))
452                         || (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp)))))) {
453                 log_err ("pplugin_dispatch_values: No valid values given.");
454                 return -1;
455         }
456
457         {
458                 AV  *array = (AV *)SvRV (*tmp);
459                 int len    = av_len (array) + 1;
460
461                 if (len <= 0)
462                         return -1;
463
464                 val = (value_t *)smalloc (len * sizeof (value_t));
465
466                 list.values_len = av2value (aTHX_ name, (AV *)SvRV (*tmp), val, len);
467                 list.values = val;
468
469                 if (-1 == list.values_len) {
470                         sfree (val);
471                         return -1;
472                 }
473         }
474
475         if (NULL != (tmp = hv_fetch (values, "time", 4, 0))) {
476                 list.time = (time_t)SvIV (*tmp);
477         }
478         else {
479                 list.time = time (NULL);
480         }
481
482         if (NULL != (tmp = hv_fetch (values, "host", 4, 0))) {
483                 strncpy (list.host, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
484                 list.host[DATA_MAX_NAME_LEN - 1] = '\0';
485         }
486         else {
487                 strcpy (list.host, hostname_g);
488         }
489
490         if (NULL != (tmp = hv_fetch (values, "plugin", 6, 0))) {
491                 strncpy (list.plugin, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
492                 list.plugin[DATA_MAX_NAME_LEN - 1] = '\0';
493         }
494
495         if (NULL != (tmp = hv_fetch (values,
496                         "plugin_instance", 15, 0))) {
497                 strncpy (list.plugin_instance, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
498                 list.plugin_instance[DATA_MAX_NAME_LEN - 1] = '\0';
499         }
500
501         if (NULL != (tmp = hv_fetch (values, "type_instance", 13, 0))) {
502                 strncpy (list.type_instance, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
503                 list.type_instance[DATA_MAX_NAME_LEN - 1] = '\0';
504         }
505
506         ret = plugin_dispatch_values (name, &list);
507
508         sfree (val);
509         return ret;
510 } /* static int pplugin_dispatch_values (char *, HV *) */
511
512 /*
513  * Call all working functions of the given type.
514  */
515 static int pplugin_call_all (pTHX_ int type, ...)
516 {
517         int retvals = 0;
518
519         va_list ap;
520         int ret = 0;
521
522         dSP;
523
524         if ((type < 0) || (type >= PLUGIN_TYPES))
525                 return -1;
526
527         va_start (ap, type);
528
529         ENTER;
530         SAVETMPS;
531
532         PUSHMARK (SP);
533
534         XPUSHs (sv_2mortal (newSViv ((IV)type)));
535
536         if (PLUGIN_WRITE == type) {
537                 /*
538                  * $_[0] = $plugin_type;
539                  *
540                  * $_[1] =
541                  * [
542                  *   {
543                  *     name => $ds_name,
544                  *     type => $ds_type,
545                  *     min  => $ds_min,
546                  *     max  => $ds_max
547                  *   },
548                  *   ...
549                  * ];
550                  *
551                  * $_[2] =
552                  * {
553                  *   values => [ $v1, ... ],
554                  *   time   => $time,
555                  *   host   => $hostname,
556                  *   plugin => $plugin,
557                  *   plugin_instance => $instance,
558                  *   type_instance   => $type_instance
559                  * };
560                  */
561                 data_set_t   *ds;
562                 value_list_t *vl;
563
564                 AV *pds = newAV ();
565                 HV *pvl = newHV ();
566
567                 ds = va_arg (ap, data_set_t *);
568                 vl = va_arg (ap, value_list_t *);
569
570                 if (-1 == data_set2av (aTHX_ ds, pds))
571                         return -1;
572
573                 if (-1 == value_list2hv (aTHX_ vl, ds, pvl))
574                         return -1;
575
576                 XPUSHs (sv_2mortal (newSVpv (ds->type, 0)));
577                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
578                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
579         }
580         else if (PLUGIN_LOG == type) {
581                 /*
582                  * $_[0] = $level;
583                  *
584                  * $_[1] = $message;
585                  */
586                 XPUSHs (sv_2mortal (newSViv (va_arg (ap, int))));
587                 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
588         }
589
590         PUTBACK;
591
592         retvals = call_pv ("Collectd::plugin_call_all", G_SCALAR);
593
594         SPAGAIN;
595         if (0 < retvals) {
596                 SV *tmp = POPs;
597                 if (! SvTRUE (tmp))
598                         ret = -1;
599         }
600
601         PUTBACK;
602         FREETMPS;
603         LEAVE;
604
605         va_end (ap);
606         return ret;
607 } /* static int pplugin_call_all (int, ...) */
608
609 /*
610  * Exported Perl API.
611  */
612
613 /*
614  * Collectd::plugin_register_data_set (type, dataset).
615  *
616  * type:
617  *   type of the dataset
618  *
619  * dataset:
620  *   dataset to be registered
621  */
622 static XS (Collectd_plugin_register_ds)
623 {
624         SV  *data = NULL;
625         int ret   = 0;
626
627         dXSARGS;
628
629         if (2 != items) {
630                 log_err ("Usage: Collectd::plugin_register_data_set(type, dataset)");
631                 XSRETURN_EMPTY;
632         }
633
634         log_debug ("Collectd::plugin_register_data_set: "
635                         "type = \"%s\", dataset = \"%s\"",
636                         SvPV_nolen (ST (0)), SvPV_nolen (ST (1)));
637
638         data = ST (1);
639
640         if (SvROK (data) && (SVt_PVAV == SvTYPE (SvRV (data)))) {
641                 ret = pplugin_register_data_set (aTHX_ SvPV_nolen (ST (0)),
642                                 (AV *)SvRV (data));
643         }
644         else {
645                 log_err ("Collectd::plugin_register_data_set: Invalid data.");
646                 XSRETURN_EMPTY;
647         }
648
649         if (0 == ret)
650                 XSRETURN_YES;
651         else
652                 XSRETURN_EMPTY;
653 } /* static XS (Collectd_plugin_register_ds) */
654
655 /*
656  * Collectd::plugin_unregister_data_set (type).
657  *
658  * type:
659  *   type of the dataset
660  */
661 static XS (Collectd_plugin_unregister_ds)
662 {
663         dXSARGS;
664
665         if (1 != items) {
666                 log_err ("Usage: Collectd::plugin_unregister_data_set(type)");
667                 XSRETURN_EMPTY;
668         }
669
670         log_debug ("Collectd::plugin_unregister_data_set: type = \"%s\"",
671                         SvPV_nolen (ST (0)));
672
673         if (0 == pplugin_unregister_data_set (SvPV_nolen (ST (1))))
674                 XSRETURN_YES;
675         else
676                 XSRETURN_EMPTY;
677 } /* static XS (Collectd_plugin_register_ds) */
678
679 /*
680  * Collectd::plugin_dispatch_values (name, values).
681  *
682  * name:
683  *   name of the plugin
684  *
685  * values:
686  *   value list to submit
687  */
688 static XS (Collectd_plugin_dispatch_values)
689 {
690         SV *values = NULL;
691
692         int ret = 0;
693
694         dXSARGS;
695
696         if (2 != items) {
697                 log_err ("Usage: Collectd::plugin_dispatch_values(name, values)");
698                 XSRETURN_EMPTY;
699         }
700
701         log_debug ("Collectd::plugin_dispatch_values: "
702                         "name = \"%s\", values=\"%s\"",
703                         SvPV_nolen (ST (0)), SvPV_nolen (ST (1)));
704
705         values = ST (1);
706
707         if (! (SvROK (values) && (SVt_PVHV == SvTYPE (SvRV (values))))) {
708                 log_err ("Collectd::plugin_dispatch_values: Invalid values.");
709                 XSRETURN_EMPTY;
710         }
711
712         if ((NULL == ST (0)) || (NULL == values))
713                 XSRETURN_EMPTY;
714
715         ret = pplugin_dispatch_values (aTHX_ SvPV_nolen (ST (0)),
716                         (HV *)SvRV (values));
717
718         if (0 == ret)
719                 XSRETURN_YES;
720         else
721                 XSRETURN_EMPTY;
722 } /* static XS (Collectd_plugin_dispatch_values) */
723
724 /*
725  * Collectd::plugin_log (level, message).
726  *
727  * level:
728  *   log level (LOG_DEBUG, ... LOG_ERR)
729  *
730  * message:
731  *   log message
732  */
733 static XS (Collectd_plugin_log)
734 {
735         dXSARGS;
736
737         if (2 != items) {
738                 log_err ("Usage: Collectd::plugin_log(level, message)");
739                 XSRETURN_EMPTY;
740         }
741
742         plugin_log (SvIV (ST (0)), SvPV_nolen (ST (1)));
743         XSRETURN_YES;
744 } /* static XS (Collectd_plugin_log) */
745
746 /*
747  * Collectd::call_by_name (...).
748  *
749  * Call a Perl sub identified by its name passed through $Collectd::cb_name.
750  */
751 static XS (Collectd_call_by_name)
752 {
753         SV   *tmp  = NULL;
754         char *name = NULL;
755
756         if (NULL == (tmp = get_sv ("Collectd::cb_name", 0))) {
757                 sv_setpv (get_sv ("@", 1), "cb_name has not been set");
758                 CLEAR_STACK_FRAME;
759                 return;
760         }
761
762         name = SvPV_nolen (tmp);
763
764         if (NULL == get_cv (name, 0)) {
765                 sv_setpvf (get_sv ("@", 1), "unknown callback \"%s\"", name);
766                 CLEAR_STACK_FRAME;
767                 return;
768         }
769
770         /* simply pass on the subroutine call without touching the stack,
771          * thus leaving any arguments and return values in place */
772         call_pv (name, 0);
773 } /* static XS (Collectd_call_by_name) */
774
775 /*
776  * collectd's perl interpreter based thread implementation.
777  *
778  * This has been inspired by Perl's ithreads introduced in version 5.6.0.
779  */
780
781 /* must be called with perl_threads->mutex locked */
782 static void c_ithread_destroy (c_ithread_t *ithread)
783 {
784         dTHXa (ithread->interp);
785
786         assert (NULL != perl_threads);
787
788         PERL_SET_CONTEXT (aTHX);
789         log_debug ("Shutting down Perl interpreter %p...", aTHX);
790
791 #if COLLECT_DEBUG
792         sv_report_used ();
793
794         --perl_threads->number_of_threads;
795 #endif /* COLLECT_DEBUG */
796
797         perl_destruct (aTHX);
798         perl_free (aTHX);
799
800         if (NULL == ithread->prev)
801                 perl_threads->head = ithread->next;
802         else
803                 ithread->prev->next = ithread->next;
804
805         if (NULL == ithread->next)
806                 perl_threads->tail = ithread->prev;
807         else
808                 ithread->next->prev = ithread->prev;
809
810         sfree (ithread);
811         return;
812 } /* static void c_ithread_destroy (c_ithread_t *) */
813
814 static void c_ithread_destructor (void *arg)
815 {
816         c_ithread_t *ithread = (c_ithread_t *)arg;
817         c_ithread_t *t = NULL;
818
819         if (NULL == perl_threads)
820                 return;
821
822         pthread_mutex_lock (&perl_threads->mutex);
823
824         for (t = perl_threads->head; NULL != t; t = t->next)
825                 if (t == ithread)
826                         break;
827
828         /* the ithread no longer exists */
829         if (NULL == t)
830                 return;
831
832         c_ithread_destroy (ithread);
833
834         pthread_mutex_unlock (&perl_threads->mutex);
835         return;
836 } /* static void c_ithread_destructor (void *) */
837
838 /* must be called with perl_threads->mutex locked */
839 static c_ithread_t *c_ithread_create (PerlInterpreter *base)
840 {
841         c_ithread_t *t = NULL;
842         dTHXa (NULL);
843
844         assert (NULL != perl_threads);
845
846         t = (c_ithread_t *)smalloc (sizeof (c_ithread_t));
847         memset (t, 0, sizeof (c_ithread_t));
848
849         t->interp = (NULL == base)
850                 ? NULL
851                 : perl_clone (base, CLONEf_KEEP_PTR_TABLE);
852
853         aTHX = t->interp;
854
855         if (NULL != base) {
856                 av_clear (PL_endav);
857                 av_undef (PL_endav);
858                 PL_endav = Nullav;
859         }
860
861 #if COLLECT_DEBUG
862         ++perl_threads->number_of_threads;
863 #endif /* COLLECT_DEBUG */
864
865         t->next = NULL;
866
867         if (NULL == perl_threads->tail) {
868                 perl_threads->head = t;
869                 t->prev = NULL;
870         }
871         else {
872                 perl_threads->tail->next = t;
873                 t->prev = perl_threads->tail;
874         }
875
876         perl_threads->tail = t;
877
878         pthread_setspecific (perl_thr_key, (const void *)t);
879         return t;
880 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
881
882 /*
883  * Interface to collectd.
884  */
885
886 static int perl_init (void)
887 {
888         dTHX;
889
890         if (NULL == perl_threads)
891                 return 0;
892
893         if (NULL == aTHX) {
894                 c_ithread_t *t = NULL;
895
896                 pthread_mutex_lock (&perl_threads->mutex);
897                 t = c_ithread_create (perl_threads->head->interp);
898                 pthread_mutex_unlock (&perl_threads->mutex);
899
900                 aTHX = t->interp;
901         }
902
903         log_debug ("perl_init: c_ithread: interp = %p (active threads: %i)",
904                         aTHX, perl_threads->number_of_threads);
905         return pplugin_call_all (aTHX_ PLUGIN_INIT);
906 } /* static int perl_init (void) */
907
908 static int perl_read (void)
909 {
910         dTHX;
911
912         if (NULL == perl_threads)
913                 return 0;
914
915         if (NULL == aTHX) {
916                 c_ithread_t *t = NULL;
917
918                 pthread_mutex_lock (&perl_threads->mutex);
919                 t = c_ithread_create (perl_threads->head->interp);
920                 pthread_mutex_unlock (&perl_threads->mutex);
921
922                 aTHX = t->interp;
923         }
924
925         log_debug ("perl_read: c_ithread: interp = %p (active threads: %i)",
926                         aTHX, perl_threads->number_of_threads);
927         return pplugin_call_all (aTHX_ PLUGIN_READ);
928 } /* static int perl_read (void) */
929
930 static int perl_write (const data_set_t *ds, const value_list_t *vl)
931 {
932         dTHX;
933
934         if (NULL == perl_threads)
935                 return 0;
936
937         if (NULL == aTHX) {
938                 c_ithread_t *t = NULL;
939
940                 pthread_mutex_lock (&perl_threads->mutex);
941                 t = c_ithread_create (perl_threads->head->interp);
942                 pthread_mutex_unlock (&perl_threads->mutex);
943
944                 aTHX = t->interp;
945         }
946
947         log_debug ("perl_write: c_ithread: interp = %p (active threads: %i)",
948                         aTHX, perl_threads->number_of_threads);
949         return pplugin_call_all (aTHX_ PLUGIN_WRITE, ds, vl);
950 } /* static int perl_write (const data_set_t *, const value_list_t *) */
951
952 static void perl_log (int level, const char *msg)
953 {
954         dTHX;
955
956         if (NULL == perl_threads)
957                 return;
958
959         if (NULL == aTHX) {
960                 c_ithread_t *t = NULL;
961
962                 pthread_mutex_lock (&perl_threads->mutex);
963                 t = c_ithread_create (perl_threads->head->interp);
964                 pthread_mutex_unlock (&perl_threads->mutex);
965
966                 aTHX = t->interp;
967         }
968
969         pplugin_call_all (aTHX_ PLUGIN_LOG, level, msg);
970         return;
971 } /* static void perl_log (int, const char *) */
972
973 static int perl_shutdown (void)
974 {
975         c_ithread_t *t = NULL;
976
977         int ret = 0;
978
979         dTHX;
980
981         plugin_unregister_complex_config ("perl");
982
983         if (NULL == perl_threads)
984                 return 0;
985
986         if (NULL == aTHX) {
987                 c_ithread_t *t = NULL;
988
989                 pthread_mutex_lock (&perl_threads->mutex);
990                 t = c_ithread_create (perl_threads->head->interp);
991                 pthread_mutex_unlock (&perl_threads->mutex);
992
993                 aTHX = t->interp;
994         }
995
996         log_debug ("perl_shutdown: c_ithread: interp = %p (active threads: %i)",
997                         aTHX, perl_threads->number_of_threads);
998
999         plugin_unregister_log ("perl");
1000         plugin_unregister_init ("perl");
1001         plugin_unregister_read ("perl");
1002         plugin_unregister_write ("perl");
1003
1004         ret = pplugin_call_all (aTHX_ PLUGIN_SHUTDOWN);
1005
1006         pthread_mutex_lock (&perl_threads->mutex);
1007         t = perl_threads->tail;
1008
1009         while (NULL != t) {
1010                 c_ithread_t *thr = t;
1011
1012                 /* the pointer has to be advanced before destroying
1013                  * the thread as this will free the memory */
1014                 t = t->prev;
1015
1016                 c_ithread_destroy (thr);
1017         }
1018
1019         pthread_mutex_unlock (&perl_threads->mutex);
1020         pthread_mutex_destroy (&perl_threads->mutex);
1021
1022         sfree (perl_threads);
1023
1024         pthread_key_delete (perl_thr_key);
1025
1026         PERL_SYS_TERM ();
1027
1028         plugin_unregister_shutdown ("perl");
1029         return ret;
1030 } /* static void perl_shutdown (void) */
1031
1032 /* bootstrap the Collectd module */
1033 static void xs_init (pTHX)
1034 {
1035         HV   *stash = NULL;
1036         char *file  = __FILE__;
1037
1038         int i = 0;
1039
1040         dXSUB_SYS;
1041
1042         /* enable usage of Perl modules using shared libraries */
1043         newXS ("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
1044
1045         /* register API */
1046         for (i = 0; NULL != api[i].f; ++i)
1047                 newXS (api[i].name, api[i].f, file);
1048
1049         stash = gv_stashpv ("Collectd", 1);
1050
1051         /* export "constants" */
1052         for (i = 0; '\0' != constants[i].name[0]; ++i)
1053                 newCONSTSUB (stash, constants[i].name, newSViv (constants[i].value));
1054         return;
1055 } /* static void xs_init (pTHX) */
1056
1057 /* Initialize the global Perl interpreter. */
1058 static int init_pi (int argc, char **argv)
1059 {
1060         dTHXa (NULL);
1061
1062         if (NULL != perl_threads)
1063                 return 0;
1064
1065         log_info ("Initializing Perl interpreter...");
1066 #if COLLECT_DEBUG
1067         {
1068                 int i = 0;
1069
1070                 for (i = 0; i < argc; ++i)
1071                         log_debug ("argv[%i] = \"%s\"", i, argv[i]);
1072         }
1073 #endif /* COLLECT_DEBUG */
1074
1075         if (0 != pthread_key_create (&perl_thr_key, c_ithread_destructor)) {
1076                 log_err ("init_pi: pthread_key_create failed");
1077
1078                 /* this must not happen - cowardly giving up if it does */
1079                 exit (1);
1080         }
1081
1082         PERL_SYS_INIT3 (&argc, &argv, &environ);
1083
1084         perl_threads = (c_ithread_list_t *)smalloc (sizeof (c_ithread_list_t));
1085         memset (perl_threads, 0, sizeof (c_ithread_list_t));
1086
1087         pthread_mutex_init (&perl_threads->mutex, NULL);
1088         /* locking the mutex should not be necessary at this point
1089          * but let's just do it for the sake of completeness */
1090         pthread_mutex_lock (&perl_threads->mutex);
1091
1092         perl_threads->head = c_ithread_create (NULL);
1093         perl_threads->tail = perl_threads->head;
1094
1095         if (NULL == (perl_threads->head->interp = perl_alloc ())) {
1096                 log_err ("init_pi: Not enough memory.");
1097                 exit (3);
1098         }
1099
1100         aTHX = perl_threads->head->interp;
1101         pthread_mutex_unlock (&perl_threads->mutex);
1102
1103         perl_construct (aTHX);
1104
1105         PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
1106
1107         if (0 != perl_parse (aTHX_ xs_init, argc, argv, NULL)) {
1108                 log_err ("init_pi: Unable to bootstrap Collectd.");
1109                 exit (1);
1110         }
1111
1112         /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
1113         sv_setpv (get_sv ("0", 0), "collectd");
1114
1115         perl_run (aTHX);
1116
1117         plugin_register_log ("perl", perl_log);
1118         plugin_register_init ("perl", perl_init);
1119
1120         plugin_register_read ("perl", perl_read);
1121
1122         plugin_register_write ("perl", perl_write);
1123         plugin_register_shutdown ("perl", perl_shutdown);
1124         return 0;
1125 } /* static int init_pi (const char **, const int) */
1126
1127 /*
1128  * LoadPlugin "<Plugin>"
1129  */
1130 static int perl_config_loadplugin (pTHX_ oconfig_item_t *ci)
1131 {
1132         char module_name[DATA_MAX_NAME_LEN];
1133
1134         char *value = NULL;
1135
1136         if ((0 != ci->children_num) || (1 != ci->values_num)
1137                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1138                 log_err ("LoadPlugin expects a single string argument.");
1139                 return 1;
1140         }
1141
1142         value = ci->values[0].value.string;
1143
1144         if (NULL == get_module_name (module_name, sizeof (module_name), value)) {
1145                 log_err ("Invalid module name %s", value);
1146                 return (1);
1147         }
1148
1149         init_pi (perl_argc, perl_argv);
1150         assert (NULL != perl_threads);
1151         assert (NULL != perl_threads->head);
1152
1153         aTHX = perl_threads->head->interp;
1154
1155         log_debug ("perl_config: loading perl plugin \"%s\"", value);
1156         load_module (PERL_LOADMOD_NOIMPORT,
1157                         newSVpv (module_name, strlen (module_name)), Nullsv);
1158         return 0;
1159 } /* static int perl_config_loadplugin (oconfig_item_it *) */
1160
1161 /*
1162  * BaseName "<Name>"
1163  */
1164 static int perl_config_basename (pTHX_ oconfig_item_t *ci)
1165 {
1166         char *value = NULL;
1167
1168         if ((0 != ci->children_num) || (1 != ci->values_num)
1169                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1170                 log_err ("BaseName expects a single string argument.");
1171                 return 1;
1172         }
1173
1174         value = ci->values[0].value.string;
1175
1176         log_debug ("perl_config: Setting plugin basename to \"%s\"", value);
1177         strncpy (base_name, value, sizeof (base_name));
1178         base_name[sizeof (base_name) - 1] = '\0';
1179         return 0;
1180 } /* static int perl_config_basename (oconfig_item_it *) */
1181
1182 /*
1183  * EnableDebugger "<Package>"|""
1184  */
1185 static int perl_config_enabledebugger (pTHX_ oconfig_item_t *ci)
1186 {
1187         char *value = NULL;
1188
1189         if ((0 != ci->children_num) || (1 != ci->values_num)
1190                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1191                 log_err ("EnableDebugger expects a single string argument.");
1192                 return 1;
1193         }
1194
1195         value = ci->values[0].value.string;
1196
1197         perl_argv = (char **)realloc (perl_argv,
1198                         (++perl_argc + 1) * sizeof (char *));
1199
1200         if (NULL == perl_argv) {
1201                 log_err ("perl_config: Not enough memory.");
1202                 exit (3);
1203         }
1204
1205         if ('\0' == value[0]) {
1206                 perl_argv[perl_argc - 1] = "-d";
1207         }
1208         else {
1209                 perl_argv[perl_argc - 1] = (char *)smalloc (strlen (value) + 4);
1210                 sstrncpy (perl_argv[perl_argc - 1], "-d:", 4);
1211                 sstrncpy (perl_argv[perl_argc - 1] + 3, value, strlen (value) + 1);
1212         }
1213
1214         perl_argv[perl_argc] = NULL;
1215         return 0;
1216 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
1217
1218 /*
1219  * IncludeDir "<Dir>"
1220  */
1221 static int perl_config_includedir (pTHX_ oconfig_item_t *ci)
1222 {
1223         char *value = NULL;
1224
1225         if ((0 != ci->children_num) || (1 != ci->values_num)
1226                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1227                 log_err ("IncludeDir expects a single string argument.");
1228                 return 1;
1229         }
1230
1231         value = ci->values[0].value.string;
1232
1233         if (NULL == aTHX) {
1234                 perl_argv = (char **)realloc (perl_argv,
1235                                 (++perl_argc + 1) * sizeof (char *));
1236
1237                 if (NULL == perl_argv) {
1238                         log_err ("perl_config: Not enough memory.");
1239                         exit (3);
1240                 }
1241
1242                 perl_argv[perl_argc - 1] = (char *)smalloc (strlen (value) + 3);
1243                 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
1244                 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen (value) + 1);
1245
1246                 perl_argv[perl_argc] = NULL;
1247         }
1248         else {
1249                 /* prepend the directory to @INC */
1250                 av_unshift (GvAVn (PL_incgv), 1);
1251                 av_store (GvAVn (PL_incgv), 0, newSVpv (value, strlen (value)));
1252         }
1253         return 0;
1254 } /* static int perl_config_includedir (oconfig_item_it *) */
1255
1256 static int perl_config (oconfig_item_t *ci)
1257 {
1258         int i = 0;
1259
1260         dTHX;
1261
1262         /* dTHX does not get any valid values in case Perl
1263          * has not been initialized */
1264         if (NULL == perl_threads)
1265                 aTHX = NULL;
1266
1267         for (i = 0; i < ci->children_num; ++i) {
1268                 oconfig_item_t *c = ci->children + i;
1269
1270                 if (0 == strcasecmp (c->key, "LoadPlugin"))
1271                         perl_config_loadplugin (aTHX_ c);
1272                 else if (0 == strcasecmp (c->key, "BaseName"))
1273                         perl_config_basename (aTHX_ c);
1274                 else if (0 == strcasecmp (c->key, "EnableDebugger"))
1275                         perl_config_enabledebugger (aTHX_ c);
1276                 else if (0 == strcasecmp (c->key, "IncludeDir"))
1277                         perl_config_includedir (aTHX_ c);
1278                 else
1279                         log_warn ("Ignoring unknown config key \"%s\".", c->key);
1280         }
1281         return 0;
1282 } /* static int perl_config (oconfig_item_t *) */
1283
1284 void module_register (void)
1285 {
1286         perl_argc = 4;
1287         perl_argv = (char **)smalloc ((perl_argc + 1) * sizeof (char *));
1288
1289         /* default options for the Perl interpreter */
1290         perl_argv[0] = "";
1291         perl_argv[1] = "-MCollectd";
1292         perl_argv[2] = "-e";
1293         perl_argv[3] = "1";
1294         perl_argv[4] = NULL;
1295
1296         plugin_register_complex_config ("perl", perl_config);
1297         return;
1298 } /* void module_register (void) */
1299
1300 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */
1301