Merge branch 'collectd-4.3' into collectd-4.4
[collectd.git] / src / perl.c
1 /**
2  * collectd - src/perl.c
3  * Copyright (C) 2007, 2008  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 #define DONT_POISON_SPRINTF_YET 1
31 #include "collectd.h"
32 #undef DONT_POISON_SPRINTF_YET
33
34 #include "configfile.h"
35
36 #include <EXTERN.h>
37 #include <perl.h>
38
39 #if __GNUC__
40 # pragma GCC poison sprintf
41 #endif
42
43 #include <XSUB.h>
44
45 /* Some versions of Perl define their own version of DEBUG... :-/ */
46 #ifdef DEBUG
47 # undef DEBUG
48 #endif /* DEBUG */
49
50 /* ... while we want the definition found in plugin.h. */
51 #include "plugin.h"
52 #include "common.h"
53
54 #include <pthread.h>
55
56 #if !defined(USE_ITHREADS)
57 # error "Perl does not support ithreads!"
58 #endif /* !defined(USE_ITHREADS) */
59
60 /* clear the Perl sub's stack frame
61  * (this should only be used inside an XSUB) */
62 #define CLEAR_STACK_FRAME PL_stack_sp = PL_stack_base + *PL_markstack_ptr
63
64 #define PLUGIN_INIT     0
65 #define PLUGIN_READ     1
66 #define PLUGIN_WRITE    2
67 #define PLUGIN_SHUTDOWN 3
68 #define PLUGIN_LOG      4
69 #define PLUGIN_NOTIF    5
70 #define PLUGIN_FLUSH    6
71
72 #define PLUGIN_TYPES    7
73
74 #define PLUGIN_DATASET  255
75
76 #define log_debug(...) DEBUG ("perl: " __VA_ARGS__)
77 #define log_info(...) INFO ("perl: " __VA_ARGS__)
78 #define log_warn(...) WARNING ("perl: " __VA_ARGS__)
79 #define log_err(...) ERROR ("perl: " __VA_ARGS__)
80
81 /* this is defined in DynaLoader.a */
82 void boot_DynaLoader (PerlInterpreter *, CV *);
83
84 static XS (Collectd_plugin_register_ds);
85 static XS (Collectd_plugin_unregister_ds);
86 static XS (Collectd_plugin_dispatch_values);
87 static XS (Collectd_plugin_flush_one);
88 static XS (Collectd_plugin_flush_all);
89 static XS (Collectd_plugin_dispatch_notification);
90 static XS (Collectd_plugin_log);
91 static XS (Collectd_call_by_name);
92
93 /*
94  * private data types
95  */
96
97 typedef struct c_ithread_s {
98         /* the thread's Perl interpreter */
99         PerlInterpreter *interp;
100
101         /* double linked list of threads */
102         struct c_ithread_s *prev;
103         struct c_ithread_s *next;
104 } c_ithread_t;
105
106 typedef struct {
107         c_ithread_t *head;
108         c_ithread_t *tail;
109
110 #if COLLECT_DEBUG
111         /* some usage stats */
112         int number_of_threads;
113 #endif /* COLLECT_DEBUG */
114
115         pthread_mutex_t mutex;
116 } c_ithread_list_t;
117
118 /*
119  * private variables
120  */
121
122 /* if perl_threads != NULL perl_threads->head must
123  * point to the "base" thread */
124 static c_ithread_list_t *perl_threads = NULL;
125
126 /* the key used to store each pthread's ithread */
127 static pthread_key_t perl_thr_key;
128
129 static int    perl_argc = 0;
130 static char **perl_argv = NULL;
131
132 static char base_name[DATA_MAX_NAME_LEN] = "";
133
134 static struct {
135         char name[64];
136         XS ((*f));
137 } api[] =
138 {
139         { "Collectd::plugin_register_data_set",   Collectd_plugin_register_ds },
140         { "Collectd::plugin_unregister_data_set", Collectd_plugin_unregister_ds },
141         { "Collectd::plugin_dispatch_values",     Collectd_plugin_dispatch_values },
142         { "Collectd::plugin_flush_one",           Collectd_plugin_flush_one },
143         { "Collectd::plugin_flush_all",           Collectd_plugin_flush_all },
144         { "Collectd::plugin_dispatch_notification",
145                 Collectd_plugin_dispatch_notification },
146         { "Collectd::plugin_log",                 Collectd_plugin_log },
147         { "Collectd::call_by_name",               Collectd_call_by_name },
148         { "", NULL }
149 };
150
151 struct {
152         char name[64];
153         int  value;
154 } constants[] =
155 {
156         { "Collectd::TYPE_INIT",       PLUGIN_INIT },
157         { "Collectd::TYPE_READ",       PLUGIN_READ },
158         { "Collectd::TYPE_WRITE",      PLUGIN_WRITE },
159         { "Collectd::TYPE_SHUTDOWN",   PLUGIN_SHUTDOWN },
160         { "Collectd::TYPE_LOG",        PLUGIN_LOG },
161         { "Collectd::TYPE_NOTIF",      PLUGIN_NOTIF },
162         { "Collectd::TYPE_FLUSH",      PLUGIN_FLUSH },
163         { "Collectd::TYPE_DATASET",    PLUGIN_DATASET },
164         { "Collectd::DS_TYPE_COUNTER", DS_TYPE_COUNTER },
165         { "Collectd::DS_TYPE_GAUGE",   DS_TYPE_GAUGE },
166         { "Collectd::LOG_ERR",         LOG_ERR },
167         { "Collectd::LOG_WARNING",     LOG_WARNING },
168         { "Collectd::LOG_NOTICE",      LOG_NOTICE },
169         { "Collectd::LOG_INFO",        LOG_INFO },
170         { "Collectd::LOG_DEBUG",       LOG_DEBUG },
171         { "Collectd::NOTIF_FAILURE",   NOTIF_FAILURE },
172         { "Collectd::NOTIF_WARNING",   NOTIF_WARNING },
173         { "Collectd::NOTIF_OKAY",      NOTIF_OKAY },
174         { "", 0 }
175 };
176
177 struct {
178         char  name[64];
179         char *var;
180 } g_strings[] =
181 {
182         { "Collectd::hostname_g", hostname_g },
183         { "", NULL }
184 };
185
186 struct {
187         char  name[64];
188         int  *var;
189 } g_integers[] =
190 {
191         { "Collectd::interval_g", &interval_g },
192         { "", NULL }
193 };
194
195 /*
196  * Helper functions for data type conversion.
197  */
198
199 /*
200  * data source:
201  * [
202  *   {
203  *     name => $ds_name,
204  *     type => $ds_type,
205  *     min  => $ds_min,
206  *     max  => $ds_max
207  *   },
208  *   ...
209  * ]
210  */
211 static int hv2data_source (pTHX_ HV *hash, data_source_t *ds)
212 {
213         SV **tmp = NULL;
214
215         if ((NULL == hash) || (NULL == ds))
216                 return -1;
217
218         if (NULL != (tmp = hv_fetch (hash, "name", 4, 0))) {
219                 strncpy (ds->name, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
220                 ds->name[DATA_MAX_NAME_LEN - 1] = '\0';
221         }
222         else {
223                 log_err ("hv2data_source: No DS name given.");
224                 return -1;
225         }
226
227         if (NULL != (tmp = hv_fetch (hash, "type", 4, 0))) {
228                 ds->type = SvIV (*tmp);
229
230                 if ((DS_TYPE_COUNTER != ds->type) && (DS_TYPE_GAUGE != ds->type)) {
231                         log_err ("hv2data_source: Invalid DS type.");
232                         return -1;
233                 }
234         }
235         else {
236                 ds->type = DS_TYPE_COUNTER;
237         }
238
239         if (NULL != (tmp = hv_fetch (hash, "min", 3, 0)))
240                 ds->min = SvNV (*tmp);
241         else
242                 ds->min = NAN;
243
244         if (NULL != (tmp = hv_fetch (hash, "max", 3, 0)))
245                 ds->max = SvNV (*tmp);
246         else
247                 ds->max = NAN;
248         return 0;
249 } /* static data_source_t *hv2data_source (HV *) */
250
251 static int av2value (pTHX_ char *name, AV *array, value_t *value, int len)
252 {
253         const data_set_t *ds;
254
255         int i = 0;
256
257         if ((NULL == name) || (NULL == array) || (NULL == value))
258                 return -1;
259
260         if (av_len (array) < len - 1)
261                 len = av_len (array) + 1;
262
263         if (0 >= len)
264                 return -1;
265
266         ds = plugin_get_ds (name);
267         if (NULL == ds) {
268                 log_err ("av2value: Unknown dataset \"%s\"", name);
269                 return -1;
270         }
271
272         if (ds->ds_num < len) {
273                 log_warn ("av2value: Value length exceeds data set length.");
274                 len = ds->ds_num;
275         }
276
277         for (i = 0; i < len; ++i) {
278                 SV **tmp = av_fetch (array, i, 0);
279
280                 if (NULL != tmp) {
281                         if (DS_TYPE_COUNTER == ds->ds[i].type)
282                                 value[i].counter = SvIV (*tmp);
283                         else
284                                 value[i].gauge = SvNV (*tmp);
285                 }
286                 else {
287                         return -1;
288                 }
289         }
290         return len;
291 } /* static int av2value (char *, AV *, value_t *, int) */
292
293 static int data_set2av (pTHX_ data_set_t *ds, AV *array)
294 {
295         int i = 0;
296
297         if ((NULL == ds) || (NULL == array))
298                 return -1;
299
300         av_extend (array, ds->ds_num);
301
302         for (i = 0; i < ds->ds_num; ++i) {
303                 HV *source = newHV ();
304
305                 if (NULL == hv_store (source, "name", 4,
306                                 newSVpv (ds->ds[i].name, 0), 0))
307                         return -1;
308
309                 if (NULL == hv_store (source, "type", 4, newSViv (ds->ds[i].type), 0))
310                         return -1;
311
312                 if (! isnan (ds->ds[i].min))
313                         if (NULL == hv_store (source, "min", 3,
314                                         newSVnv (ds->ds[i].min), 0))
315                                 return -1;
316
317                 if (! isnan (ds->ds[i].max))
318                         if (NULL == hv_store (source, "max", 3,
319                                         newSVnv (ds->ds[i].max), 0))
320                                 return -1;
321
322                 if (NULL == av_store (array, i, newRV_noinc ((SV *)source)))
323                         return -1;
324         }
325         return 0;
326 } /* static int data_set2av (data_set_t *, AV *) */
327
328 static int value_list2hv (pTHX_ value_list_t *vl, data_set_t *ds, HV *hash)
329 {
330         AV *values = NULL;
331
332         int i   = 0;
333         int len = 0;
334
335         if ((NULL == vl) || (NULL == ds) || (NULL == hash))
336                 return -1;
337
338         len = vl->values_len;
339
340         if (ds->ds_num < len) {
341                 log_warn ("value2av: Value length exceeds data set length.");
342                 len = ds->ds_num;
343         }
344
345         values = newAV ();
346         av_extend (values, len - 1);
347
348         for (i = 0; i < len; ++i) {
349                 SV *val = NULL;
350
351                 if (DS_TYPE_COUNTER == ds->ds[i].type)
352                         val = newSViv (vl->values[i].counter);
353                 else
354                         val = newSVnv (vl->values[i].gauge);
355
356                 if (NULL == av_store (values, i, val)) {
357                         av_undef (values);
358                         return -1;
359                 }
360         }
361
362         if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0))
363                 return -1;
364
365         if (0 != vl->time)
366                 if (NULL == hv_store (hash, "time", 4, newSViv (vl->time), 0))
367                         return -1;
368
369         if ('\0' != vl->host[0])
370                 if (NULL == hv_store (hash, "host", 4, newSVpv (vl->host, 0), 0))
371                         return -1;
372
373         if ('\0' != vl->plugin[0])
374                 if (NULL == hv_store (hash, "plugin", 6, newSVpv (vl->plugin, 0), 0))
375                         return -1;
376
377         if ('\0' != vl->plugin_instance[0])
378                 if (NULL == hv_store (hash, "plugin_instance", 15,
379                                 newSVpv (vl->plugin_instance, 0), 0))
380                         return -1;
381
382         if ('\0' != vl->type_instance[0])
383                 if (NULL == hv_store (hash, "type_instance", 13,
384                                 newSVpv (vl->type_instance, 0), 0))
385                         return -1;
386         return 0;
387 } /* static int value2av (value_list_t *, data_set_t *, HV *) */
388
389 static int notification2hv (pTHX_ notification_t *n, HV *hash)
390 {
391         if (NULL == hv_store (hash, "severity", 8, newSViv (n->severity), 0))
392                 return -1;
393
394         if (0 != n->time)
395                 if (NULL == hv_store (hash, "time", 4, newSViv (n->time), 0))
396                         return -1;
397
398         if ('\0' != *n->message)
399                 if (NULL == hv_store (hash, "message", 7, newSVpv (n->message, 0), 0))
400                         return -1;
401
402         if ('\0' != *n->host)
403                 if (NULL == hv_store (hash, "host", 4, newSVpv (n->host, 0), 0))
404                         return -1;
405
406         if ('\0' != *n->plugin)
407                 if (NULL == hv_store (hash, "plugin", 6, newSVpv (n->plugin, 0), 0))
408                         return -1;
409
410         if ('\0' != *n->plugin_instance)
411                 if (NULL == hv_store (hash, "plugin_instance", 15,
412                                 newSVpv (n->plugin_instance, 0), 0))
413                         return -1;
414
415         if ('\0' != *n->type)
416                 if (NULL == hv_store (hash, "type", 4, newSVpv (n->type, 0), 0))
417                         return -1;
418
419         if ('\0' != *n->type_instance)
420                 if (NULL == hv_store (hash, "type_instance", 13,
421                                 newSVpv (n->type_instance, 0), 0))
422                         return -1;
423         return 0;
424 } /* static int notification2hv (notification_t *, HV *) */
425
426 /*
427  * Internal functions.
428  */
429
430 static char *get_module_name (char *buf, size_t buf_len, const char *module) {
431         int status = 0;
432         if (base_name[0] == '\0')
433                 status = snprintf (buf, buf_len, "%s", module);
434         else
435                 status = snprintf (buf, buf_len, "%s::%s", base_name, module);
436         if ((status < 0) || ((unsigned int)status >= buf_len))
437                 return (NULL);
438         buf[buf_len - 1] = '\0';
439         return (buf);
440 } /* char *get_module_name */
441
442 /*
443  * Add a plugin's data set definition.
444  */
445 static int pplugin_register_data_set (pTHX_ char *name, AV *dataset)
446 {
447         int len = -1;
448         int ret = 0;
449         int i   = 0;
450
451         data_source_t *ds  = NULL;
452         data_set_t    *set = NULL;
453
454         if ((NULL == name) || (NULL == dataset))
455                 return -1;
456
457         len = av_len (dataset);
458
459         if (-1 == len)
460                 return -1;
461
462         ds  = (data_source_t *)smalloc ((len + 1) * sizeof (data_source_t));
463         set = (data_set_t *)smalloc (sizeof (data_set_t));
464
465         for (i = 0; i <= len; ++i) {
466                 SV **elem = av_fetch (dataset, i, 0);
467
468                 if (NULL == elem)
469                         return -1;
470
471                 if (! (SvROK (*elem) && (SVt_PVHV == SvTYPE (SvRV (*elem))))) {
472                         log_err ("pplugin_register_data_set: Invalid data source.");
473                         return -1;
474                 }
475
476                 if (-1 == hv2data_source (aTHX_ (HV *)SvRV (*elem), &ds[i]))
477                         return -1;
478
479                 log_debug ("pplugin_register_data_set: "
480                                 "DS.name = \"%s\", DS.type = %i, DS.min = %f, DS.max = %f",
481                                 ds[i].name, ds[i].type, ds[i].min, ds[i].max);
482         }
483
484         strncpy (set->type, name, DATA_MAX_NAME_LEN);
485         set->type[DATA_MAX_NAME_LEN - 1] = '\0';
486
487         set->ds_num = len + 1;
488         set->ds = ds;
489
490         ret = plugin_register_data_set (set);
491
492         free (ds);
493         free (set);
494         return ret;
495 } /* static int pplugin_register_data_set (char *, SV *) */
496
497 /*
498  * Remove a plugin's data set definition.
499  */
500 static int pplugin_unregister_data_set (char *name)
501 {
502         if (NULL == name)
503                 return 0;
504         return plugin_unregister_data_set (name);
505 } /* static int pplugin_unregister_data_set (char *) */
506
507 /*
508  * Submit the values to the write functions.
509  *
510  * value list:
511  * {
512  *   values => [ @values ],
513  *   time   => $time,
514  *   host   => $host,
515  *   plugin => $plugin,
516  *   plugin_instance => $pinstance,
517  *   type_instance   => $tinstance,
518  * }
519  */
520 static int pplugin_dispatch_values (pTHX_ char *name, HV *values)
521 {
522         value_list_t list = VALUE_LIST_INIT;
523         value_t      *val = NULL;
524
525         SV **tmp = NULL;
526
527         int ret = 0;
528
529         if ((NULL == name) || (NULL == values))
530                 return -1;
531
532         if ((NULL == (tmp = hv_fetch (values, "values", 6, 0)))
533                         || (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp)))))) {
534                 log_err ("pplugin_dispatch_values: No valid values given.");
535                 return -1;
536         }
537
538         {
539                 AV  *array = (AV *)SvRV (*tmp);
540                 int len    = av_len (array) + 1;
541
542                 if (len <= 0)
543                         return -1;
544
545                 val = (value_t *)smalloc (len * sizeof (value_t));
546
547                 list.values_len = av2value (aTHX_ name, (AV *)SvRV (*tmp), val, len);
548                 list.values = val;
549
550                 if (-1 == list.values_len) {
551                         sfree (val);
552                         return -1;
553                 }
554         }
555
556         if (NULL != (tmp = hv_fetch (values, "time", 4, 0))) {
557                 list.time = (time_t)SvIV (*tmp);
558         }
559         else {
560                 list.time = time (NULL);
561         }
562
563         if (NULL != (tmp = hv_fetch (values, "host", 4, 0))) {
564                 strncpy (list.host, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
565                 list.host[DATA_MAX_NAME_LEN - 1] = '\0';
566         }
567         else {
568                 sstrncpy (list.host, hostname_g, sizeof (list.host));
569         }
570
571         if (NULL != (tmp = hv_fetch (values, "plugin", 6, 0))) {
572                 strncpy (list.plugin, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
573                 list.plugin[DATA_MAX_NAME_LEN - 1] = '\0';
574         }
575
576         if (NULL != (tmp = hv_fetch (values, "plugin_instance", 15, 0))) {
577                 strncpy (list.plugin_instance, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
578                 list.plugin_instance[DATA_MAX_NAME_LEN - 1] = '\0';
579         }
580
581         if (NULL != (tmp = hv_fetch (values, "type_instance", 13, 0))) {
582                 strncpy (list.type_instance, SvPV_nolen (*tmp), DATA_MAX_NAME_LEN);
583                 list.type_instance[DATA_MAX_NAME_LEN - 1] = '\0';
584         }
585
586         ret = plugin_dispatch_values (name, &list);
587
588         sfree (val);
589         return ret;
590 } /* static int pplugin_dispatch_values (char *, HV *) */
591
592 /*
593  * Dispatch a notification.
594  *
595  * notification:
596  * {
597  *   severity => $severity,
598  *   time     => $time,
599  *   message  => $msg,
600  *   host     => $host,
601  *   plugin   => $plugin,
602  *   type     => $type,
603  *   plugin_instance => $instance,
604  *   type_instance   => $type_instance
605  * }
606  */
607 static int pplugin_dispatch_notification (pTHX_ HV *notif)
608 {
609         notification_t n;
610
611         SV **tmp = NULL;
612
613         if (NULL == notif)
614                 return -1;
615
616         memset (&n, 0, sizeof (n));
617
618         if (NULL != (tmp = hv_fetch (notif, "severity", 8, 0)))
619                 n.severity = SvIV (*tmp);
620         else
621                 n.severity = NOTIF_FAILURE;
622
623         if (NULL != (tmp = hv_fetch (notif, "time", 4, 0)))
624                 n.time = (time_t)SvIV (*tmp);
625         else
626                 n.time = time (NULL);
627
628         if (NULL != (tmp = hv_fetch (notif, "message", 7, 0)))
629                 strncpy (n.message, SvPV_nolen (*tmp), sizeof (n.message));
630         n.message[sizeof (n.message) - 1] = '\0';
631
632         if (NULL != (tmp = hv_fetch (notif, "host", 4, 0)))
633                 strncpy (n.host, SvPV_nolen (*tmp), sizeof (n.host));
634         else
635                 strncpy (n.host, hostname_g, sizeof (n.host));
636         n.host[sizeof (n.host) - 1] = '\0';
637
638         if (NULL != (tmp = hv_fetch (notif, "plugin", 6, 0)))
639                 strncpy (n.plugin, SvPV_nolen (*tmp), sizeof (n.plugin));
640         n.plugin[sizeof (n.plugin) - 1] = '\0';
641
642         if (NULL != (tmp = hv_fetch (notif, "plugin_instance", 15, 0)))
643                 strncpy (n.plugin_instance, SvPV_nolen (*tmp),
644                                 sizeof (n.plugin_instance));
645         n.plugin_instance[sizeof (n.plugin_instance) - 1] = '\0';
646
647         if (NULL != (tmp = hv_fetch (notif, "type", 4, 0)))
648                 strncpy (n.type, SvPV_nolen (*tmp), sizeof (n.type));
649         n.type[sizeof (n.type) - 1] = '\0';
650
651         if (NULL != (tmp = hv_fetch (notif, "type_instance", 13, 0)))
652                 strncpy (n.type_instance, SvPV_nolen (*tmp), sizeof (n.type_instance));
653         n.type_instance[sizeof (n.type_instance) - 1] = '\0';
654         return plugin_dispatch_notification (&n);
655 } /* static int pplugin_dispatch_notification (HV *) */
656
657 /*
658  * Call all working functions of the given type.
659  */
660 static int pplugin_call_all (pTHX_ int type, ...)
661 {
662         int retvals = 0;
663
664         va_list ap;
665         int ret = 0;
666
667         dSP;
668
669         if ((type < 0) || (type >= PLUGIN_TYPES))
670                 return -1;
671
672         va_start (ap, type);
673
674         ENTER;
675         SAVETMPS;
676
677         PUSHMARK (SP);
678
679         XPUSHs (sv_2mortal (newSViv ((IV)type)));
680
681         if (PLUGIN_WRITE == type) {
682                 /*
683                  * $_[0] = $plugin_type;
684                  *
685                  * $_[1] =
686                  * [
687                  *   {
688                  *     name => $ds_name,
689                  *     type => $ds_type,
690                  *     min  => $ds_min,
691                  *     max  => $ds_max
692                  *   },
693                  *   ...
694                  * ];
695                  *
696                  * $_[2] =
697                  * {
698                  *   values => [ $v1, ... ],
699                  *   time   => $time,
700                  *   host   => $hostname,
701                  *   plugin => $plugin,
702                  *   plugin_instance => $instance,
703                  *   type_instance   => $type_instance
704                  * };
705                  */
706                 data_set_t   *ds;
707                 value_list_t *vl;
708
709                 AV *pds = newAV ();
710                 HV *pvl = newHV ();
711
712                 ds = va_arg (ap, data_set_t *);
713                 vl = va_arg (ap, value_list_t *);
714
715                 if (-1 == data_set2av (aTHX_ ds, pds)) {
716                         av_clear (pds);
717                         av_undef (pds);
718                         pds = Nullav;
719                         ret = -1;
720                 }
721
722                 if (-1 == value_list2hv (aTHX_ vl, ds, pvl)) {
723                         hv_clear (pvl);
724                         hv_undef (pvl);
725                         pvl = Nullhv;
726                         ret = -1;
727                 }
728
729                 XPUSHs (sv_2mortal (newSVpv (ds->type, 0)));
730                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
731                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
732         }
733         else if (PLUGIN_LOG == type) {
734                 /*
735                  * $_[0] = $level;
736                  *
737                  * $_[1] = $message;
738                  */
739                 XPUSHs (sv_2mortal (newSViv (va_arg (ap, int))));
740                 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
741         }
742         else if (PLUGIN_NOTIF == type) {
743                 /*
744                  * $_[0] =
745                  * {
746                  *   severity => $severity,
747                  *   time     => $time,
748                  *   message  => $msg,
749                  *   host     => $host,
750                  *   plugin   => $plugin,
751                  *   type     => $type,
752                  *   plugin_instance => $instance,
753                  *   type_instance   => $type_instance
754                  * };
755                  */
756                 notification_t *n;
757                 HV *notif = newHV ();
758
759                 n = va_arg (ap, notification_t *);
760
761                 if (-1 == notification2hv (aTHX_ n, notif)) {
762                         hv_clear (notif);
763                         hv_undef (notif);
764                         notif = Nullhv;
765                         ret = -1;
766                 }
767
768                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)notif)));
769         }
770         else if (PLUGIN_FLUSH == type) {
771                 /*
772                  * $_[0] = $timeout;
773                  */
774                 XPUSHs (sv_2mortal (newSViv (va_arg (ap, int))));
775         }
776
777         PUTBACK;
778
779         retvals = call_pv ("Collectd::plugin_call_all", G_SCALAR);
780
781         SPAGAIN;
782         if (0 < retvals) {
783                 SV *tmp = POPs;
784                 if (! SvTRUE (tmp))
785                         ret = -1;
786         }
787
788         PUTBACK;
789         FREETMPS;
790         LEAVE;
791
792         va_end (ap);
793         return ret;
794 } /* static int pplugin_call_all (int, ...) */
795
796 /*
797  * Exported Perl API.
798  */
799
800 /*
801  * Collectd::plugin_register_data_set (type, dataset).
802  *
803  * type:
804  *   type of the dataset
805  *
806  * dataset:
807  *   dataset to be registered
808  */
809 static XS (Collectd_plugin_register_ds)
810 {
811         SV  *data = NULL;
812         int ret   = 0;
813
814         dXSARGS;
815
816         if (2 != items) {
817                 log_err ("Usage: Collectd::plugin_register_data_set(type, dataset)");
818                 XSRETURN_EMPTY;
819         }
820
821         log_debug ("Collectd::plugin_register_data_set: "
822                         "type = \"%s\", dataset = \"%s\"",
823                         SvPV_nolen (ST (0)), SvPV_nolen (ST (1)));
824
825         data = ST (1);
826
827         if (SvROK (data) && (SVt_PVAV == SvTYPE (SvRV (data)))) {
828                 ret = pplugin_register_data_set (aTHX_ SvPV_nolen (ST (0)),
829                                 (AV *)SvRV (data));
830         }
831         else {
832                 log_err ("Collectd::plugin_register_data_set: Invalid data.");
833                 XSRETURN_EMPTY;
834         }
835
836         if (0 == ret)
837                 XSRETURN_YES;
838         else
839                 XSRETURN_EMPTY;
840 } /* static XS (Collectd_plugin_register_ds) */
841
842 /*
843  * Collectd::plugin_unregister_data_set (type).
844  *
845  * type:
846  *   type of the dataset
847  */
848 static XS (Collectd_plugin_unregister_ds)
849 {
850         dXSARGS;
851
852         if (1 != items) {
853                 log_err ("Usage: Collectd::plugin_unregister_data_set(type)");
854                 XSRETURN_EMPTY;
855         }
856
857         log_debug ("Collectd::plugin_unregister_data_set: type = \"%s\"",
858                         SvPV_nolen (ST (0)));
859
860         if (0 == pplugin_unregister_data_set (SvPV_nolen (ST (0))))
861                 XSRETURN_YES;
862         else
863                 XSRETURN_EMPTY;
864 } /* static XS (Collectd_plugin_register_ds) */
865
866 /*
867  * Collectd::plugin_dispatch_values (name, values).
868  *
869  * name:
870  *   name of the plugin
871  *
872  * values:
873  *   value list to submit
874  */
875 static XS (Collectd_plugin_dispatch_values)
876 {
877         SV *values = NULL;
878
879         int ret = 0;
880
881         dXSARGS;
882
883         if (2 != items) {
884                 log_err ("Usage: Collectd::plugin_dispatch_values(name, values)");
885                 XSRETURN_EMPTY;
886         }
887
888         log_debug ("Collectd::plugin_dispatch_values: "
889                         "name = \"%s\", values=\"%s\"",
890                         SvPV_nolen (ST (0)), SvPV_nolen (ST (1)));
891
892         values = ST (1);
893
894         if (! (SvROK (values) && (SVt_PVHV == SvTYPE (SvRV (values))))) {
895                 log_err ("Collectd::plugin_dispatch_values: Invalid values.");
896                 XSRETURN_EMPTY;
897         }
898
899         if ((NULL == ST (0)) || (NULL == values))
900                 XSRETURN_EMPTY;
901
902         ret = pplugin_dispatch_values (aTHX_ SvPV_nolen (ST (0)),
903                         (HV *)SvRV (values));
904
905         if (0 == ret)
906                 XSRETURN_YES;
907         else
908                 XSRETURN_EMPTY;
909 } /* static XS (Collectd_plugin_dispatch_values) */
910
911 /*
912  * Collectd::plugin_flush_one (timeout, name).
913  *
914  * timeout:
915  *   timeout to use when flushing the data
916  *
917  * name:
918  *   name of the plugin to flush
919  */
920 static XS (Collectd_plugin_flush_one)
921 {
922         dXSARGS;
923
924         if (2 != items) {
925                 log_err ("Usage: Collectd::plugin_flush_one(timeout, name)");
926                 XSRETURN_EMPTY;
927         }
928
929         log_debug ("Collectd::plugin_flush_one: timeout = %i, name = \"%s\"",
930                         (int)SvIV (ST (0)), SvPV_nolen (ST (1)));
931
932         if (0 == plugin_flush_one ((int)SvIV (ST (0)), SvPV_nolen (ST (1))))
933                 XSRETURN_YES;
934         else
935                 XSRETURN_EMPTY;
936 } /* static XS (Collectd_plugin_flush_one) */
937
938 /*
939  * Collectd::plugin_flush_all (timeout).
940  *
941  * timeout:
942  *   timeout to use when flushing the data
943  */
944 static XS (Collectd_plugin_flush_all)
945 {
946         dXSARGS;
947
948         if (1 != items) {
949                 log_err ("Usage: Collectd::plugin_flush_all(timeout)");
950                 XSRETURN_EMPTY;
951         }
952
953         log_debug ("Collectd::plugin_flush_all: timeout = %i", (int)SvIV (ST (0)));
954
955         plugin_flush_all ((int)SvIV (ST (0)));
956         XSRETURN_YES;
957 } /* static XS (Collectd_plugin_flush_all) */
958
959 /*
960  * Collectd::plugin_dispatch_notification (notif).
961  *
962  * notif:
963  *   notification to dispatch
964  */
965 static XS (Collectd_plugin_dispatch_notification)
966 {
967         SV *notif = NULL;
968
969         int ret = 0;
970
971         dXSARGS;
972
973         if (1 != items) {
974                 log_err ("Usage: Collectd::plugin_dispatch_notification(notif)");
975                 XSRETURN_EMPTY;
976         }
977
978         log_debug ("Collectd::plugin_dispatch_notification: notif = \"%s\"",
979                         SvPV_nolen (ST (0)));
980
981         notif = ST (0);
982
983         if (! (SvROK (notif) && (SVt_PVHV == SvTYPE (SvRV (notif))))) {
984                 log_err ("Collectd::plugin_dispatch_notification: Invalid notif.");
985                 XSRETURN_EMPTY;
986         }
987
988         ret = pplugin_dispatch_notification (aTHX_ (HV *)SvRV (notif));
989
990         if (0 == ret)
991                 XSRETURN_YES;
992         else
993                 XSRETURN_EMPTY;
994 } /* static XS (Collectd_plugin_dispatch_notification) */
995
996 /*
997  * Collectd::plugin_log (level, message).
998  *
999  * level:
1000  *   log level (LOG_DEBUG, ... LOG_ERR)
1001  *
1002  * message:
1003  *   log message
1004  */
1005 static XS (Collectd_plugin_log)
1006 {
1007         dXSARGS;
1008
1009         if (2 != items) {
1010                 log_err ("Usage: Collectd::plugin_log(level, message)");
1011                 XSRETURN_EMPTY;
1012         }
1013
1014         plugin_log (SvIV (ST (0)), SvPV_nolen (ST (1)));
1015         XSRETURN_YES;
1016 } /* static XS (Collectd_plugin_log) */
1017
1018 /*
1019  * Collectd::call_by_name (...).
1020  *
1021  * Call a Perl sub identified by its name passed through $Collectd::cb_name.
1022  */
1023 static XS (Collectd_call_by_name)
1024 {
1025         SV   *tmp  = NULL;
1026         char *name = NULL;
1027
1028         if (NULL == (tmp = get_sv ("Collectd::cb_name", 0))) {
1029                 sv_setpv (get_sv ("@", 1), "cb_name has not been set");
1030                 CLEAR_STACK_FRAME;
1031                 return;
1032         }
1033
1034         name = SvPV_nolen (tmp);
1035
1036         if (NULL == get_cv (name, 0)) {
1037                 sv_setpvf (get_sv ("@", 1), "unknown callback \"%s\"", name);
1038                 CLEAR_STACK_FRAME;
1039                 return;
1040         }
1041
1042         /* simply pass on the subroutine call without touching the stack,
1043          * thus leaving any arguments and return values in place */
1044         call_pv (name, 0);
1045 } /* static XS (Collectd_call_by_name) */
1046
1047 /*
1048  * collectd's perl interpreter based thread implementation.
1049  *
1050  * This has been inspired by Perl's ithreads introduced in version 5.6.0.
1051  */
1052
1053 /* must be called with perl_threads->mutex locked */
1054 static void c_ithread_destroy (c_ithread_t *ithread)
1055 {
1056         dTHXa (ithread->interp);
1057
1058         assert (NULL != perl_threads);
1059
1060         PERL_SET_CONTEXT (aTHX);
1061         log_debug ("Shutting down Perl interpreter %p...", aTHX);
1062
1063 #if COLLECT_DEBUG
1064         sv_report_used ();
1065
1066         --perl_threads->number_of_threads;
1067 #endif /* COLLECT_DEBUG */
1068
1069         perl_destruct (aTHX);
1070         perl_free (aTHX);
1071
1072         if (NULL == ithread->prev)
1073                 perl_threads->head = ithread->next;
1074         else
1075                 ithread->prev->next = ithread->next;
1076
1077         if (NULL == ithread->next)
1078                 perl_threads->tail = ithread->prev;
1079         else
1080                 ithread->next->prev = ithread->prev;
1081
1082         sfree (ithread);
1083         return;
1084 } /* static void c_ithread_destroy (c_ithread_t *) */
1085
1086 static void c_ithread_destructor (void *arg)
1087 {
1088         c_ithread_t *ithread = (c_ithread_t *)arg;
1089         c_ithread_t *t = NULL;
1090
1091         if (NULL == perl_threads)
1092                 return;
1093
1094         pthread_mutex_lock (&perl_threads->mutex);
1095
1096         for (t = perl_threads->head; NULL != t; t = t->next)
1097                 if (t == ithread)
1098                         break;
1099
1100         /* the ithread no longer exists */
1101         if (NULL == t)
1102                 return;
1103
1104         c_ithread_destroy (ithread);
1105
1106         pthread_mutex_unlock (&perl_threads->mutex);
1107         return;
1108 } /* static void c_ithread_destructor (void *) */
1109
1110 /* must be called with perl_threads->mutex locked */
1111 static c_ithread_t *c_ithread_create (PerlInterpreter *base)
1112 {
1113         c_ithread_t *t = NULL;
1114         dTHXa (NULL);
1115
1116         assert (NULL != perl_threads);
1117
1118         t = (c_ithread_t *)smalloc (sizeof (c_ithread_t));
1119         memset (t, 0, sizeof (c_ithread_t));
1120
1121         t->interp = (NULL == base)
1122                 ? NULL
1123                 : perl_clone (base, CLONEf_KEEP_PTR_TABLE);
1124
1125         aTHX = t->interp;
1126
1127         if ((NULL != base) && (NULL != PL_endav)) {
1128                 av_clear (PL_endav);
1129                 av_undef (PL_endav);
1130                 PL_endav = Nullav;
1131         }
1132
1133 #if COLLECT_DEBUG
1134         ++perl_threads->number_of_threads;
1135 #endif /* COLLECT_DEBUG */
1136
1137         t->next = NULL;
1138
1139         if (NULL == perl_threads->tail) {
1140                 perl_threads->head = t;
1141                 t->prev = NULL;
1142         }
1143         else {
1144                 perl_threads->tail->next = t;
1145                 t->prev = perl_threads->tail;
1146         }
1147
1148         perl_threads->tail = t;
1149
1150         pthread_setspecific (perl_thr_key, (const void *)t);
1151         return t;
1152 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
1153
1154 /*
1155  * Interface to collectd.
1156  */
1157
1158 static int perl_init (void)
1159 {
1160         dTHX;
1161
1162         if (NULL == perl_threads)
1163                 return 0;
1164
1165         if (NULL == aTHX) {
1166                 c_ithread_t *t = NULL;
1167
1168                 pthread_mutex_lock (&perl_threads->mutex);
1169                 t = c_ithread_create (perl_threads->head->interp);
1170                 pthread_mutex_unlock (&perl_threads->mutex);
1171
1172                 aTHX = t->interp;
1173         }
1174
1175         log_debug ("perl_init: c_ithread: interp = %p (active threads: %i)",
1176                         aTHX, perl_threads->number_of_threads);
1177         return pplugin_call_all (aTHX_ PLUGIN_INIT);
1178 } /* static int perl_init (void) */
1179
1180 static int perl_read (void)
1181 {
1182         dTHX;
1183
1184         if (NULL == perl_threads)
1185                 return 0;
1186
1187         if (NULL == aTHX) {
1188                 c_ithread_t *t = NULL;
1189
1190                 pthread_mutex_lock (&perl_threads->mutex);
1191                 t = c_ithread_create (perl_threads->head->interp);
1192                 pthread_mutex_unlock (&perl_threads->mutex);
1193
1194                 aTHX = t->interp;
1195         }
1196
1197         log_debug ("perl_read: c_ithread: interp = %p (active threads: %i)",
1198                         aTHX, perl_threads->number_of_threads);
1199         return pplugin_call_all (aTHX_ PLUGIN_READ);
1200 } /* static int perl_read (void) */
1201
1202 static int perl_write (const data_set_t *ds, const value_list_t *vl)
1203 {
1204         dTHX;
1205
1206         if (NULL == perl_threads)
1207                 return 0;
1208
1209         if (NULL == aTHX) {
1210                 c_ithread_t *t = NULL;
1211
1212                 pthread_mutex_lock (&perl_threads->mutex);
1213                 t = c_ithread_create (perl_threads->head->interp);
1214                 pthread_mutex_unlock (&perl_threads->mutex);
1215
1216                 aTHX = t->interp;
1217         }
1218
1219         log_debug ("perl_write: c_ithread: interp = %p (active threads: %i)",
1220                         aTHX, perl_threads->number_of_threads);
1221         return pplugin_call_all (aTHX_ PLUGIN_WRITE, ds, vl);
1222 } /* static int perl_write (const data_set_t *, const value_list_t *) */
1223
1224 static void perl_log (int level, const char *msg)
1225 {
1226         dTHX;
1227
1228         if (NULL == perl_threads)
1229                 return;
1230
1231         if (NULL == aTHX) {
1232                 c_ithread_t *t = NULL;
1233
1234                 pthread_mutex_lock (&perl_threads->mutex);
1235                 t = c_ithread_create (perl_threads->head->interp);
1236                 pthread_mutex_unlock (&perl_threads->mutex);
1237
1238                 aTHX = t->interp;
1239         }
1240
1241         pplugin_call_all (aTHX_ PLUGIN_LOG, level, msg);
1242         return;
1243 } /* static void perl_log (int, const char *) */
1244
1245 static int perl_notify (const notification_t *notif)
1246 {
1247         dTHX;
1248
1249         if (NULL == perl_threads)
1250                 return 0;
1251
1252         if (NULL == aTHX) {
1253                 c_ithread_t *t = NULL;
1254
1255                 pthread_mutex_lock (&perl_threads->mutex);
1256                 t = c_ithread_create (perl_threads->head->interp);
1257                 pthread_mutex_unlock (&perl_threads->mutex);
1258
1259                 aTHX = t->interp;
1260         }
1261         return pplugin_call_all (aTHX_ PLUGIN_NOTIF, notif);
1262 } /* static int perl_notify (const notification_t *) */
1263
1264 static int perl_flush (const int timeout)
1265 {
1266         dTHX;
1267
1268         if (NULL == perl_threads)
1269                 return 0;
1270
1271         if (NULL == aTHX) {
1272                 c_ithread_t *t = NULL;
1273
1274                 pthread_mutex_lock (&perl_threads->mutex);
1275                 t = c_ithread_create (perl_threads->head->interp);
1276                 pthread_mutex_unlock (&perl_threads->mutex);
1277
1278                 aTHX = t->interp;
1279         }
1280         return pplugin_call_all (aTHX_ PLUGIN_FLUSH, timeout);
1281 } /* static int perl_flush (const int) */
1282
1283 static int perl_shutdown (void)
1284 {
1285         c_ithread_t *t = NULL;
1286
1287         int ret = 0;
1288
1289         dTHX;
1290
1291         plugin_unregister_complex_config ("perl");
1292
1293         if (NULL == perl_threads)
1294                 return 0;
1295
1296         if (NULL == aTHX) {
1297                 c_ithread_t *t = NULL;
1298
1299                 pthread_mutex_lock (&perl_threads->mutex);
1300                 t = c_ithread_create (perl_threads->head->interp);
1301                 pthread_mutex_unlock (&perl_threads->mutex);
1302
1303                 aTHX = t->interp;
1304         }
1305
1306         log_debug ("perl_shutdown: c_ithread: interp = %p (active threads: %i)",
1307                         aTHX, perl_threads->number_of_threads);
1308
1309         plugin_unregister_log ("perl");
1310         plugin_unregister_notification ("perl");
1311         plugin_unregister_init ("perl");
1312         plugin_unregister_read ("perl");
1313         plugin_unregister_write ("perl");
1314         plugin_unregister_flush ("perl");
1315
1316         ret = pplugin_call_all (aTHX_ PLUGIN_SHUTDOWN);
1317
1318         pthread_mutex_lock (&perl_threads->mutex);
1319         t = perl_threads->tail;
1320
1321         while (NULL != t) {
1322                 c_ithread_t *thr = t;
1323
1324                 /* the pointer has to be advanced before destroying
1325                  * the thread as this will free the memory */
1326                 t = t->prev;
1327
1328                 c_ithread_destroy (thr);
1329         }
1330
1331         pthread_mutex_unlock (&perl_threads->mutex);
1332         pthread_mutex_destroy (&perl_threads->mutex);
1333
1334         sfree (perl_threads);
1335
1336         pthread_key_delete (perl_thr_key);
1337
1338         PERL_SYS_TERM ();
1339
1340         plugin_unregister_shutdown ("perl");
1341         return ret;
1342 } /* static void perl_shutdown (void) */
1343
1344 /*
1345  * Access functions for global variables.
1346  *
1347  * These functions implement the "magic" used to access
1348  * the global variables from Perl.
1349  */
1350
1351 static int g_pv_get (pTHX_ SV *var, MAGIC *mg)
1352 {
1353         char *pv = mg->mg_ptr;
1354         sv_setpv (var, pv);
1355         return 0;
1356 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
1357
1358 static int g_pv_set (pTHX_ SV *var, MAGIC *mg)
1359 {
1360         char *pv = mg->mg_ptr;
1361         strncpy (pv, SvPV_nolen (var), DATA_MAX_NAME_LEN);
1362         pv[DATA_MAX_NAME_LEN - 1] = '\0';
1363         return 0;
1364 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
1365
1366 static int g_iv_get (pTHX_ SV *var, MAGIC *mg)
1367 {
1368         int *iv = (int *)mg->mg_ptr;
1369         sv_setiv (var, *iv);
1370         return 0;
1371 } /* static int g_iv_get (pTHX_ SV *, MAGIC *) */
1372
1373 static int g_iv_set (pTHX_ SV *var, MAGIC *mg)
1374 {
1375         int *iv = (int *)mg->mg_ptr;
1376         *iv = (int)SvIV (var);
1377         return 0;
1378 } /* static int g_iv_set (pTHX_ SV *, MAGIC *) */
1379
1380 static MGVTBL g_pv_vtbl = { g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL };
1381 static MGVTBL g_iv_vtbl = { g_iv_get, g_iv_set, NULL, NULL, NULL, NULL, NULL };
1382
1383 /* bootstrap the Collectd module */
1384 static void xs_init (pTHX)
1385 {
1386         HV   *stash = NULL;
1387         SV   *tmp   = NULL;
1388         char *file  = __FILE__;
1389
1390         int i = 0;
1391
1392         dXSUB_SYS;
1393
1394         /* enable usage of Perl modules using shared libraries */
1395         newXS ("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
1396
1397         /* register API */
1398         for (i = 0; NULL != api[i].f; ++i)
1399                 newXS (api[i].name, api[i].f, file);
1400
1401         stash = gv_stashpv ("Collectd", 1);
1402
1403         /* export "constants" */
1404         for (i = 0; '\0' != constants[i].name[0]; ++i)
1405                 newCONSTSUB (stash, constants[i].name, newSViv (constants[i].value));
1406
1407         /* export global variables
1408          * by adding "magic" to the SV's representing the globale variables
1409          * perl is able to automagically call the get/set function when
1410          * accessing any such variable (this is basically the same as using
1411          * tie() in Perl) */
1412         /* global strings */
1413         for (i = 0; '\0' != g_strings[i].name[0]; ++i) {
1414                 tmp = get_sv (g_strings[i].name, 1);
1415                 sv_magicext (tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl,
1416                                 g_strings[i].var, 0);
1417         }
1418
1419         /* global integers */
1420         for (i = 0; '\0' != g_integers[i].name[0]; ++i) {
1421                 tmp = get_sv (g_integers[i].name, 1);
1422                 sv_magicext (tmp, NULL, PERL_MAGIC_ext, &g_iv_vtbl,
1423                                 (char *)g_integers[i].var, 0);
1424         }
1425         return;
1426 } /* static void xs_init (pTHX) */
1427
1428 /* Initialize the global Perl interpreter. */
1429 static int init_pi (int argc, char **argv)
1430 {
1431         dTHXa (NULL);
1432
1433         if (NULL != perl_threads)
1434                 return 0;
1435
1436         log_info ("Initializing Perl interpreter...");
1437 #if COLLECT_DEBUG
1438         {
1439                 int i = 0;
1440
1441                 for (i = 0; i < argc; ++i)
1442                         log_debug ("argv[%i] = \"%s\"", i, argv[i]);
1443         }
1444 #endif /* COLLECT_DEBUG */
1445
1446         if (0 != pthread_key_create (&perl_thr_key, c_ithread_destructor)) {
1447                 log_err ("init_pi: pthread_key_create failed");
1448
1449                 /* this must not happen - cowardly giving up if it does */
1450                 return -1;
1451         }
1452
1453 #ifdef __FreeBSD__
1454         /* On FreeBSD, PERL_SYS_INIT3 expands to some expression which
1455          * triggers a "value computed is not used" warning by gcc. */
1456         (void)
1457 #endif
1458         PERL_SYS_INIT3 (&argc, &argv, &environ);
1459
1460         perl_threads = (c_ithread_list_t *)smalloc (sizeof (c_ithread_list_t));
1461         memset (perl_threads, 0, sizeof (c_ithread_list_t));
1462
1463         pthread_mutex_init (&perl_threads->mutex, NULL);
1464         /* locking the mutex should not be necessary at this point
1465          * but let's just do it for the sake of completeness */
1466         pthread_mutex_lock (&perl_threads->mutex);
1467
1468         perl_threads->head = c_ithread_create (NULL);
1469         perl_threads->tail = perl_threads->head;
1470
1471         if (NULL == (perl_threads->head->interp = perl_alloc ())) {
1472                 log_err ("init_pi: Not enough memory.");
1473                 exit (3);
1474         }
1475
1476         aTHX = perl_threads->head->interp;
1477         pthread_mutex_unlock (&perl_threads->mutex);
1478
1479         perl_construct (aTHX);
1480
1481         PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
1482
1483         if (0 != perl_parse (aTHX_ xs_init, argc, argv, NULL)) {
1484                 log_err ("init_pi: Unable to bootstrap Collectd.");
1485
1486                 perl_destruct (perl_threads->head->interp);
1487                 perl_free (perl_threads->head->interp);
1488                 sfree (perl_threads);
1489
1490                 pthread_key_delete (perl_thr_key);
1491                 return -1;
1492         }
1493
1494         /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
1495         sv_setpv (get_sv ("0", 0), "collectd");
1496
1497         perl_run (aTHX);
1498
1499         plugin_register_log ("perl", perl_log);
1500         plugin_register_notification ("perl", perl_notify);
1501         plugin_register_init ("perl", perl_init);
1502
1503         plugin_register_read ("perl", perl_read);
1504
1505         plugin_register_write ("perl", perl_write);
1506         plugin_register_flush ("perl", perl_flush);
1507         plugin_register_shutdown ("perl", perl_shutdown);
1508         return 0;
1509 } /* static int init_pi (const char **, const int) */
1510
1511 /*
1512  * LoadPlugin "<Plugin>"
1513  */
1514 static int perl_config_loadplugin (pTHX_ oconfig_item_t *ci)
1515 {
1516         char module_name[DATA_MAX_NAME_LEN];
1517
1518         char *value = NULL;
1519
1520         if ((0 != ci->children_num) || (1 != ci->values_num)
1521                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1522                 log_err ("LoadPlugin expects a single string argument.");
1523                 return 1;
1524         }
1525
1526         value = ci->values[0].value.string;
1527
1528         if (NULL == get_module_name (module_name, sizeof (module_name), value)) {
1529                 log_err ("Invalid module name %s", value);
1530                 return (1);
1531         }
1532
1533         if (0 != init_pi (perl_argc, perl_argv))
1534                 return -1;
1535
1536         assert (NULL != perl_threads);
1537         assert (NULL != perl_threads->head);
1538
1539         aTHX = perl_threads->head->interp;
1540
1541         log_debug ("perl_config: loading perl plugin \"%s\"", value);
1542         load_module (PERL_LOADMOD_NOIMPORT,
1543                         newSVpv (module_name, strlen (module_name)), Nullsv);
1544         return 0;
1545 } /* static int perl_config_loadplugin (oconfig_item_it *) */
1546
1547 /*
1548  * BaseName "<Name>"
1549  */
1550 static int perl_config_basename (pTHX_ oconfig_item_t *ci)
1551 {
1552         char *value = NULL;
1553
1554         if ((0 != ci->children_num) || (1 != ci->values_num)
1555                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1556                 log_err ("BaseName expects a single string argument.");
1557                 return 1;
1558         }
1559
1560         value = ci->values[0].value.string;
1561
1562         log_debug ("perl_config: Setting plugin basename to \"%s\"", value);
1563         strncpy (base_name, value, sizeof (base_name));
1564         base_name[sizeof (base_name) - 1] = '\0';
1565         return 0;
1566 } /* static int perl_config_basename (oconfig_item_it *) */
1567
1568 /*
1569  * EnableDebugger "<Package>"|""
1570  */
1571 static int perl_config_enabledebugger (pTHX_ oconfig_item_t *ci)
1572 {
1573         char *value = NULL;
1574
1575         if ((0 != ci->children_num) || (1 != ci->values_num)
1576                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1577                 log_err ("EnableDebugger expects a single string argument.");
1578                 return 1;
1579         }
1580
1581         if (NULL != perl_threads) {
1582                 log_warn ("EnableDebugger has no effects if used after LoadPlugin.");
1583                 return 1;
1584         }
1585
1586         value = ci->values[0].value.string;
1587
1588         perl_argv = (char **)realloc (perl_argv,
1589                         (++perl_argc + 1) * sizeof (char *));
1590
1591         if (NULL == perl_argv) {
1592                 log_err ("perl_config: Not enough memory.");
1593                 exit (3);
1594         }
1595
1596         if ('\0' == value[0]) {
1597                 perl_argv[perl_argc - 1] = "-d";
1598         }
1599         else {
1600                 perl_argv[perl_argc - 1] = (char *)smalloc (strlen (value) + 4);
1601                 sstrncpy (perl_argv[perl_argc - 1], "-d:", 4);
1602                 sstrncpy (perl_argv[perl_argc - 1] + 3, value, strlen (value) + 1);
1603         }
1604
1605         perl_argv[perl_argc] = NULL;
1606         return 0;
1607 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
1608
1609 /*
1610  * IncludeDir "<Dir>"
1611  */
1612 static int perl_config_includedir (pTHX_ oconfig_item_t *ci)
1613 {
1614         char *value = NULL;
1615
1616         if ((0 != ci->children_num) || (1 != ci->values_num)
1617                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1618                 log_err ("IncludeDir expects a single string argument.");
1619                 return 1;
1620         }
1621
1622         value = ci->values[0].value.string;
1623
1624         if (NULL == aTHX) {
1625                 perl_argv = (char **)realloc (perl_argv,
1626                                 (++perl_argc + 1) * sizeof (char *));
1627
1628                 if (NULL == perl_argv) {
1629                         log_err ("perl_config: Not enough memory.");
1630                         exit (3);
1631                 }
1632
1633                 perl_argv[perl_argc - 1] = (char *)smalloc (strlen (value) + 3);
1634                 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
1635                 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen (value) + 1);
1636
1637                 perl_argv[perl_argc] = NULL;
1638         }
1639         else {
1640                 /* prepend the directory to @INC */
1641                 av_unshift (GvAVn (PL_incgv), 1);
1642                 av_store (GvAVn (PL_incgv), 0, newSVpv (value, strlen (value)));
1643         }
1644         return 0;
1645 } /* static int perl_config_includedir (oconfig_item_it *) */
1646
1647 static int perl_config (oconfig_item_t *ci)
1648 {
1649         int i = 0;
1650
1651         dTHXa (NULL);
1652
1653         for (i = 0; i < ci->children_num; ++i) {
1654                 oconfig_item_t *c = ci->children + i;
1655
1656                 if (NULL != perl_threads)
1657                         aTHX = PERL_GET_CONTEXT;
1658
1659                 if (0 == strcasecmp (c->key, "LoadPlugin"))
1660                         perl_config_loadplugin (aTHX_ c);
1661                 else if (0 == strcasecmp (c->key, "BaseName"))
1662                         perl_config_basename (aTHX_ c);
1663                 else if (0 == strcasecmp (c->key, "EnableDebugger"))
1664                         perl_config_enabledebugger (aTHX_ c);
1665                 else if (0 == strcasecmp (c->key, "IncludeDir"))
1666                         perl_config_includedir (aTHX_ c);
1667                 else
1668                         log_warn ("Ignoring unknown config key \"%s\".", c->key);
1669         }
1670         return 0;
1671 } /* static int perl_config (oconfig_item_t *) */
1672
1673 void module_register (void)
1674 {
1675         perl_argc = 4;
1676         perl_argv = (char **)smalloc ((perl_argc + 1) * sizeof (char *));
1677
1678         /* default options for the Perl interpreter */
1679         perl_argv[0] = "";
1680         perl_argv[1] = "-MCollectd";
1681         perl_argv[2] = "-e";
1682         perl_argv[3] = "1";
1683         perl_argv[4] = NULL;
1684
1685         plugin_register_complex_config ("perl", perl_config);
1686         return;
1687 } /* void module_register (void) */
1688
1689 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */
1690