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