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