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