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