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