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