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