Code

perl plugin: Do not initialize the Perl interpreter until loading a module.
[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  **/
22 /*
23  * This plugin embeds a Perl interpreter into collectd and provides an
24  * interface for collectd plugins written in perl.
25  */
27 #include "collectd.h"
29 #include "configfile.h"
31 #include <EXTERN.h>
32 #include <perl.h>
34 #include <XSUB.h>
36 /* Some versions of Perl define their own version of DEBUG... :-/ */
37 #ifdef DEBUG
38 # undef DEBUG
39 #endif /* DEBUG */
41 /* ... while we want the definition found in plugin.h. */
42 #include "plugin.h"
43 #include "common.h"
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
51 #define PLUGIN_TYPES    5
53 #define PLUGIN_DATASET  255
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__)
61 /* this is defined in DynaLoader.a */
62 void boot_DynaLoader (PerlInterpreter *, CV *);
64 static XS (Collectd_plugin_register);
65 static XS (Collectd_plugin_unregister);
66 static XS (Collectd_plugin_dispatch_values);
67 static XS (Collectd_plugin_log);
70 /*
71  * private data types
72  */
74 typedef struct {
75         int len;
76         int *values;
77 } ds_types_t;
79 typedef struct {
80         int wait_time;
81         int wait_left;
83         SV  *sub;
84 } pplugin_t;
87 /*
88  * private variables
89  */
91 /* valid configuration file keys */
92 static const char *config_keys[] =
93 {
94         "LoadPlugin",
95         "BaseName",
96         "IncludeDir"
97 };
98 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
100 static PerlInterpreter *perl = NULL;
102 static int  perl_argc   = 0;
103 static char **perl_argv = NULL;
105 static char base_name[DATA_MAX_NAME_LEN] = "";
107 static char *plugin_types[] = { "init", "read", "write", "shutdown" };
108 static HV   *plugins[PLUGIN_TYPES];
109 static HV   *data_sets;
111 static struct {
112         char name[64];
113         XS ((*f));
114 } api[] =
116         { "Collectd::plugin_register",        Collectd_plugin_register },
117         { "Collectd::plugin_unregister",      Collectd_plugin_unregister },
118         { "Collectd::plugin_dispatch_values", Collectd_plugin_dispatch_values },
119         { "Collectd::plugin_log",             Collectd_plugin_log },
120         { "", NULL }
121 };
124 /*
125  * Helper functions for data type conversion.
126  */
128 /*
129  * data source:
130  * [
131  *   {
132  *     name => $ds_name,
133  *     type => $ds_type,
134  *     min  => $ds_min,
135  *     max  => $ds_max
136  *   },
137  *   ...
138  * ]
139  */
140 static int hv2data_source (HV *hash, data_source_t *ds)
142         SV **tmp = NULL;
144         if ((NULL == hash) || (NULL == ds))
145                 return -1;
147         if (NULL != (tmp = Perl_hv_fetch (perl, hash, "name", 4, 0))) {
148                 strncpy (ds->name, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
149                 ds->name[DATA_MAX_NAME_LEN - 1] = '\0';
150         }
151         else {
152                 log_err ("hv2data_source: No DS name given.");
153                 return -1;
154         }
156         if (NULL != (tmp = Perl_hv_fetch (perl, hash, "type", 4, 0))) {
157                 ds->type = SvIV (*tmp);
159                 if ((DS_TYPE_COUNTER != ds->type) && (DS_TYPE_GAUGE != ds->type)) {
160                         log_err ("hv2data_source: Invalid DS type.");
161                         return -1;
162                 }
163         }
164         else {
165                 ds->type = DS_TYPE_COUNTER;
166         }
168         if (NULL != (tmp = Perl_hv_fetch (perl, hash, "min", 3, 0)))
169                 ds->min = SvNV (*tmp);
170         else
171                 ds->min = NAN;
173         if (NULL != (tmp = Perl_hv_fetch (perl, hash, "max", 3, 0)))
174                 ds->max = SvNV (*tmp);
175         else
176                 ds->max = NAN;
177         return 0;
178 } /* static data_source_t *hv2data_source (HV *) */
180 static int av2value (char *name, AV *array, value_t *value, int len)
182         SV **tmp = NULL;
184         ds_types_t *ds = NULL;
186         int i = 0;
188         if ((NULL == name) || (NULL == array) || (NULL == value))
189                 return -1;
191         if (Perl_av_len (perl, array) < len - 1)
192                 len = Perl_av_len (perl, array) + 1;
194         if (0 >= len)
195                 return -1;
197         tmp = Perl_hv_fetch (perl, data_sets, name, strlen (name), 0);
198         if (NULL == tmp) {
199                 log_err ("av2value: No dataset for \"%s\".", name);
200                 return -1;
201         }
202         ds = (ds_types_t *)SvIV ((SV *)SvRV (*tmp));
204         if (ds->len < len) {
205                 log_warn ("av2value: Value length exceeds data set length.");
206                 len = ds->len;
207         }
209         for (i = 0; i < len; ++i) {
210                 SV **tmp = Perl_av_fetch (perl, array, i, 0);
212                 if (NULL != tmp) {
213                         if (DS_TYPE_COUNTER == ds->values[i])
214                                 value[i].counter = SvIV (*tmp);
215                         else
216                                 value[i].gauge = SvNV (*tmp);
217                 }
218                 else {
219                         return -1;
220                 }
221         }
222         return len;
223 } /* static int av2value (char *, AV *, value_t *, int) */
225 static int data_set2av (data_set_t *ds, AV *array)
227         int i = 0;
229         if ((NULL == ds) || (NULL == array))
230                 return -1;
232         Perl_av_extend (perl, array, ds->ds_num);
234         for (i = 0; i < ds->ds_num; ++i) {
235                 HV *source = Perl_newHV (perl);
237                 if (NULL == Perl_hv_store (perl, source, "name", 4,
238                                 Perl_newSVpv (perl, ds->ds[i].name, 0), 0))
239                         return -1;
241                 if (NULL == Perl_hv_store (perl, source, "type", 4,
242                                 Perl_newSViv (perl, ds->ds[i].type), 0))
243                         return -1;
245                 if (! isnan (ds->ds[i].min))
246                         if (NULL == Perl_hv_store (perl, source, "min", 3,
247                                         Perl_newSVnv (perl, ds->ds[i].min), 0))
248                                 return -1;
250                 if (! isnan (ds->ds[i].max))
251                         if (NULL == Perl_hv_store (perl, source, "max", 3,
252                                         Perl_newSVnv (perl, ds->ds[i].max), 0))
253                                 return -1;
255                 if (NULL == Perl_av_store (perl, array, i,
256                                 Perl_newRV_noinc (perl, (SV *)source)))
257                         return -1;
258         }
259         return 0;
260 } /* static int data_set2av (data_set_t *, AV *) */
262 static int value_list2hv (value_list_t *vl, data_set_t *ds, HV *hash)
264         AV *values = NULL;
266         int i   = 0;
267         int len = 0;
269         if ((NULL == vl) || (NULL == ds) || (NULL == hash))
270                 return -1;
272         len = vl->values_len;
274         if (ds->ds_num < len) {
275                 log_warn ("value2av: Value length exceeds data set length.");
276                 len = ds->ds_num;
277         }
279         values = Perl_newAV (perl);
280         Perl_av_extend (perl, values, len - 1);
282         for (i = 0; i < len; ++i) {
283                 SV *val = NULL;
285                 if (DS_TYPE_COUNTER == ds->ds[i].type)
286                         val = Perl_newSViv (perl, vl->values[i].counter);
287                 else
288                         val = Perl_newSVnv (perl, vl->values[i].gauge);
290                 if (NULL == Perl_av_store (perl, values, i, val)) {
291                         Perl_av_undef (perl, values);
292                         return -1;
293                 }
294         }
296         if (NULL == Perl_hv_store (perl, hash, "values", 6,
297                         Perl_newRV_noinc (perl, (SV *)values), 0))
298                 return -1;
300         if (0 != vl->time)
301                 if (NULL == Perl_hv_store (perl, hash, "time", 4,
302                                 Perl_newSViv (perl, vl->time), 0))
303                         return -1;
305         if ('\0' != vl->host[0])
306                 if (NULL == Perl_hv_store (perl, hash, "host", 4,
307                                 Perl_newSVpv (perl, vl->host, 0), 0))
308                         return -1;
310         if ('\0' != vl->plugin[0])
311                 if (NULL == Perl_hv_store (perl, hash, "plugin", 6,
312                                 Perl_newSVpv (perl, vl->plugin, 0), 0))
313                         return -1;
315         if ('\0' != vl->plugin_instance[0])
316                 if (NULL == Perl_hv_store (perl, hash, "plugin_instance", 15,
317                                 Perl_newSVpv (perl, vl->plugin_instance, 0), 0))
318                         return -1;
320         if ('\0' != vl->type_instance[0])
321                 if (NULL == Perl_hv_store (perl, hash, "type_instance", 13,
322                                 Perl_newSVpv (perl, vl->type_instance, 0), 0))
323                         return -1;
324         return 0;
325 } /* static int value2av (value_list_t *, data_set_t *, HV *) */
328 /*
329  * Internal functions.
330  */
332 static char *get_module_name (char *buf, size_t buf_len, const char *module) {
333         int status = 0;
334         if (base_name[0] == '\0')
335                 status = snprintf (buf, buf_len, "%s", module);
336         else
337                 status = snprintf (buf, buf_len, "%s::%s", base_name, module);
338         if ((status < 0) || (status >= buf_len))
339                 return (NULL);
340         buf[buf_len - 1] = '\0';
341         return (buf);
342 } /* char *get_module_name */
344 /*
345  * Add a new plugin with the given name.
346  */
347 static int pplugin_register (int type, const char *name, SV *sub)
349         pplugin_t *p = NULL;
351         if ((type < 0) || (type >= PLUGIN_TYPES))
352                 return -1;
354         if (NULL == name)
355                 return -1;
357         p = (pplugin_t *)smalloc (sizeof (pplugin_t));
358         /* this happens during parsing of config file,
359          * thus interval_g is not set correctly */
360         p->wait_time = 10;
361         p->wait_left = 0;
362         p->sub = Perl_newSVsv (perl, sub);
364         if (NULL == Perl_hv_store (perl, plugins[type], name, strlen (name),
365                                 Perl_sv_setref_pv (perl, Perl_newSV (perl, 0), 0, p), 0)) {
366                 log_debug ("pplugin_register: Failed to add plugin \"%s\" (\"%s\")",
367                                 name, SvPV_nolen (sub));
368                 Perl_sv_free (perl, p->sub);
369                 sfree (p);
370                 return -1;
371         }
372         return 0;
373 } /* static int pplugin_register (int, char *, SV *) */
375 /*
376  * Removes the plugin with the given name and frees any ressources.
377  */
378 static int pplugin_unregister (int type, char *name)
380         SV *tmp = NULL;
382         if ((type < 0) || (type >= PLUGIN_TYPES))
383                 return -1;
385         if (NULL == name)
386                 return -1;
388         /* freeing the allocated memory of the element itself (pplugin_t *) causes
389          * a segfault during perl_destruct () thus I assume perl somehow takes
390          * care of this... */
392         tmp = Perl_hv_delete (perl, plugins[type], name, strlen (name), 0);
393         if (NULL != tmp) {
394                 pplugin_t *p = (pplugin_t *)SvIV ((SV *)SvRV (tmp));
395                 Perl_sv_free (perl, p->sub);
396         }
397         return 0;
398 } /* static int pplugin_unregister (char *) */
400 /*
401  * Add a plugin's data set definition.
402  */
403 static int pplugin_register_data_set (char *name, AV *dataset)
405         int len = -1;
406         int i   = 0;
408         data_source_t *ds  = NULL;
409         data_set_t    *set = NULL;
411         ds_types_t *types = NULL;
413         if ((NULL == name) || (NULL == dataset))
414                 return -1;
416         len = Perl_av_len (perl, dataset);
418         if (-1 == len)
419                 return -1;
421         ds  = (data_source_t *)smalloc ((len + 1) * sizeof (data_source_t));
422         set = (data_set_t *)smalloc (sizeof (data_set_t));
424         types = (ds_types_t *)smalloc (sizeof (ds_types_t));
425         types->len = len + 1;
426         types->values = (int *)smalloc ((types->len) * sizeof (int));
428         for (i = 0; i <= len; ++i) {
429                 SV **elem = Perl_av_fetch (perl, dataset, i, 0);
431                 if (NULL == elem)
432                         return -1;
434                 if (! (SvROK (*elem) && (SVt_PVHV == SvTYPE (SvRV (*elem))))) {
435                         log_err ("pplugin_register_data_set: Invalid data source.");
436                         return -1;
437                 }
439                 if (-1 == hv2data_source ((HV *)SvRV (*elem), &ds[i]))
440                         return -1;
442                 types->values[i] = ds[i].type;
443                 log_debug ("pplugin_register_data_set: "
444                                 "DS.name = \"%s\", DS.type = %i, DS.min = %f, DS.max = %f",
445                                 ds[i].name, ds[i].type, ds[i].min, ds[i].max);
446         }
448         if (NULL == Perl_hv_store (perl, data_sets, name, strlen (name),
449                         Perl_sv_setref_pv (perl, Perl_newSV (perl, 0), 0, types), 0))
450                 return -1;
452         strncpy (set->type, name, DATA_MAX_NAME_LEN);
453         set->type[DATA_MAX_NAME_LEN - 1] = '\0';
455         set->ds_num = len + 1;
456         set->ds = ds;
457         return plugin_register_data_set (set);
458 } /* static int pplugin_register_data_set (char *, SV *) */
460 /*
461  * Remove a plugin's data set definition.
462  */
463 static int pplugin_unregister_data_set (char *name)
465         SV *tmp = NULL;
467         if (NULL == name)
468                 return 0;
470         /* freeing the allocated memory of the element itself (ds_types_t *)
471          * causes a segfault during perl_destruct () thus I assume perl somehow
472          * takes care of this... */
474         tmp = Perl_hv_delete (perl, data_sets, name, strlen (name), 0);
475         if (NULL != tmp) {
476                 ds_types_t *ds = (ds_types_t *)SvIV ((SV *)SvRV (tmp));
477                 sfree (ds->values);
478         }
479         return plugin_unregister_data_set (name);
480 } /* static int pplugin_unregister_data_set (char *) */
482 /*
483  * Submit the values to the write functions.
484  *
485  * value list:
486  * {
487  *   values => [ @values ],
488  *   time   => $time,
489  *   host   => $host,
490  *   plugin => $plugin,
491  *   plugin_instance => $pinstance,
492  *   type_instance   => $tinstance,
493  * }
494  */
495 static int pplugin_dispatch_values (char *name, HV *values)
497         value_list_t list = VALUE_LIST_INIT;
498         value_t      *val = NULL;
500         SV **tmp = NULL;
502         int ret = 0;
504         if ((NULL == name) || (NULL == values))
505                 return -1;
507         if ((NULL == (tmp = Perl_hv_fetch (perl, values, "values", 6, 0)))
508                         || (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp)))))) {
509                 log_err ("pplugin_dispatch_values: No valid values given.");
510                 return -1;
511         }
513         {
514                 AV  *array = (AV *)SvRV (*tmp);
515                 int len    = Perl_av_len (perl, array) + 1;
517                 val = (value_t *)smalloc (len * sizeof (value_t));
519                 list.values_len = av2value (name, (AV *)SvRV (*tmp), val, len);
520                 list.values = val;
522                 if (-1 == list.values_len) {
523                         sfree (val);
524                         return -1;
525                 }
526         }
528         if (NULL != (tmp = Perl_hv_fetch (perl, values, "time", 4, 0))) {
529                 list.time = (time_t)SvIV (*tmp);
530         }
531         else {
532                 list.time = time (NULL);
533         }
535         if (NULL != (tmp = Perl_hv_fetch (perl, values, "host", 4, 0))) {
536                 strncpy (list.host, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
537                 list.host[DATA_MAX_NAME_LEN - 1] = '\0';
538         }
539         else {
540                 strcpy (list.host, hostname_g);
541         }
543         if (NULL != (tmp = Perl_hv_fetch (perl, values, "plugin", 6, 0))) {
544                 strncpy (list.plugin, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
545                 list.plugin[DATA_MAX_NAME_LEN - 1] = '\0';
546         }
548         if (NULL != (tmp = Perl_hv_fetch (perl, values,
549                         "plugin_instance", 15, 0))) {
550                 strncpy (list.plugin_instance, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
551                 list.plugin_instance[DATA_MAX_NAME_LEN - 1] = '\0';
552         }
554         if (NULL != (tmp = Perl_hv_fetch (perl, values, "type_instance", 13, 0))) {
555                 strncpy (list.type_instance, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
556                 list.type_instance[DATA_MAX_NAME_LEN - 1] = '\0';
557         }
559         ret = plugin_dispatch_values (name, &list);
561         sfree (val);
562         return ret;
563 } /* static int pplugin_dispatch_values (char *, HV *) */
565 /*
566  * Call a plugin's working function.
567  */
568 static int pplugin_call (int type, char *name, SV *sub, va_list ap)
570         int retvals = 0;
571         I32 xflags  = G_NOARGS;
573         int ret = 0;
575         dSP;
577         if ((type < 0) || (type >= PLUGIN_TYPES))
578                 return -1;
580         ENTER;
581         SAVETMPS;
583         PUSHMARK (SP);
585         if (PLUGIN_WRITE == type) {
586                 /*
587                  * $_[0] = $plugin_type;
588                  *
589                  * $_[1] =
590                  * [
591                  *   {
592                  *     name => $ds_name,
593                  *     type => $ds_type,
594                  *     min  => $ds_min,
595                  *     max  => $ds_max
596                  *   },
597                  *   ...
598                  * ];
599                  *
600                  * $_[2] =
601                  * {
602                  *   values => [ $v1, ... ],
603                  *   time   => $time,
604                  *   host   => $hostname,
605                  *   plugin => $plugin,
606                  *   plugin_instance => $instance,
607                  *   type_instance   => $type_instance
608                  * };
609                  */
610                 data_set_t   *ds;
611                 value_list_t *vl;
613                 AV *pds = Perl_newAV (perl);
614                 HV *pvl = Perl_newHV (perl);
616                 ds = va_arg (ap, data_set_t *);
617                 vl = va_arg (ap, value_list_t *);
619                 if (-1 == data_set2av (ds, pds))
620                         return -1;
622                 if (-1 == value_list2hv (vl, ds, pvl))
623                         return -1;
625                 XPUSHs (sv_2mortal (Perl_newSVpv (perl, ds->type, 0)));
626                 XPUSHs (sv_2mortal (Perl_newRV_noinc (perl, (SV *)pds)));
627                 XPUSHs (sv_2mortal (Perl_newRV_noinc (perl, (SV *)pvl)));
629                 xflags = 0;
630         }
631         else if (PLUGIN_LOG == type) {
632                 /*
633                  * $_[0] = $level;
634                  *
635                  * $_[1] = $message;
636                  */
637                 XPUSHs (sv_2mortal (Perl_newSViv (perl, va_arg (ap, int))));
638                 XPUSHs (sv_2mortal (Perl_newSVpv (perl, va_arg (ap, char *), 0)));
640                 xflags = 0;
641         }
643         PUTBACK;
645         /* prevent an endless loop */
646         if (PLUGIN_LOG != type)
647                 log_debug ("pplugin_call: executing %s::%s->%s()",
648                                 base_name, name, plugin_types[type]);
650         retvals = Perl_call_sv (perl, sub, G_SCALAR | xflags);
652         SPAGAIN;
653         if (1 > retvals) {
654                 if (PLUGIN_LOG != type)
655                         log_warn ("pplugin_call: "
656                                         "%s::%s->%s() returned void - assuming true",
657                                         base_name, name, plugin_types[type]);
658         }
659         else {
660                 SV *tmp = POPs;
661                 if (! SvTRUE (tmp))
662                         ret = -1;
663         }
665         PUTBACK;
666         FREETMPS;
667         LEAVE;
668         return ret;
669 } /* static int pplugin_call (int, char *, SV *, va_list) */
671 /*
672  * Call all working functions of the given type.
673  */
674 static int pplugin_call_all (int type, ...)
676         SV *tmp = NULL;
678         char *plugin;
679         I32  len;
681         if ((type < 0) || (type >= PLUGIN_TYPES))
682                 return -1;
684         if (0 == Perl_hv_iterinit (perl, plugins[type]))
685                 return 0;
687         while (NULL != (tmp = Perl_hv_iternextsv (perl, plugins[type],
688                         &plugin, &len))) {
689                 pplugin_t *p;
690                 va_list   ap;
692                 int status;
694                 va_start (ap, type);
696                 p = (pplugin_t *)SvIV ((SV *)SvRV (tmp));
698                 if (p->wait_left > 0)
699                         p->wait_left -= interval_g;
701                 if (p->wait_left > 0)
702                         continue;
704                 if (0 == (status = pplugin_call (type, plugin, p->sub, ap))) {
705                         p->wait_left = 0;
706                         p->wait_time = interval_g;
707                 }
708                 else if (PLUGIN_READ == type) {
709                         p->wait_left = p->wait_time;
710                         p->wait_time <<= 1;
712                         if (p->wait_time > 86400)
713                                 p->wait_time = 86400;
715                         log_warn ("%s->read() failed. Will suspend it for %i seconds.",
716                                         plugin, p->wait_left);
717                 }
718                 else if (PLUGIN_INIT == type) {
719                         int i = 0;
721                         log_err ("%s->init() failed. Plugin will be disabled.",
722                                         plugin, status);
724                         for (i = 0; i < PLUGIN_TYPES; ++i)
725                                 pplugin_unregister (i, plugin);
726                 }
727                 else if (PLUGIN_LOG != type) {
728                         log_warn ("%s->%s() failed with status %i.",
729                                         plugin, plugin_types[type], status);
730                 }
732                 va_end (ap);
733         }
734         return 0;
735 } /* static int pplugin_call_all (int, ...) */
738 /*
739  * Exported Perl API.
740  */
742 /*
743  * Collectd::plugin_register (type, name, data).
744  *
745  * type:
746  *   init, read, write, shutdown, data set
747  *
748  * name:
749  *   name of the plugin
750  *
751  * data:
752  *   reference to the plugin's subroutine that does the work or the data set
753  *   definition
754  */
755 static XS (Collectd_plugin_register)
757         int type  = 0;
758         SV  *data = NULL;
760         int ret = 0;
762         dXSARGS;
764         if (3 != items) {
765                 log_err ("Usage: Collectd::plugin_register(type, name, data)");
766                 XSRETURN_EMPTY;
767         }
769         log_debug ("Collectd::plugin_register: "
770                         "type = \"%i\", name = \"%s\", \"%s\"",
771                         (int)SvIV (ST (0)), SvPV_nolen (ST (1)), SvPV_nolen (ST (2)));
773         type = (int)SvIV (ST (0));
774         data = ST (2);
776         if ((type >= 0) && (type < PLUGIN_TYPES)
777                         && SvROK (data) && (SVt_PVCV == SvTYPE (SvRV (data)))) {
778                 ret = pplugin_register (type, SvPV_nolen (ST (1)), data);
779         }
780         else if ((type == PLUGIN_DATASET)
781                         && SvROK (data) && (SVt_PVAV == SvTYPE (SvRV (data)))) {
782                 ret = pplugin_register_data_set (SvPV_nolen (ST (1)),
783                                 (AV *)SvRV (data));
784         }
785         else {
786                 log_err ("Collectd::plugin_register: Invalid data.");
787                 XSRETURN_EMPTY;
788         }
790         if (0 == ret)
791                 XSRETURN_YES;
792         else
793                 XSRETURN_EMPTY;
794 } /* static XS (Collectd_plugin_register) */
796 /*
797  * Collectd::plugin_unregister (type, name).
798  *
799  * type:
800  *   init, read, write, shutdown, data set
801  *
802  * name:
803  *   name of the plugin
804  */
805 static XS (Collectd_plugin_unregister)
807         int type = 0;
808         int ret  = 0;
810         dXSARGS;
812         if (2 != items) {
813                 log_err ("Usage: Collectd::plugin_unregister(type, name)");
814                 XSRETURN_EMPTY;
815         }
817         log_debug ("Collectd::plugin_unregister: type = \"%i\", name = \"%s\"",
818                         (int)SvIV (ST (0)), SvPV_nolen (ST (1)));
820         type = (int)SvIV (ST (0));
822         if ((type >= 0) && (type < PLUGIN_TYPES)) {
823                 ret = pplugin_unregister (type, SvPV_nolen (ST (1)));
824         }
825         else if (type == PLUGIN_DATASET) {
826                 ret = pplugin_unregister_data_set (SvPV_nolen (ST (1)));
827         }
828         else {
829                 log_err ("Collectd::plugin_unregister: Invalid type.");
830                 XSRETURN_EMPTY;
831         }
833         if (0 == ret)
834                 XSRETURN_YES;
835         else
836                 XSRETURN_EMPTY;
837 } /* static XS (Collectd_plugin_unregister) */
839 /*
840  * Collectd::plugin_dispatch_values (name, values).
841  *
842  * name:
843  *   name of the plugin
844  *
845  * values:
846  *   value list to submit
847  */
848 static XS (Collectd_plugin_dispatch_values)
850         SV *values = NULL;
852         int ret = 0;
854         dXSARGS;
856         if (2 != items) {
857                 log_err ("Usage: Collectd::plugin_dispatch_values(name, values)");
858                 XSRETURN_EMPTY;
859         }
861         log_debug ("Collectd::plugin_dispatch_values: "
862                         "name = \"%s\", values=\"%s\"",
863                         SvPV_nolen (ST (0)), SvPV_nolen (ST (1)));
865         values = ST (1);
867         if (! (SvROK (values) && (SVt_PVHV == SvTYPE (SvRV (values))))) {
868                 log_err ("Collectd::plugin_dispatch_values: Invalid values.");
869                 XSRETURN_EMPTY;
870         }
872         if ((NULL == ST (0)) || (NULL == values))
873                 XSRETURN_EMPTY;
875         ret = pplugin_dispatch_values (SvPV_nolen (ST (0)), (HV *)SvRV (values));
877         if (0 == ret)
878                 XSRETURN_YES;
879         else
880                 XSRETURN_EMPTY;
881 } /* static XS (Collectd_plugin_dispatch_values) */
883 /*
884  * Collectd::plugin_log (level, message).
885  *
886  * level:
887  *   log level (LOG_DEBUG, ... LOG_ERR)
888  *
889  * message:
890  *   log message
891  */
892 static XS (Collectd_plugin_log)
894         dXSARGS;
896         if (2 != items) {
897                 log_err ("Usage: Collectd::plugin_log(level, message)");
898                 XSRETURN_EMPTY;
899         }
901         log_debug ("Collectd::plugin_log: level = %i, message = \"%s\"",
902                         SvIV (ST (0)), SvPV_nolen (ST (1)));
903         plugin_log (SvIV (ST (0)), SvPV_nolen (ST (1)));
904         XSRETURN_YES;
905 } /* static XS (Collectd_plugin_log) */
907 /*
908  * Collectd::bootstrap ().
909  */
910 static XS (boot_Collectd)
912         HV   *stash = NULL;
913         char *file  = __FILE__;
915         struct {
916                 char name[64];
917                 SV   *value;
918         } consts[] =
919         {
920                 { "Collectd::TYPE_INIT",       Perl_newSViv (perl, PLUGIN_INIT) },
921                 { "Collectd::TYPE_READ",       Perl_newSViv (perl, PLUGIN_READ) },
922                 { "Collectd::TYPE_WRITE",      Perl_newSViv (perl, PLUGIN_WRITE) },
923                 { "Collectd::TYPE_SHUTDOWN",   Perl_newSViv (perl, PLUGIN_SHUTDOWN) },
924                 { "Collectd::TYPE_LOG",        Perl_newSViv (perl, PLUGIN_LOG) },
925                 { "Collectd::TYPE_DATASET",    Perl_newSViv (perl, PLUGIN_DATASET) },
926                 { "Collectd::DS_TYPE_COUNTER", Perl_newSViv (perl, DS_TYPE_COUNTER) },
927                 { "Collectd::DS_TYPE_GAUGE",   Perl_newSViv (perl, DS_TYPE_GAUGE) },
928                 { "Collectd::LOG_ERR",         Perl_newSViv (perl, LOG_ERR) },
929                 { "Collectd::LOG_WARNING",     Perl_newSViv (perl, LOG_WARNING) },
930                 { "Collectd::LOG_NOTICE",      Perl_newSViv (perl, LOG_NOTICE) },
931                 { "Collectd::LOG_INFO",        Perl_newSViv (perl, LOG_INFO) },
932                 { "Collectd::LOG_DEBUG",       Perl_newSViv (perl, LOG_DEBUG) },
933                 { "", NULL }
934         };
936         int i = 0;
938         dXSARGS;
940         if ((1 > items) || (2 < items)) {
941                 log_err ("Usage: Collectd::bootstrap(name[, version])");
942                 XSRETURN_EMPTY;
943         }
945         XS_VERSION_BOOTCHECK;
947         /* register API */
948         for (i = 0; NULL != api[i].f; ++i)
949                 Perl_newXS (perl, api[i].name, api[i].f, file);
951         stash = Perl_gv_stashpv (perl, "Collectd", 1);
953         /* export "constants" */
954         for (i = 0; NULL != consts[i].value; ++i)
955                 Perl_newCONSTSUB (perl, stash, consts[i].name, consts[i].value);
956         XSRETURN_YES;
957 } /* static XS (boot_Collectd) */
960 /*
961  * Interface to collectd.
962  */
964 static int perl_init (void)
966         if (NULL == perl)
967                 return 0;
969         PERL_SET_CONTEXT (perl);
970         return pplugin_call_all (PLUGIN_INIT);
971 } /* static int perl_init (void) */
973 static int perl_read (void)
975         if (NULL == perl)
976                 return 0;
978         PERL_SET_CONTEXT (perl);
979         return pplugin_call_all (PLUGIN_READ);
980 } /* static int perl_read (void) */
982 static int perl_write (const data_set_t *ds, const value_list_t *vl)
984         if (NULL == perl)
985                 return 0;
987         PERL_SET_CONTEXT (perl);
988         return pplugin_call_all (PLUGIN_WRITE, ds, vl);
989 } /* static int perl_write (const data_set_t *, const value_list_t *) */
991 static void perl_log (int level, const char *msg)
993         if (NULL == perl)
994                 return;
996         PERL_SET_CONTEXT (perl);
997         pplugin_call_all (PLUGIN_LOG, level, msg);
998         return;
999 } /* static void perl_log (int, const char *) */
1001 static int perl_shutdown (void)
1003         int i   = 0;
1004         int ret = 0;
1006         plugin_unregister_log ("perl");
1007         plugin_unregister_config ("perl");
1008         plugin_unregister_init ("perl");
1009         plugin_unregister_read ("perl");
1010         plugin_unregister_write ("perl");
1012         if (NULL == perl)
1013                 return 0;
1015         PERL_SET_CONTEXT (perl);
1016         ret = pplugin_call_all (PLUGIN_SHUTDOWN);
1018         for (i = 0; i < PLUGIN_TYPES; ++i) {
1019                 if (0 < Perl_hv_iterinit (perl, plugins[i])) {
1020                         char *k = NULL;
1021                         I32  l  = 0;
1023                         while (NULL != Perl_hv_iternextsv (perl, plugins[i], &k, &l)) {
1024                                 pplugin_unregister (i, k);
1025                         }
1026                 }
1028                 Perl_hv_undef (perl, plugins[i]);
1029         }
1031         if (0 < Perl_hv_iterinit (perl, data_sets)) {
1032                 char *k = NULL;
1033                 I32  l  = 0;
1035                 while (NULL != Perl_hv_iternextsv (perl, data_sets, &k, &l)) {
1036                         pplugin_unregister_data_set (k);
1037                 }
1038         }
1040         Perl_hv_undef (perl, data_sets);
1042 #if COLLECT_DEBUG
1043         Perl_sv_report_used (perl);
1044 #endif /* COLLECT_DEBUG */
1046         perl_destruct (perl);
1047         perl_free (perl);
1048         perl = NULL;
1050         PERL_SYS_TERM ();
1052         plugin_unregister_shutdown ("perl");
1053         return ret;
1054 } /* static void perl_shutdown (void) */
1056 static void xs_init (pTHX)
1058         char *file = __FILE__;
1060         dXSUB_SYS;
1062         /* build the Collectd module into the perl interpreter */
1063         Perl_newXS (perl, "Collectd::bootstrap", boot_Collectd, file);
1065         /* enable usage of Perl modules using shared libraries */
1066         Perl_newXS (perl, "DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
1067         return;
1068 } /* static void xs_init (pTHX) */
1070 /* Initialize the global Perl interpreter. */
1071 static int init_pi (int argc, char **argv)
1073         int i = 0;
1075         if (NULL != perl)
1076                 return 0;
1078         log_info ("Initializing Perl interpreter...");
1079 #if COLLECT_DEBUG
1080         for (i = 0; i < argc; ++i)
1081                 log_debug ("argv[%i] = \"%s\"", i, argv[i]);
1082 #endif /* COLLECT_DEBUG */
1084         PERL_SYS_INIT3 (&argc, &argv, &environ);
1086         if (NULL == (perl = perl_alloc ())) {
1087                 log_err ("module_register: Not enough memory.");
1088                 exit (3);
1089         }
1090         perl_construct (perl);
1092         PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
1094         if (0 != perl_parse (perl, xs_init, argc, argv, NULL)) {
1095                 log_err ("module_register: Unable to bootstrap Collectd.");
1096                 exit (1);
1097         }
1098         perl_run (perl);
1100         for (i = 0; i < PLUGIN_TYPES; ++i)
1101                 plugins[i] = Perl_newHV (perl);
1103         data_sets = Perl_newHV (perl);
1105         plugin_register_log ("perl", perl_log);
1106         plugin_register_init ("perl", perl_init);
1108         plugin_register_read ("perl", perl_read);
1110         plugin_register_write ("perl", perl_write);
1111         plugin_register_shutdown ("perl", perl_shutdown);
1112         return 0;
1113 } /* static int init_pi (const char **, const int) */
1115 static int perl_config (const char *key, const char *value)
1117         log_debug ("perl_config: key = \"%s\", value=\"%s\"", key, value);
1119         if (0 == strcasecmp (key, "LoadPlugin")) {
1120                 char module_name[DATA_MAX_NAME_LEN];
1122                 if (get_module_name (module_name, sizeof (module_name), value)
1123                                 == NULL) {
1124                         log_err ("Invalid module name %s", value);
1125                         return (1);
1126                 } /* if (get_module_name == NULL) */
1128                 init_pi (perl_argc, perl_argv);
1130                 log_info ("perl_config: loading perl plugin \"%s\"", value);
1131                 Perl_load_module (perl, PERL_LOADMOD_NOIMPORT,
1132                                 Perl_newSVpv (perl, module_name, strlen (module_name)),
1133                                 Nullsv);
1134         }
1135         else if (0 == strcasecmp (key, "BaseName")) {
1136                 log_debug ("perl_config: Setting plugin basename to \"%s\"", value);
1137                 strncpy (base_name, value, sizeof (base_name));
1138                 base_name[sizeof (base_name) - 1] = '\0';
1139         }
1140         else if (0 == strcasecmp (key, "IncludeDir")) {
1141                 perl_argv = (char **)realloc (perl_argv,
1142                                 (++perl_argc + 1) * sizeof (char *));
1144                 if (NULL == perl_argv) {
1145                         log_err ("perl_config: Not enough memory.");
1146                         exit (3);
1147                 }
1149                 perl_argv[perl_argc - 1] = (char *)smalloc (strlen (value) + 3);
1150                 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
1151                 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen (value) + 1);
1153                 perl_argv[perl_argc] = NULL;
1154         }
1155         else {
1156                 return -1;
1157         }
1158         return 0;
1159 } /* static int perl_config (char *, char *) */
1161 void module_register (void)
1163         perl_argc = 4;
1164         perl_argv = (char **)smalloc ((perl_argc + 1) * sizeof (char *));
1166         /* default options for the Perl interpreter */
1167         perl_argv[0] = "";
1168         perl_argv[1] = "-MCollectd";
1169         perl_argv[2] = "-e";
1170         perl_argv[3] = "1";
1171         perl_argv[4] = NULL;
1173         plugin_register_config ("perl", perl_config, config_keys, config_keys_num);
1174         return;
1175 } /* void module_register (void) */
1177 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */