perl plugin: Use PERL_NO_GET_CONTEXT.
[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 #if !defined(USE_ITHREADS)
49 # error "Perl does not support ithreads!"
50 #endif /* !defined(USE_ITHREADS) */
51
52 #define PLUGIN_INIT     0
53 #define PLUGIN_READ     1
54 #define PLUGIN_WRITE    2
55 #define PLUGIN_SHUTDOWN 3
56 #define PLUGIN_LOG      4
57
58 #define PLUGIN_TYPES    5
59
60 #define PLUGIN_DATASET  255
61
62 #define log_debug(...) DEBUG ("perl: " __VA_ARGS__)
63 #define log_info(...) INFO ("perl: " __VA_ARGS__)
64 #define log_warn(...) WARNING ("perl: " __VA_ARGS__)
65 #define log_err(...) ERROR ("perl: " __VA_ARGS__)
66
67 /* this is defined in DynaLoader.a */
68 void boot_DynaLoader (PerlInterpreter *, CV *);
69
70 static XS (Collectd_plugin_register_ds);
71 static XS (Collectd_plugin_unregister_ds);
72 static XS (Collectd_plugin_dispatch_values);
73 static XS (Collectd_plugin_log);
74
75 /*
76  * private variables
77  */
78
79 static PerlInterpreter *perl = NULL;
80
81 static int  perl_argc   = 0;
82 static char **perl_argv = NULL;
83
84 static char base_name[DATA_MAX_NAME_LEN] = "";
85
86 static struct {
87         char name[64];
88         XS ((*f));
89 } api[] =
90 {
91         { "Collectd::plugin_register_data_set",   Collectd_plugin_register_ds },
92         { "Collectd::plugin_unregister_data_set", Collectd_plugin_unregister_ds },
93         { "Collectd::plugin_dispatch_values",     Collectd_plugin_dispatch_values },
94         { "Collectd::plugin_log",                 Collectd_plugin_log },
95         { "", NULL }
96 };
97
98 struct {
99         char name[64];
100         int  value;
101 } constants[] =
102 {
103         { "Collectd::TYPE_INIT",       PLUGIN_INIT },
104         { "Collectd::TYPE_READ",       PLUGIN_READ },
105         { "Collectd::TYPE_WRITE",      PLUGIN_WRITE },
106         { "Collectd::TYPE_SHUTDOWN",   PLUGIN_SHUTDOWN },
107         { "Collectd::TYPE_LOG",        PLUGIN_LOG },
108         { "Collectd::TYPE_DATASET",    PLUGIN_DATASET },
109         { "Collectd::DS_TYPE_COUNTER", DS_TYPE_COUNTER },
110         { "Collectd::DS_TYPE_GAUGE",   DS_TYPE_GAUGE },
111         { "Collectd::LOG_ERR",         LOG_ERR },
112         { "Collectd::LOG_WARNING",     LOG_WARNING },
113         { "Collectd::LOG_NOTICE",      LOG_NOTICE },
114         { "Collectd::LOG_INFO",        LOG_INFO },
115         { "Collectd::LOG_DEBUG",       LOG_DEBUG },
116         { "", 0 }
117 };
118
119 /*
120  * Helper functions for data type conversion.
121  */
122
123 /*
124  * data source:
125  * [
126  *   {
127  *     name => $ds_name,
128  *     type => $ds_type,
129  *     min  => $ds_min,
130  *     max  => $ds_max
131  *   },
132  *   ...
133  * ]
134  */
135 static int hv2data_source (pTHX_ HV *hash, data_source_t *ds)
136 {
137         SV **tmp = NULL;
138
139         if ((NULL == hash) || (NULL == ds))
140                 return -1;
141
142         if (NULL != (tmp = hv_fetch (hash, "name", 4, 0))) {
143                 strncpy (ds->name, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
144                 ds->name[DATA_MAX_NAME_LEN - 1] = '\0';
145         }
146         else {
147                 log_err ("hv2data_source: No DS name given.");
148                 return -1;
149         }
150
151         if (NULL != (tmp = hv_fetch (hash, "type", 4, 0))) {
152                 ds->type = SvIV (*tmp);
153
154                 if ((DS_TYPE_COUNTER != ds->type) && (DS_TYPE_GAUGE != ds->type)) {
155                         log_err ("hv2data_source: Invalid DS type.");
156                         return -1;
157                 }
158         }
159         else {
160                 ds->type = DS_TYPE_COUNTER;
161         }
162
163         if (NULL != (tmp = hv_fetch (hash, "min", 3, 0)))
164                 ds->min = SvNV (*tmp);
165         else
166                 ds->min = NAN;
167
168         if (NULL != (tmp = hv_fetch (hash, "max", 3, 0)))
169                 ds->max = SvNV (*tmp);
170         else
171                 ds->max = NAN;
172         return 0;
173 } /* static data_source_t *hv2data_source (HV *) */
174
175 static int av2value (pTHX_ char *name, AV *array, value_t *value, int len)
176 {
177         const data_set_t *ds;
178
179         int i = 0;
180
181         if ((NULL == name) || (NULL == array) || (NULL == value))
182                 return -1;
183
184         if (av_len (array) < len - 1)
185                 len = av_len (array) + 1;
186
187         if (0 >= len)
188                 return -1;
189
190         ds = plugin_get_ds (name);
191         if (NULL == ds) {
192                 log_err ("av2value: Unknown dataset \"%s\"", name);
193                 return -1;
194         }
195
196         if (ds->ds_num < len) {
197                 log_warn ("av2value: Value length exceeds data set length.");
198                 len = ds->ds_num;
199         }
200
201         for (i = 0; i < len; ++i) {
202                 SV **tmp = av_fetch (array, i, 0);
203
204                 if (NULL != tmp) {
205                         if (DS_TYPE_COUNTER == ds->ds[i].type)
206                                 value[i].counter = SvIV (*tmp);
207                         else
208                                 value[i].gauge = SvNV (*tmp);
209                 }
210                 else {
211                         return -1;
212                 }
213         }
214         return len;
215 } /* static int av2value (char *, AV *, value_t *, int) */
216
217 static int data_set2av (pTHX_ data_set_t *ds, AV *array)
218 {
219         int i = 0;
220
221         if ((NULL == ds) || (NULL == array))
222                 return -1;
223
224         av_extend (array, ds->ds_num);
225
226         for (i = 0; i < ds->ds_num; ++i) {
227                 HV *source = newHV ();
228
229                 if (NULL == hv_store (source, "name", 4,
230                                 newSVpv (ds->ds[i].name, 0), 0))
231                         return -1;
232
233                 if (NULL == hv_store (source, "type", 4, newSViv (ds->ds[i].type), 0))
234                         return -1;
235
236                 if (! isnan (ds->ds[i].min))
237                         if (NULL == hv_store (source, "min", 3,
238                                         newSVnv (ds->ds[i].min), 0))
239                                 return -1;
240
241                 if (! isnan (ds->ds[i].max))
242                         if (NULL == hv_store (source, "max", 3,
243                                         newSVnv (ds->ds[i].max), 0))
244                                 return -1;
245
246                 if (NULL == av_store (array, i, newRV_noinc ((SV *)source)))
247                         return -1;
248         }
249         return 0;
250 } /* static int data_set2av (data_set_t *, AV *) */
251
252 static int value_list2hv (pTHX_ value_list_t *vl, data_set_t *ds, HV *hash)
253 {
254         AV *values = NULL;
255
256         int i   = 0;
257         int len = 0;
258
259         if ((NULL == vl) || (NULL == ds) || (NULL == hash))
260                 return -1;
261
262         len = vl->values_len;
263
264         if (ds->ds_num < len) {
265                 log_warn ("value2av: Value length exceeds data set length.");
266                 len = ds->ds_num;
267         }
268
269         values = newAV ();
270         av_extend (values, len - 1);
271
272         for (i = 0; i < len; ++i) {
273                 SV *val = NULL;
274
275                 if (DS_TYPE_COUNTER == ds->ds[i].type)
276                         val = newSViv (vl->values[i].counter);
277                 else
278                         val = newSVnv (vl->values[i].gauge);
279
280                 if (NULL == av_store (values, i, val)) {
281                         av_undef (values);
282                         return -1;
283                 }
284         }
285
286         if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0))
287                 return -1;
288
289         if (0 != vl->time)
290                 if (NULL == hv_store (hash, "time", 4, newSViv (vl->time), 0))
291                         return -1;
292
293         if ('\0' != vl->host[0])
294                 if (NULL == hv_store (hash, "host", 4, newSVpv (vl->host, 0), 0))
295                         return -1;
296
297         if ('\0' != vl->plugin[0])
298                 if (NULL == hv_store (hash, "plugin", 6, newSVpv (vl->plugin, 0), 0))
299                         return -1;
300
301         if ('\0' != vl->plugin_instance[0])
302                 if (NULL == hv_store (hash, "plugin_instance", 15,
303                                 newSVpv (vl->plugin_instance, 0), 0))
304                         return -1;
305
306         if ('\0' != vl->type_instance[0])
307                 if (NULL == hv_store (hash, "type_instance", 13,
308                                 newSVpv (vl->type_instance, 0), 0))
309                         return -1;
310         return 0;
311 } /* static int value2av (value_list_t *, data_set_t *, HV *) */
312
313 /*
314  * Internal functions.
315  */
316
317 static char *get_module_name (char *buf, size_t buf_len, const char *module) {
318         int status = 0;
319         if (base_name[0] == '\0')
320                 status = snprintf (buf, buf_len, "%s", module);
321         else
322                 status = snprintf (buf, buf_len, "%s::%s", base_name, module);
323         if ((status < 0) || (status >= buf_len))
324                 return (NULL);
325         buf[buf_len - 1] = '\0';
326         return (buf);
327 } /* char *get_module_name */
328
329 /*
330  * Add a plugin's data set definition.
331  */
332 static int pplugin_register_data_set (pTHX_ char *name, AV *dataset)
333 {
334         int len = -1;
335         int i   = 0;
336
337         data_source_t *ds  = NULL;
338         data_set_t    *set = NULL;
339
340         if ((NULL == name) || (NULL == dataset))
341                 return -1;
342
343         len = av_len (dataset);
344
345         if (-1 == len)
346                 return -1;
347
348         ds  = (data_source_t *)smalloc ((len + 1) * sizeof (data_source_t));
349         set = (data_set_t *)smalloc (sizeof (data_set_t));
350
351         for (i = 0; i <= len; ++i) {
352                 SV **elem = av_fetch (dataset, i, 0);
353
354                 if (NULL == elem)
355                         return -1;
356
357                 if (! (SvROK (*elem) && (SVt_PVHV == SvTYPE (SvRV (*elem))))) {
358                         log_err ("pplugin_register_data_set: Invalid data source.");
359                         return -1;
360                 }
361
362                 if (-1 == hv2data_source (aTHX_ (HV *)SvRV (*elem), &ds[i]))
363                         return -1;
364
365                 log_debug ("pplugin_register_data_set: "
366                                 "DS.name = \"%s\", DS.type = %i, DS.min = %f, DS.max = %f",
367                                 ds[i].name, ds[i].type, ds[i].min, ds[i].max);
368         }
369
370         strncpy (set->type, name, DATA_MAX_NAME_LEN);
371         set->type[DATA_MAX_NAME_LEN - 1] = '\0';
372
373         set->ds_num = len + 1;
374         set->ds = ds;
375         return plugin_register_data_set (set);
376 } /* static int pplugin_register_data_set (char *, SV *) */
377
378 /*
379  * Remove a plugin's data set definition.
380  */
381 static int pplugin_unregister_data_set (char *name)
382 {
383         if (NULL == name)
384                 return 0;
385         return plugin_unregister_data_set (name);
386 } /* static int pplugin_unregister_data_set (char *) */
387
388 /*
389  * Submit the values to the write functions.
390  *
391  * value list:
392  * {
393  *   values => [ @values ],
394  *   time   => $time,
395  *   host   => $host,
396  *   plugin => $plugin,
397  *   plugin_instance => $pinstance,
398  *   type_instance   => $tinstance,
399  * }
400  */
401 static int pplugin_dispatch_values (pTHX_ char *name, HV *values)
402 {
403         value_list_t list = VALUE_LIST_INIT;
404         value_t      *val = NULL;
405
406         SV **tmp = NULL;
407
408         int ret = 0;
409
410         if ((NULL == name) || (NULL == values))
411                 return -1;
412
413         if ((NULL == (tmp = hv_fetch (values, "values", 6, 0)))
414                         || (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp)))))) {
415                 log_err ("pplugin_dispatch_values: No valid values given.");
416                 return -1;
417         }
418
419         {
420                 AV  *array = (AV *)SvRV (*tmp);
421                 int len    = av_len (array) + 1;
422
423                 if (len <= 0)
424                         return -1;
425
426                 val = (value_t *)smalloc (len * sizeof (value_t));
427
428                 list.values_len = av2value (aTHX_ name, (AV *)SvRV (*tmp), val, len);
429                 list.values = val;
430
431                 if (-1 == list.values_len) {
432                         sfree (val);
433                         return -1;
434                 }
435         }
436
437         if (NULL != (tmp = hv_fetch (values, "time", 4, 0))) {
438                 list.time = (time_t)SvIV (*tmp);
439         }
440         else {
441                 list.time = time (NULL);
442         }
443
444         if (NULL != (tmp = hv_fetch (values, "host", 4, 0))) {
445                 strncpy (list.host, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
446                 list.host[DATA_MAX_NAME_LEN - 1] = '\0';
447         }
448         else {
449                 strcpy (list.host, hostname_g);
450         }
451
452         if (NULL != (tmp = hv_fetch (values, "plugin", 6, 0))) {
453                 strncpy (list.plugin, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
454                 list.plugin[DATA_MAX_NAME_LEN - 1] = '\0';
455         }
456
457         if (NULL != (tmp = hv_fetch (values,
458                         "plugin_instance", 15, 0))) {
459                 strncpy (list.plugin_instance, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
460                 list.plugin_instance[DATA_MAX_NAME_LEN - 1] = '\0';
461         }
462
463         if (NULL != (tmp = hv_fetch (values, "type_instance", 13, 0))) {
464                 strncpy (list.type_instance, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
465                 list.type_instance[DATA_MAX_NAME_LEN - 1] = '\0';
466         }
467
468         ret = plugin_dispatch_values (name, &list);
469
470         sfree (val);
471         return ret;
472 } /* static int pplugin_dispatch_values (char *, HV *) */
473
474 /*
475  * Call all working functions of the given type.
476  */
477 static int pplugin_call_all (pTHX_ int type, ...)
478 {
479         int retvals = 0;
480
481         va_list ap;
482         int ret = 0;
483
484         dSP;
485
486         if ((type < 0) || (type >= PLUGIN_TYPES))
487                 return -1;
488
489         va_start (ap, type);
490
491         ENTER;
492         SAVETMPS;
493
494         PUSHMARK (SP);
495
496         XPUSHs (sv_2mortal (newSViv ((IV)type)));
497
498         if (PLUGIN_WRITE == type) {
499                 /*
500                  * $_[0] = $plugin_type;
501                  *
502                  * $_[1] =
503                  * [
504                  *   {
505                  *     name => $ds_name,
506                  *     type => $ds_type,
507                  *     min  => $ds_min,
508                  *     max  => $ds_max
509                  *   },
510                  *   ...
511                  * ];
512                  *
513                  * $_[2] =
514                  * {
515                  *   values => [ $v1, ... ],
516                  *   time   => $time,
517                  *   host   => $hostname,
518                  *   plugin => $plugin,
519                  *   plugin_instance => $instance,
520                  *   type_instance   => $type_instance
521                  * };
522                  */
523                 data_set_t   *ds;
524                 value_list_t *vl;
525
526                 AV *pds = newAV ();
527                 HV *pvl = newHV ();
528
529                 ds = va_arg (ap, data_set_t *);
530                 vl = va_arg (ap, value_list_t *);
531
532                 if (-1 == data_set2av (aTHX_ ds, pds))
533                         return -1;
534
535                 if (-1 == value_list2hv (aTHX_ vl, ds, pvl))
536                         return -1;
537
538                 XPUSHs (sv_2mortal (newSVpv (ds->type, 0)));
539                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
540                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
541         }
542         else if (PLUGIN_LOG == type) {
543                 /*
544                  * $_[0] = $level;
545                  *
546                  * $_[1] = $message;
547                  */
548                 XPUSHs (sv_2mortal (newSViv (va_arg (ap, int))));
549                 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
550         }
551
552         PUTBACK;
553
554         retvals = call_pv ("Collectd::plugin_call_all", G_SCALAR);
555
556         SPAGAIN;
557         if (0 < retvals) {
558                 SV *tmp = POPs;
559                 if (! SvTRUE (tmp))
560                         ret = -1;
561         }
562
563         PUTBACK;
564         FREETMPS;
565         LEAVE;
566
567         va_end (ap);
568         return ret;
569 } /* static int pplugin_call_all (int, ...) */
570
571 /*
572  * Exported Perl API.
573  */
574
575 /*
576  * Collectd::plugin_register_data_set (type, dataset).
577  *
578  * type:
579  *   type of the dataset
580  *
581  * dataset:
582  *   dataset to be registered
583  */
584 static XS (Collectd_plugin_register_ds)
585 {
586         SV  *data = NULL;
587         int ret   = 0;
588
589         dXSARGS;
590
591         if (2 != items) {
592                 log_err ("Usage: Collectd::plugin_register_data_set(type, dataset)");
593                 XSRETURN_EMPTY;
594         }
595
596         log_debug ("Collectd::plugin_register_data_set: "
597                         "type = \"%s\", dataset = \"%s\"",
598                         SvPV_nolen (ST (0)), SvPV_nolen (ST (1)));
599
600         data = ST (1);
601
602         if (SvROK (data) && (SVt_PVAV == SvTYPE (SvRV (data)))) {
603                 ret = pplugin_register_data_set (aTHX_ SvPV_nolen (ST (0)),
604                                 (AV *)SvRV (data));
605         }
606         else {
607                 log_err ("Collectd::plugin_register_data_set: Invalid data.");
608                 XSRETURN_EMPTY;
609         }
610
611         if (0 == ret)
612                 XSRETURN_YES;
613         else
614                 XSRETURN_EMPTY;
615 } /* static XS (Collectd_plugin_register_ds) */
616
617 /*
618  * Collectd::plugin_unregister_data_set (type).
619  *
620  * type:
621  *   type of the dataset
622  */
623 static XS (Collectd_plugin_unregister_ds)
624 {
625         dXSARGS;
626
627         if (1 != items) {
628                 log_err ("Usage: Collectd::plugin_unregister_data_set(type)");
629                 XSRETURN_EMPTY;
630         }
631
632         log_debug ("Collectd::plugin_unregister_data_set: type = \"%s\"",
633                         SvPV_nolen (ST (0)));
634
635         if (0 == pplugin_unregister_data_set (SvPV_nolen (ST (1))))
636                 XSRETURN_YES;
637         else
638                 XSRETURN_EMPTY;
639 } /* static XS (Collectd_plugin_register_ds) */
640
641 /*
642  * Collectd::plugin_dispatch_values (name, values).
643  *
644  * name:
645  *   name of the plugin
646  *
647  * values:
648  *   value list to submit
649  */
650 static XS (Collectd_plugin_dispatch_values)
651 {
652         SV *values = NULL;
653
654         int ret = 0;
655
656         dXSARGS;
657
658         if (2 != items) {
659                 log_err ("Usage: Collectd::plugin_dispatch_values(name, values)");
660                 XSRETURN_EMPTY;
661         }
662
663         log_debug ("Collectd::plugin_dispatch_values: "
664                         "name = \"%s\", values=\"%s\"",
665                         SvPV_nolen (ST (0)), SvPV_nolen (ST (1)));
666
667         values = ST (1);
668
669         if (! (SvROK (values) && (SVt_PVHV == SvTYPE (SvRV (values))))) {
670                 log_err ("Collectd::plugin_dispatch_values: Invalid values.");
671                 XSRETURN_EMPTY;
672         }
673
674         if ((NULL == ST (0)) || (NULL == values))
675                 XSRETURN_EMPTY;
676
677         ret = pplugin_dispatch_values (aTHX_ SvPV_nolen (ST (0)),
678                         (HV *)SvRV (values));
679
680         if (0 == ret)
681                 XSRETURN_YES;
682         else
683                 XSRETURN_EMPTY;
684 } /* static XS (Collectd_plugin_dispatch_values) */
685
686 /*
687  * Collectd::plugin_log (level, message).
688  *
689  * level:
690  *   log level (LOG_DEBUG, ... LOG_ERR)
691  *
692  * message:
693  *   log message
694  */
695 static XS (Collectd_plugin_log)
696 {
697         dXSARGS;
698
699         if (2 != items) {
700                 log_err ("Usage: Collectd::plugin_log(level, message)");
701                 XSRETURN_EMPTY;
702         }
703
704         plugin_log (SvIV (ST (0)), SvPV_nolen (ST (1)));
705         XSRETURN_YES;
706 } /* static XS (Collectd_plugin_log) */
707
708 /*
709  * Interface to collectd.
710  */
711
712 static int perl_init (void)
713 {
714         dTHXa (NULL);
715
716         if (NULL == perl)
717                 return 0;
718
719         PERL_SET_CONTEXT (perl);
720         aTHX = perl;
721
722         return pplugin_call_all (aTHX_ PLUGIN_INIT);
723 } /* static int perl_init (void) */
724
725 static int perl_read (void)
726 {
727         dTHXa (NULL);
728
729         if (NULL == perl)
730                 return 0;
731
732         PERL_SET_CONTEXT (perl);
733         aTHX = perl;
734
735         return pplugin_call_all (aTHX_ PLUGIN_READ);
736 } /* static int perl_read (void) */
737
738 static int perl_write (const data_set_t *ds, const value_list_t *vl)
739 {
740         dTHXa (NULL);
741
742         if (NULL == perl)
743                 return 0;
744
745         PERL_SET_CONTEXT (perl);
746         aTHX = perl;
747
748         return pplugin_call_all (aTHX_ PLUGIN_WRITE, ds, vl);
749 } /* static int perl_write (const data_set_t *, const value_list_t *) */
750
751 static void perl_log (int level, const char *msg)
752 {
753         dTHXa (NULL);
754
755         if (NULL == perl)
756                 return;
757
758         PERL_SET_CONTEXT (perl);
759         aTHX = perl;
760
761         pplugin_call_all (aTHX_ PLUGIN_LOG, level, msg);
762         return;
763 } /* static void perl_log (int, const char *) */
764
765 static int perl_shutdown (void)
766 {
767         int ret = 0;
768
769         dTHXa (NULL);
770
771         plugin_unregister_complex_config ("perl");
772
773         if (NULL == perl)
774                 return 0;
775
776         PERL_SET_CONTEXT (perl);
777         aTHX = perl;
778
779         plugin_unregister_log ("perl");
780         plugin_unregister_init ("perl");
781         plugin_unregister_read ("perl");
782         plugin_unregister_write ("perl");
783
784         ret = pplugin_call_all (aTHX_ PLUGIN_SHUTDOWN);
785
786 #if COLLECT_DEBUG
787         sv_report_used ();
788 #endif /* COLLECT_DEBUG */
789
790         perl_destruct (perl);
791         perl_free (perl);
792         perl = NULL;
793
794         PERL_SYS_TERM ();
795
796         plugin_unregister_shutdown ("perl");
797         return ret;
798 } /* static void perl_shutdown (void) */
799
800 /* bootstrap the Collectd module */
801 static void xs_init (pTHX)
802 {
803         HV   *stash = NULL;
804         char *file  = __FILE__;
805
806         int i = 0;
807
808         dXSUB_SYS;
809
810         /* enable usage of Perl modules using shared libraries */
811         newXS ("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
812
813         /* register API */
814         for (i = 0; NULL != api[i].f; ++i)
815                 newXS (api[i].name, api[i].f, file);
816
817         stash = gv_stashpv ("Collectd", 1);
818
819         /* export "constants" */
820         for (i = 0; '\0' != constants[i].name[0]; ++i)
821                 newCONSTSUB (stash, constants[i].name, newSViv (constants[i].value));
822         return;
823 } /* static void xs_init (pTHX) */
824
825 /* Initialize the global Perl interpreter. */
826 static int init_pi (int argc, char **argv)
827 {
828         dTHXa (NULL);
829
830         if (NULL != perl)
831                 return 0;
832
833         log_info ("Initializing Perl interpreter...");
834 #if COLLECT_DEBUG
835         {
836                 int i = 0;
837
838                 for (i = 0; i < argc; ++i)
839                         log_debug ("argv[%i] = \"%s\"", i, argv[i]);
840         }
841 #endif /* COLLECT_DEBUG */
842
843         PERL_SYS_INIT3 (&argc, &argv, &environ);
844
845         if (NULL == (perl = perl_alloc ())) {
846                 log_err ("module_register: Not enough memory.");
847                 exit (3);
848         }
849
850         aTHX = perl;
851         perl_construct (perl);
852
853         PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
854
855         if (0 != perl_parse (perl, xs_init, argc, argv, NULL)) {
856                 log_err ("module_register: Unable to bootstrap Collectd.");
857                 exit (1);
858         }
859
860         /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
861         sv_setpv (get_sv ("0", 0), "collectd");
862
863         perl_run (perl);
864
865         plugin_register_log ("perl", perl_log);
866         plugin_register_init ("perl", perl_init);
867
868         plugin_register_read ("perl", perl_read);
869
870         plugin_register_write ("perl", perl_write);
871         plugin_register_shutdown ("perl", perl_shutdown);
872         return 0;
873 } /* static int init_pi (const char **, const int) */
874
875 /*
876  * LoadPlugin "<Plugin>"
877  */
878 static int perl_config_loadplugin (pTHX_ oconfig_item_t *ci)
879 {
880         char module_name[DATA_MAX_NAME_LEN];
881
882         char *value = NULL;
883
884         if ((0 != ci->children_num) || (1 != ci->values_num)
885                         || (OCONFIG_TYPE_STRING != ci->values[0].type))
886                 return 1;
887
888         value = ci->values[0].value.string;
889
890         if (NULL == get_module_name (module_name, sizeof (module_name), value)) {
891                 log_err ("Invalid module name %s", value);
892                 return (1);
893         }
894
895         init_pi (perl_argc, perl_argv);
896         aTHX = perl;
897
898         log_debug ("perl_config: loading perl plugin \"%s\"", value);
899         load_module (PERL_LOADMOD_NOIMPORT,
900                         newSVpv (module_name, strlen (module_name)), Nullsv);
901         return 0;
902 } /* static int perl_config_loadplugin (oconfig_item_it *) */
903
904 /*
905  * BaseName "<Name>"
906  */
907 static int perl_config_basename (pTHX_ oconfig_item_t *ci)
908 {
909         char *value = NULL;
910
911         if ((0 != ci->children_num) || (1 != ci->values_num)
912                         || (OCONFIG_TYPE_STRING != ci->values[0].type))
913                 return 1;
914
915         value = ci->values[0].value.string;
916
917         log_debug ("perl_config: Setting plugin basename to \"%s\"", value);
918         strncpy (base_name, value, sizeof (base_name));
919         base_name[sizeof (base_name) - 1] = '\0';
920         return 0;
921 } /* static int perl_config_basename (oconfig_item_it *) */
922
923 /*
924  * EnableDebugger "<Package>"|""
925  */
926 static int perl_config_enabledebugger (pTHX_ oconfig_item_t *ci)
927 {
928         char *value = NULL;
929
930         if ((0 != ci->children_num) || (1 != ci->values_num)
931                         || (OCONFIG_TYPE_STRING != ci->values[0].type))
932                 return 1;
933
934         value = ci->values[0].value.string;
935
936         perl_argv = (char **)realloc (perl_argv,
937                         (++perl_argc + 1) * sizeof (char *));
938
939         if (NULL == perl_argv) {
940                 log_err ("perl_config: Not enough memory.");
941                 exit (3);
942         }
943
944         if ('\0' == value[0]) {
945                 perl_argv[perl_argc - 1] = "-d";
946         }
947         else {
948                 perl_argv[perl_argc - 1] = (char *)smalloc (strlen (value) + 4);
949                 sstrncpy (perl_argv[perl_argc - 1], "-d:", 4);
950                 sstrncpy (perl_argv[perl_argc - 1] + 3, value, strlen (value) + 1);
951         }
952
953         perl_argv[perl_argc] = NULL;
954         return 0;
955 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
956
957 /*
958  * IncludeDir "<Dir>"
959  */
960 static int perl_config_includedir (pTHX_ oconfig_item_t *ci)
961 {
962         char *value = NULL;
963
964         if ((0 != ci->children_num) || (1 != ci->values_num)
965                         || (OCONFIG_TYPE_STRING != ci->values[0].type))
966                 return 1;
967
968         value = ci->values[0].value.string;
969
970         if (NULL == aTHX) {
971                 perl_argv = (char **)realloc (perl_argv,
972                                 (++perl_argc + 1) * sizeof (char *));
973
974                 if (NULL == perl_argv) {
975                         log_err ("perl_config: Not enough memory.");
976                         exit (3);
977                 }
978
979                 perl_argv[perl_argc - 1] = (char *)smalloc (strlen (value) + 3);
980                 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
981                 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen (value) + 1);
982
983                 perl_argv[perl_argc] = NULL;
984         }
985         else {
986                 /* prepend the directory to @INC */
987                 av_unshift (GvAVn (PL_incgv), 1);
988                 av_store (GvAVn (PL_incgv), 0, newSVpv (value, strlen (value)));
989         }
990         return 0;
991 } /* static int perl_config_includedir (oconfig_item_it *) */
992
993 static int perl_config (oconfig_item_t *ci)
994 {
995         int i = 0;
996
997         dTHXa (NULL);
998
999         PERL_SET_CONTEXT (perl);
1000         aTHX = perl;
1001
1002         for (i = 0; i < ci->children_num; ++i) {
1003                 oconfig_item_t *c = ci->children + i;
1004
1005                 if (0 == strcasecmp (c->key, "LoadPlugin"))
1006                         perl_config_loadplugin (aTHX_ c);
1007                 else if (0 == strcasecmp (c->key, "BaseName"))
1008                         perl_config_basename (aTHX_ c);
1009                 else if (0 == strcasecmp (c->key, "EnableDebugger"))
1010                         perl_config_enabledebugger (aTHX_ c);
1011                 else if (0 == strcasecmp (c->key, "IncludeDir"))
1012                         perl_config_includedir (aTHX_ c);
1013                 else
1014                         log_warn ("Ignoring unknown config key \"%s\".", c->key);
1015         }
1016         return 0;
1017 } /* static int perl_config (oconfig_item_t *) */
1018
1019 void module_register (void)
1020 {
1021         perl_argc = 4;
1022         perl_argv = (char **)smalloc ((perl_argc + 1) * sizeof (char *));
1023
1024         /* default options for the Perl interpreter */
1025         perl_argv[0] = "";
1026         perl_argv[1] = "-MCollectd";
1027         perl_argv[2] = "-e";
1028         perl_argv[3] = "1";
1029         perl_argv[4] = NULL;
1030
1031         plugin_register_complex_config ("perl", perl_config);
1032         return;
1033 } /* void module_register (void) */
1034
1035 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */
1036