efb8bdd6aa3db6f898b8e60b9f9f2ee4b109a14c
[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 defined(COLLECT_DEBUG) && COLLECT_DEBUG && defined(__GNUC__) && __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_CONFIG   254
75 #define PLUGIN_DATASET  255
76
77 #define log_debug(...) DEBUG ("perl: " __VA_ARGS__)
78 #define log_info(...) INFO ("perl: " __VA_ARGS__)
79 #define log_warn(...) WARNING ("perl: " __VA_ARGS__)
80 #define log_err(...) ERROR ("perl: " __VA_ARGS__)
81
82 /* this is defined in DynaLoader.a */
83 void boot_DynaLoader (PerlInterpreter *, CV *);
84
85 static XS (Collectd_plugin_register_ds);
86 static XS (Collectd_plugin_unregister_ds);
87 static XS (Collectd_plugin_dispatch_values);
88 static XS (Collectd__plugin_write);
89 static XS (Collectd__plugin_flush);
90 static XS (Collectd_plugin_dispatch_notification);
91 static XS (Collectd_plugin_log);
92 static XS (Collectd_call_by_name);
93
94 /*
95  * private data types
96  */
97
98 typedef struct c_ithread_s {
99         /* the thread's Perl interpreter */
100         PerlInterpreter *interp;
101
102         /* double linked list of threads */
103         struct c_ithread_s *prev;
104         struct c_ithread_s *next;
105 } c_ithread_t;
106
107 typedef struct {
108         c_ithread_t *head;
109         c_ithread_t *tail;
110
111 #if COLLECT_DEBUG
112         /* some usage stats */
113         int number_of_threads;
114 #endif /* COLLECT_DEBUG */
115
116         pthread_mutex_t mutex;
117 } c_ithread_list_t;
118
119 /*
120  * private variables
121  */
122
123 /* if perl_threads != NULL perl_threads->head must
124  * point to the "base" thread */
125 static c_ithread_list_t *perl_threads = NULL;
126
127 /* the key used to store each pthread's ithread */
128 static pthread_key_t perl_thr_key;
129
130 static int    perl_argc = 0;
131 static char **perl_argv = NULL;
132
133 static char base_name[DATA_MAX_NAME_LEN] = "";
134
135 static struct {
136         char name[64];
137         XS ((*f));
138 } api[] =
139 {
140         { "Collectd::plugin_register_data_set",   Collectd_plugin_register_ds },
141         { "Collectd::plugin_unregister_data_set", Collectd_plugin_unregister_ds },
142         { "Collectd::plugin_dispatch_values",     Collectd_plugin_dispatch_values },
143         { "Collectd::_plugin_write",              Collectd__plugin_write },
144         { "Collectd::_plugin_flush",              Collectd__plugin_flush },
145         { "Collectd::plugin_dispatch_notification",
146                 Collectd_plugin_dispatch_notification },
147         { "Collectd::plugin_log",                 Collectd_plugin_log },
148         { "Collectd::call_by_name",               Collectd_call_by_name },
149         { "", NULL }
150 };
151
152 struct {
153         char name[64];
154         int  value;
155 } constants[] =
156 {
157         { "Collectd::TYPE_INIT",       PLUGIN_INIT },
158         { "Collectd::TYPE_READ",       PLUGIN_READ },
159         { "Collectd::TYPE_WRITE",      PLUGIN_WRITE },
160         { "Collectd::TYPE_SHUTDOWN",   PLUGIN_SHUTDOWN },
161         { "Collectd::TYPE_LOG",        PLUGIN_LOG },
162         { "Collectd::TYPE_NOTIF",      PLUGIN_NOTIF },
163         { "Collectd::TYPE_FLUSH",      PLUGIN_FLUSH },
164         { "Collectd::TYPE_CONFIG",     PLUGIN_CONFIG },
165         { "Collectd::TYPE_DATASET",    PLUGIN_DATASET },
166         { "Collectd::DS_TYPE_COUNTER", DS_TYPE_COUNTER },
167         { "Collectd::DS_TYPE_GAUGE",   DS_TYPE_GAUGE },
168         { "Collectd::LOG_ERR",         LOG_ERR },
169         { "Collectd::LOG_WARNING",     LOG_WARNING },
170         { "Collectd::LOG_NOTICE",      LOG_NOTICE },
171         { "Collectd::LOG_INFO",        LOG_INFO },
172         { "Collectd::LOG_DEBUG",       LOG_DEBUG },
173         { "Collectd::NOTIF_FAILURE",   NOTIF_FAILURE },
174         { "Collectd::NOTIF_WARNING",   NOTIF_WARNING },
175         { "Collectd::NOTIF_OKAY",      NOTIF_OKAY },
176         { "", 0 }
177 };
178
179 struct {
180         char  name[64];
181         char *var;
182 } g_strings[] =
183 {
184         { "Collectd::hostname_g", hostname_g },
185         { "", NULL }
186 };
187
188 struct {
189         char  name[64];
190         int  *var;
191 } g_integers[] =
192 {
193         { "Collectd::interval_g", &interval_g },
194         { "", NULL }
195 };
196
197 /*
198  * Helper functions for data type conversion.
199  */
200
201 /*
202  * data source:
203  * [
204  *   {
205  *     name => $ds_name,
206  *     type => $ds_type,
207  *     min  => $ds_min,
208  *     max  => $ds_max
209  *   },
210  *   ...
211  * ]
212  */
213 static int hv2data_source (pTHX_ HV *hash, data_source_t *ds)
214 {
215         SV **tmp = NULL;
216
217         if ((NULL == hash) || (NULL == ds))
218                 return -1;
219
220         if (NULL != (tmp = hv_fetch (hash, "name", 4, 0))) {
221                 sstrncpy (ds->name, SvPV_nolen (*tmp), sizeof (ds->name));
222         }
223         else {
224                 log_err ("hv2data_source: No DS name given.");
225                 return -1;
226         }
227
228         if (NULL != (tmp = hv_fetch (hash, "type", 4, 0))) {
229                 ds->type = SvIV (*tmp);
230
231                 if ((DS_TYPE_COUNTER != ds->type) && (DS_TYPE_GAUGE != ds->type)) {
232                         log_err ("hv2data_source: Invalid DS type.");
233                         return -1;
234                 }
235         }
236         else {
237                 ds->type = DS_TYPE_COUNTER;
238         }
239
240         if (NULL != (tmp = hv_fetch (hash, "min", 3, 0)))
241                 ds->min = SvNV (*tmp);
242         else
243                 ds->min = NAN;
244
245         if (NULL != (tmp = hv_fetch (hash, "max", 3, 0)))
246                 ds->max = SvNV (*tmp);
247         else
248                 ds->max = NAN;
249         return 0;
250 } /* static int hv2data_source (HV *, data_source_t *) */
251
252 static int av2value (pTHX_ char *name, AV *array, value_t *value, int len)
253 {
254         const data_set_t *ds;
255
256         int i = 0;
257
258         if ((NULL == name) || (NULL == array) || (NULL == value))
259                 return -1;
260
261         if (av_len (array) < len - 1)
262                 len = av_len (array) + 1;
263
264         if (0 >= len)
265                 return -1;
266
267         ds = plugin_get_ds (name);
268         if (NULL == ds) {
269                 log_err ("av2value: Unknown dataset \"%s\"", name);
270                 return -1;
271         }
272
273         if (ds->ds_num < len) {
274                 log_warn ("av2value: Value length exceeds data set length.");
275                 len = ds->ds_num;
276         }
277
278         for (i = 0; i < len; ++i) {
279                 SV **tmp = av_fetch (array, i, 0);
280
281                 if (NULL != tmp) {
282                         if (DS_TYPE_COUNTER == ds->ds[i].type)
283                                 value[i].counter = SvIV (*tmp);
284                         else
285                                 value[i].gauge = SvNV (*tmp);
286                 }
287                 else {
288                         return -1;
289                 }
290         }
291         return len;
292 } /* static int av2value (char *, AV *, value_t *, int) */
293
294 /*
295  * value list:
296  * {
297  *   values => [ @values ],
298  *   time   => $time,
299  *   host   => $host,
300  *   plugin => $plugin,
301  *   plugin_instance => $pinstance,
302  *   type_instance   => $tinstance,
303  * }
304  */
305 static int hv2value_list (pTHX_ HV *hash, value_list_t *vl)
306 {
307         SV **tmp;
308
309         if ((NULL == hash) || (NULL == vl))
310                 return -1;
311
312         if (NULL == (tmp = hv_fetch (hash, "type", 4, 0))) {
313                 log_err ("hv2value_list: No type given.");
314                 return -1;
315         }
316
317         sstrncpy (vl->type, SvPV_nolen (*tmp), sizeof (vl->type));
318
319         if ((NULL == (tmp = hv_fetch (hash, "values", 6, 0)))
320                         || (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp)))))) {
321                 log_err ("hv2value_list: No valid values given.");
322                 return -1;
323         }
324
325         {
326                 AV  *array = (AV *)SvRV (*tmp);
327                 int len    = av_len (array) + 1;
328
329                 if (len <= 0)
330                         return -1;
331
332                 vl->values     = (value_t *)smalloc (len * sizeof (value_t));
333                 vl->values_len = av2value (aTHX_ vl->type, (AV *)SvRV (*tmp),
334                                 vl->values, len);
335
336                 if (-1 == vl->values_len) {
337                         sfree (vl->values);
338                         return -1;
339                 }
340         }
341
342         if (NULL != (tmp = hv_fetch (hash, "time", 4, 0)))
343                 vl->time = (time_t)SvIV (*tmp);
344
345         if (NULL != (tmp = hv_fetch (hash, "interval", 8, 0)))
346                 vl->interval = SvIV (*tmp);
347
348         if (NULL != (tmp = hv_fetch (hash, "host", 4, 0)))
349                 sstrncpy (vl->host, SvPV_nolen (*tmp), sizeof (vl->host));
350         else
351                 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
352
353         if (NULL != (tmp = hv_fetch (hash, "plugin", 6, 0)))
354                 sstrncpy (vl->plugin, SvPV_nolen (*tmp), sizeof (vl->plugin));
355
356         if (NULL != (tmp = hv_fetch (hash, "plugin_instance", 15, 0)))
357                 sstrncpy (vl->plugin_instance, SvPV_nolen (*tmp),
358                                 sizeof (vl->plugin_instance));
359
360         if (NULL != (tmp = hv_fetch (hash, "type_instance", 13, 0)))
361                 sstrncpy (vl->type_instance, SvPV_nolen (*tmp),
362                                 sizeof (vl->type_instance));
363         return 0;
364 } /* static int hv2value_list (pTHX_ HV *, value_list_t *) */
365
366 static int av2data_set (pTHX_ AV *array, char *name, data_set_t *ds)
367 {
368         int len, i;
369
370         if ((NULL == array) || (NULL == name) || (NULL == ds))
371                 return -1;
372
373         len = av_len (array);
374
375         if (-1 == len) {
376                 log_err ("av2data_set: Invalid data set.");
377                 return -1;
378         }
379
380         ds->ds = (data_source_t *)smalloc ((len + 1) * sizeof (data_source_t));
381         ds->ds_num = len + 1;
382
383         for (i = 0; i <= len; ++i) {
384                 SV **elem = av_fetch (array, i, 0);
385
386                 if (NULL == elem) {
387                         log_err ("av2data_set: Failed to fetch data source %i.", i);
388                         return -1;
389                 }
390
391                 if (! (SvROK (*elem) && (SVt_PVHV == SvTYPE (SvRV (*elem))))) {
392                         log_err ("av2data_set: Invalid data source.");
393                         return -1;
394                 }
395
396                 if (-1 == hv2data_source (aTHX_ (HV *)SvRV (*elem), &ds->ds[i]))
397                         return -1;
398
399                 log_debug ("av2data_set: "
400                                 "DS.name = \"%s\", DS.type = %i, DS.min = %f, DS.max = %f",
401                                 ds->ds[i].name, ds->ds[i].type, ds->ds[i].min, ds->ds[i].max);
402         }
403
404         sstrncpy (ds->type, name, sizeof (ds->type));
405         return 0;
406 } /* static int av2data_set (pTHX_ AV *, data_set_t *) */
407
408 /*
409  * notification:
410  * {
411  *   severity => $severity,
412  *   time     => $time,
413  *   message  => $msg,
414  *   host     => $host,
415  *   plugin   => $plugin,
416  *   type     => $type,
417  *   plugin_instance => $instance,
418  *   type_instance   => $type_instance,
419  *   meta     => [ { name => <name>, value => <value> }, ... ]
420  * }
421  */
422 static int av2notification_meta (pTHX_ AV *array, notification_meta_t **meta)
423 {
424         notification_meta_t **m = meta;
425
426         int len = av_len (array);
427         int i;
428
429         for (i = 0; i <= len; ++i) {
430                 SV **tmp = av_fetch (array, i, 0);
431                 HV  *hash;
432
433                 if (NULL == tmp)
434                         return -1;
435
436                 if (! (SvROK (*tmp) && (SVt_PVHV == SvTYPE (SvRV (*tmp))))) {
437                         log_warn ("av2notification_meta: Skipping invalid "
438                                         "meta information.");
439                         continue;
440                 }
441
442                 hash = (HV *)SvRV (*tmp);
443
444                 *m = (notification_meta_t *)smalloc (sizeof (**m));
445
446                 if (NULL == (tmp = hv_fetch (hash, "name", 4, 0))) {
447                         log_warn ("av2notification_meta: Skipping invalid "
448                                         "meta information.");
449                         free (*m);
450                         continue;
451                 }
452                 sstrncpy ((*m)->name, SvPV_nolen (*tmp), sizeof ((*m)->name));
453
454                 if (NULL == (tmp = hv_fetch (hash, "value", 5, 0))) {
455                         log_warn ("av2notification_meta: Skipping invalid "
456                                         "meta information.");
457                         free ((*m)->name);
458                         free (*m);
459                         continue;
460                 }
461
462                 if (SvNOK (*tmp)) {
463                         (*m)->nm_value.nm_double = SvNVX (*tmp);
464                         (*m)->type = NM_TYPE_DOUBLE;
465                 }
466                 else if (SvUOK (*tmp)) {
467                         (*m)->nm_value.nm_unsigned_int = SvUVX (*tmp);
468                         (*m)->type = NM_TYPE_UNSIGNED_INT;
469                 }
470                 else if (SvIOK (*tmp)) {
471                         (*m)->nm_value.nm_signed_int = SvIVX (*tmp);
472                         (*m)->type = NM_TYPE_SIGNED_INT;
473                 }
474                 else {
475                         (*m)->nm_value.nm_string = sstrdup (SvPV_nolen (*tmp));
476                         (*m)->type = NM_TYPE_STRING;
477                 }
478
479                 (*m)->next = NULL;
480                 m = &((*m)->next);
481         }
482         return 0;
483 } /* static int av2notification_meta (AV *, notification_meta_t *) */
484
485 static int hv2notification (pTHX_ HV *hash, notification_t *n)
486 {
487         SV **tmp = NULL;
488
489         if ((NULL == hash) || (NULL == n))
490                 return -1;
491
492         if (NULL != (tmp = hv_fetch (hash, "severity", 8, 0)))
493                 n->severity = SvIV (*tmp);
494         else
495                 n->severity = NOTIF_FAILURE;
496
497         if (NULL != (tmp = hv_fetch (hash, "time", 4, 0)))
498                 n->time = (time_t)SvIV (*tmp);
499         else
500                 n->time = time (NULL);
501
502         if (NULL != (tmp = hv_fetch (hash, "message", 7, 0)))
503                 sstrncpy (n->message, SvPV_nolen (*tmp), sizeof (n->message));
504
505         if (NULL != (tmp = hv_fetch (hash, "host", 4, 0)))
506                 sstrncpy (n->host, SvPV_nolen (*tmp), sizeof (n->host));
507         else
508                 sstrncpy (n->host, hostname_g, sizeof (n->host));
509
510         if (NULL != (tmp = hv_fetch (hash, "plugin", 6, 0)))
511                 sstrncpy (n->plugin, SvPV_nolen (*tmp), sizeof (n->plugin));
512
513         if (NULL != (tmp = hv_fetch (hash, "plugin_instance", 15, 0)))
514                 sstrncpy (n->plugin_instance, SvPV_nolen (*tmp),
515                                 sizeof (n->plugin_instance));
516
517         if (NULL != (tmp = hv_fetch (hash, "type", 4, 0)))
518                 sstrncpy (n->type, SvPV_nolen (*tmp), sizeof (n->type));
519
520         if (NULL != (tmp = hv_fetch (hash, "type_instance", 13, 0)))
521                 sstrncpy (n->type_instance, SvPV_nolen (*tmp),
522                                 sizeof (n->type_instance));
523
524         n->meta = NULL;
525         while (NULL != (tmp = hv_fetch (hash, "meta", 4, 0))) {
526                 if (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp))))) {
527                         log_warn ("hv2notification: Ignoring invalid meta information.");
528                         break;
529                 }
530
531                 if (0 != av2notification_meta (aTHX_ (AV *)SvRV (*tmp), &n->meta)) {
532                         plugin_notification_meta_free (n);
533                         return -1;
534                 }
535                 break;
536         }
537         return 0;
538 } /* static int hv2notification (pTHX_ HV *, notification_t *) */
539
540 static int data_set2av (pTHX_ data_set_t *ds, AV *array)
541 {
542         int i = 0;
543
544         if ((NULL == ds) || (NULL == array))
545                 return -1;
546
547         av_extend (array, ds->ds_num);
548
549         for (i = 0; i < ds->ds_num; ++i) {
550                 HV *source = newHV ();
551
552                 if (NULL == hv_store (source, "name", 4,
553                                 newSVpv (ds->ds[i].name, 0), 0))
554                         return -1;
555
556                 if (NULL == hv_store (source, "type", 4, newSViv (ds->ds[i].type), 0))
557                         return -1;
558
559                 if (! isnan (ds->ds[i].min))
560                         if (NULL == hv_store (source, "min", 3,
561                                         newSVnv (ds->ds[i].min), 0))
562                                 return -1;
563
564                 if (! isnan (ds->ds[i].max))
565                         if (NULL == hv_store (source, "max", 3,
566                                         newSVnv (ds->ds[i].max), 0))
567                                 return -1;
568
569                 if (NULL == av_store (array, i, newRV_noinc ((SV *)source)))
570                         return -1;
571         }
572         return 0;
573 } /* static int data_set2av (data_set_t *, AV *) */
574
575 static int value_list2hv (pTHX_ value_list_t *vl, data_set_t *ds, HV *hash)
576 {
577         AV *values = NULL;
578
579         int i   = 0;
580         int len = 0;
581
582         if ((NULL == vl) || (NULL == ds) || (NULL == hash))
583                 return -1;
584
585         len = vl->values_len;
586
587         if (ds->ds_num < len) {
588                 log_warn ("value2av: Value length exceeds data set length.");
589                 len = ds->ds_num;
590         }
591
592         values = newAV ();
593         av_extend (values, len - 1);
594
595         for (i = 0; i < len; ++i) {
596                 SV *val = NULL;
597
598                 if (DS_TYPE_COUNTER == ds->ds[i].type)
599                         val = newSViv (vl->values[i].counter);
600                 else
601                         val = newSVnv (vl->values[i].gauge);
602
603                 if (NULL == av_store (values, i, val)) {
604                         av_undef (values);
605                         return -1;
606                 }
607         }
608
609         if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0))
610                 return -1;
611
612         if (0 != vl->time)
613                 if (NULL == hv_store (hash, "time", 4, newSViv (vl->time), 0))
614                         return -1;
615
616         if (NULL == hv_store (hash, "interval", 8, newSViv (vl->interval), 0))
617                 return -1;
618
619         if ('\0' != vl->host[0])
620                 if (NULL == hv_store (hash, "host", 4, newSVpv (vl->host, 0), 0))
621                         return -1;
622
623         if ('\0' != vl->plugin[0])
624                 if (NULL == hv_store (hash, "plugin", 6, newSVpv (vl->plugin, 0), 0))
625                         return -1;
626
627         if ('\0' != vl->plugin_instance[0])
628                 if (NULL == hv_store (hash, "plugin_instance", 15,
629                                 newSVpv (vl->plugin_instance, 0), 0))
630                         return -1;
631
632         if ('\0' != vl->type[0])
633                 if (NULL == hv_store (hash, "type", 4, newSVpv (vl->type, 0), 0))
634                         return -1;
635
636         if ('\0' != vl->type_instance[0])
637                 if (NULL == hv_store (hash, "type_instance", 13,
638                                 newSVpv (vl->type_instance, 0), 0))
639                         return -1;
640         return 0;
641 } /* static int value2av (value_list_t *, data_set_t *, HV *) */
642
643 static int notification_meta2av (pTHX_ notification_meta_t *meta, AV *array)
644 {
645         int meta_num = 0;
646         int i;
647
648         while (meta) {
649                 ++meta_num;
650                 meta = meta->next;
651         }
652
653         av_extend (array, meta_num);
654
655         for (i = 0; NULL != meta; meta = meta->next, ++i) {
656                 HV *m = newHV ();
657                 SV *value;
658
659                 if (NULL == hv_store (m, "name", 4, newSVpv (meta->name, 0), 0))
660                         return -1;
661
662                 if (NM_TYPE_STRING == meta->type)
663                         value = newSVpv (meta->nm_value.nm_string, 0);
664                 else if (NM_TYPE_SIGNED_INT == meta->type)
665                         value = newSViv (meta->nm_value.nm_signed_int);
666                 else if (NM_TYPE_UNSIGNED_INT == meta->type)
667                         value = newSVuv (meta->nm_value.nm_unsigned_int);
668                 else if (NM_TYPE_DOUBLE == meta->type)
669                         value = newSVnv (meta->nm_value.nm_double);
670                 else if (NM_TYPE_BOOLEAN == meta->type)
671                         value = meta->nm_value.nm_boolean ? &PL_sv_yes : &PL_sv_no;
672                 else
673                         return -1;
674
675                 if (NULL == hv_store (m, "value", 5, value, 0)) {
676                         sv_free (value);
677                         return -1;
678                 }
679
680                 if (NULL == av_store (array, i, newRV_noinc ((SV *)m))) {
681                         hv_clear (m);
682                         hv_undef (m);
683                         return -1;
684                 }
685         }
686         return 0;
687 } /* static int notification_meta2av (notification_meta_t *, AV *) */
688
689 static int notification2hv (pTHX_ notification_t *n, HV *hash)
690 {
691         if (NULL == hv_store (hash, "severity", 8, newSViv (n->severity), 0))
692                 return -1;
693
694         if (0 != n->time)
695                 if (NULL == hv_store (hash, "time", 4, newSViv (n->time), 0))
696                         return -1;
697
698         if ('\0' != *n->message)
699                 if (NULL == hv_store (hash, "message", 7, newSVpv (n->message, 0), 0))
700                         return -1;
701
702         if ('\0' != *n->host)
703                 if (NULL == hv_store (hash, "host", 4, newSVpv (n->host, 0), 0))
704                         return -1;
705
706         if ('\0' != *n->plugin)
707                 if (NULL == hv_store (hash, "plugin", 6, newSVpv (n->plugin, 0), 0))
708                         return -1;
709
710         if ('\0' != *n->plugin_instance)
711                 if (NULL == hv_store (hash, "plugin_instance", 15,
712                                 newSVpv (n->plugin_instance, 0), 0))
713                         return -1;
714
715         if ('\0' != *n->type)
716                 if (NULL == hv_store (hash, "type", 4, newSVpv (n->type, 0), 0))
717                         return -1;
718
719         if ('\0' != *n->type_instance)
720                 if (NULL == hv_store (hash, "type_instance", 13,
721                                 newSVpv (n->type_instance, 0), 0))
722                         return -1;
723
724         if (NULL != n->meta) {
725                 AV *meta = newAV ();
726                 if ((0 != notification_meta2av (aTHX_ n->meta, meta))
727                                 || (NULL == hv_store (hash, "meta", 4,
728                                                 newRV_noinc ((SV *)meta), 0))) {
729                         av_clear (meta);
730                         av_undef (meta);
731                         return -1;
732                 }
733         }
734         return 0;
735 } /* static int notification2hv (notification_t *, HV *) */
736
737 static int oconfig_item2hv (pTHX_ oconfig_item_t *ci, HV *hash)
738 {
739         int i;
740
741         AV *values;
742         AV *children;
743
744         if (NULL == hv_store (hash, "key", 3, newSVpv (ci->key, 0), 0))
745                 return -1;
746
747         values = newAV ();
748         if (0 < ci->values_num)
749                 av_extend (values, ci->values_num);
750
751         if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0)) {
752                 av_clear (values);
753                 av_undef (values);
754                 return -1;
755         }
756
757         for (i = 0; i < ci->values_num; ++i) {
758                 SV *value;
759
760                 switch (ci->values[i].type) {
761                         case OCONFIG_TYPE_STRING:
762                                 value = newSVpv (ci->values[i].value.string, 0);
763                                 break;
764                         case OCONFIG_TYPE_NUMBER:
765                                 value = newSVnv ((NV)ci->values[i].value.number);
766                                 break;
767                         case OCONFIG_TYPE_BOOLEAN:
768                                 value = ci->values[i].value.boolean ? &PL_sv_yes : &PL_sv_no;
769                                 break;
770                         default:
771                                 log_err ("oconfig_item2hv: Invalid value type %i.",
772                                                 ci->values[i].type);
773                                 value = &PL_sv_undef;
774                 }
775
776                 if (NULL == av_store (values, i, value)) {
777                         sv_free (value);
778                         return -1;
779                 }
780         }
781
782         /* ignoring 'parent' member which is uninteresting in this case */
783
784         children = newAV ();
785         if (0 < ci->children_num)
786                 av_extend (children, ci->children_num);
787
788         if (NULL == hv_store (hash, "children", 8, newRV_noinc ((SV *)children), 0)) {
789                 av_clear (children);
790                 av_undef (children);
791                 return -1;
792         }
793
794         for (i = 0; i < ci->children_num; ++i) {
795                 HV *child = newHV ();
796
797                 if (0 != oconfig_item2hv (aTHX_ ci->children + i, child)) {
798                         hv_clear (child);
799                         hv_undef (child);
800                         return -1;
801                 }
802
803                 if (NULL == av_store (children, i, newRV_noinc ((SV *)child))) {
804                         hv_clear (child);
805                         hv_undef (child);
806                         return -1;
807                 }
808         }
809         return 0;
810 } /* static int oconfig_item2hv (pTHX_ oconfig_item_t *, HV *) */
811
812 /*
813  * Internal functions.
814  */
815
816 static char *get_module_name (char *buf, size_t buf_len, const char *module) {
817         int status = 0;
818         if (base_name[0] == '\0')
819                 status = ssnprintf (buf, buf_len, "%s", module);
820         else
821                 status = ssnprintf (buf, buf_len, "%s::%s", base_name, module);
822         if ((status < 0) || ((unsigned int)status >= buf_len))
823                 return (NULL);
824         return (buf);
825 } /* char *get_module_name */
826
827 /*
828  * Add a plugin's data set definition.
829  */
830 static int pplugin_register_data_set (pTHX_ char *name, AV *dataset)
831 {
832         int ret = 0;
833
834         data_set_t ds;
835
836         if ((NULL == name) || (NULL == dataset))
837                 return -1;
838
839         if (0 != av2data_set (aTHX_ dataset, name, &ds))
840                 return -1;
841
842         ret = plugin_register_data_set (&ds);
843
844         free (ds.ds);
845         return ret;
846 } /* static int pplugin_register_data_set (char *, SV *) */
847
848 /*
849  * Remove a plugin's data set definition.
850  */
851 static int pplugin_unregister_data_set (char *name)
852 {
853         if (NULL == name)
854                 return 0;
855         return plugin_unregister_data_set (name);
856 } /* static int pplugin_unregister_data_set (char *) */
857
858 /*
859  * Submit the values to the write functions.
860  */
861 static int pplugin_dispatch_values (pTHX_ HV *values)
862 {
863         value_list_t vl = VALUE_LIST_INIT;
864
865         int ret = 0;
866
867         if (NULL == values)
868                 return -1;
869
870         if (0 != hv2value_list (aTHX_ values, &vl))
871                 return -1;
872
873         ret = plugin_dispatch_values (&vl);
874
875         sfree (vl.values);
876         return ret;
877 } /* static int pplugin_dispatch_values (char *, HV *) */
878
879 /*
880  * Submit the values to a single write function.
881  */
882 static int pplugin_write (pTHX_ const char *plugin, AV *data_set, HV *values)
883 {
884         data_set_t   ds;
885         value_list_t vl = VALUE_LIST_INIT;
886
887         int ret;
888
889         if (NULL == values)
890                 return -1;
891
892         if (0 != hv2value_list (aTHX_ values, &vl))
893                 return -1;
894
895         if ((NULL != data_set)
896                         && (0 != av2data_set (aTHX_ data_set, vl.type, &ds)))
897                 return -1;
898
899         ret = plugin_write (plugin, NULL == data_set ? NULL : &ds, &vl);
900         if (0 != ret)
901                 log_warn ("Dispatching value to plugin \"%s\" failed with status %i.",
902                                 NULL == plugin ? "<any>" : plugin, ret);
903
904         if (NULL != data_set)
905                 sfree (ds.ds);
906         sfree (vl.values);
907         return ret;
908 } /* static int pplugin_write (const char *plugin, HV *, HV *) */
909
910 /*
911  * Dispatch a notification.
912  */
913 static int pplugin_dispatch_notification (pTHX_ HV *notif)
914 {
915         notification_t n;
916
917         int ret;
918
919         if (NULL == notif)
920                 return -1;
921
922         memset (&n, 0, sizeof (n));
923
924         if (0 != hv2notification (aTHX_ notif, &n))
925                 return -1;
926
927         ret = plugin_dispatch_notification (&n);
928         plugin_notification_meta_free (&n);
929         return ret;
930 } /* static int pplugin_dispatch_notification (HV *) */
931
932 /*
933  * Call all working functions of the given type.
934  */
935 static int pplugin_call_all (pTHX_ int type, ...)
936 {
937         int retvals = 0;
938
939         va_list ap;
940         int ret = 0;
941
942         dSP;
943
944         if ((type < 0) || (type >= PLUGIN_TYPES))
945                 return -1;
946
947         va_start (ap, type);
948
949         ENTER;
950         SAVETMPS;
951
952         PUSHMARK (SP);
953
954         XPUSHs (sv_2mortal (newSViv ((IV)type)));
955
956         if (PLUGIN_WRITE == type) {
957                 /*
958                  * $_[0] = $plugin_type;
959                  *
960                  * $_[1] =
961                  * [
962                  *   {
963                  *     name => $ds_name,
964                  *     type => $ds_type,
965                  *     min  => $ds_min,
966                  *     max  => $ds_max
967                  *   },
968                  *   ...
969                  * ];
970                  *
971                  * $_[2] =
972                  * {
973                  *   values => [ $v1, ... ],
974                  *   time   => $time,
975                  *   host   => $hostname,
976                  *   plugin => $plugin,
977                  *   type   => $type,
978                  *   plugin_instance => $instance,
979                  *   type_instance   => $type_instance
980                  * };
981                  */
982                 data_set_t   *ds;
983                 value_list_t *vl;
984
985                 AV *pds = newAV ();
986                 HV *pvl = newHV ();
987
988                 ds = va_arg (ap, data_set_t *);
989                 vl = va_arg (ap, value_list_t *);
990
991                 if (-1 == data_set2av (aTHX_ ds, pds)) {
992                         av_clear (pds);
993                         av_undef (pds);
994                         pds = Nullav;
995                         ret = -1;
996                 }
997
998                 if (-1 == value_list2hv (aTHX_ vl, ds, pvl)) {
999                         hv_clear (pvl);
1000                         hv_undef (pvl);
1001                         pvl = Nullhv;
1002                         ret = -1;
1003                 }
1004
1005                 XPUSHs (sv_2mortal (newSVpv (ds->type, 0)));
1006                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1007                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1008         }
1009         else if (PLUGIN_LOG == type) {
1010                 /*
1011                  * $_[0] = $level;
1012                  *
1013                  * $_[1] = $message;
1014                  */
1015                 XPUSHs (sv_2mortal (newSViv (va_arg (ap, int))));
1016                 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1017         }
1018         else if (PLUGIN_NOTIF == type) {
1019                 /*
1020                  * $_[0] =
1021                  * {
1022                  *   severity => $severity,
1023                  *   time     => $time,
1024                  *   message  => $msg,
1025                  *   host     => $host,
1026                  *   plugin   => $plugin,
1027                  *   type     => $type,
1028                  *   plugin_instance => $instance,
1029                  *   type_instance   => $type_instance
1030                  * };
1031                  */
1032                 notification_t *n;
1033                 HV *notif = newHV ();
1034
1035                 n = va_arg (ap, notification_t *);
1036
1037                 if (-1 == notification2hv (aTHX_ n, notif)) {
1038                         hv_clear (notif);
1039                         hv_undef (notif);
1040                         notif = Nullhv;
1041                         ret = -1;
1042                 }
1043
1044                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)notif)));
1045         }
1046         else if (PLUGIN_FLUSH == type) {
1047                 /*
1048                  * $_[0] = $timeout;
1049                  * $_[1] = $identifier;
1050                  */
1051                 XPUSHs (sv_2mortal (newSViv (va_arg (ap, int))));
1052                 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1053         }
1054
1055         PUTBACK;
1056
1057         retvals = call_pv ("Collectd::plugin_call_all", G_SCALAR);
1058
1059         SPAGAIN;
1060         if (0 < retvals) {
1061                 SV *tmp = POPs;
1062                 if (! SvTRUE (tmp))
1063                         ret = -1;
1064         }
1065
1066         PUTBACK;
1067         FREETMPS;
1068         LEAVE;
1069
1070         va_end (ap);
1071         return ret;
1072 } /* static int pplugin_call_all (int, ...) */
1073
1074 /*
1075  * Exported Perl API.
1076  */
1077
1078 /*
1079  * Collectd::plugin_register_data_set (type, dataset).
1080  *
1081  * type:
1082  *   type of the dataset
1083  *
1084  * dataset:
1085  *   dataset to be registered
1086  */
1087 static XS (Collectd_plugin_register_ds)
1088 {
1089         SV  *data = NULL;
1090         int ret   = 0;
1091
1092         dXSARGS;
1093
1094         if (2 != items) {
1095                 log_err ("Usage: Collectd::plugin_register_data_set(type, dataset)");
1096                 XSRETURN_EMPTY;
1097         }
1098
1099         log_debug ("Collectd::plugin_register_data_set: "
1100                         "type = \"%s\", dataset = \"%s\"",
1101                         SvPV_nolen (ST (0)), SvPV_nolen (ST (1)));
1102
1103         data = ST (1);
1104
1105         if (SvROK (data) && (SVt_PVAV == SvTYPE (SvRV (data)))) {
1106                 ret = pplugin_register_data_set (aTHX_ SvPV_nolen (ST (0)),
1107                                 (AV *)SvRV (data));
1108         }
1109         else {
1110                 log_err ("Collectd::plugin_register_data_set: Invalid data.");
1111                 XSRETURN_EMPTY;
1112         }
1113
1114         if (0 == ret)
1115                 XSRETURN_YES;
1116         else
1117                 XSRETURN_EMPTY;
1118 } /* static XS (Collectd_plugin_register_ds) */
1119
1120 /*
1121  * Collectd::plugin_unregister_data_set (type).
1122  *
1123  * type:
1124  *   type of the dataset
1125  */
1126 static XS (Collectd_plugin_unregister_ds)
1127 {
1128         dXSARGS;
1129
1130         if (1 != items) {
1131                 log_err ("Usage: Collectd::plugin_unregister_data_set(type)");
1132                 XSRETURN_EMPTY;
1133         }
1134
1135         log_debug ("Collectd::plugin_unregister_data_set: type = \"%s\"",
1136                         SvPV_nolen (ST (0)));
1137
1138         if (0 == pplugin_unregister_data_set (SvPV_nolen (ST (0))))
1139                 XSRETURN_YES;
1140         else
1141                 XSRETURN_EMPTY;
1142 } /* static XS (Collectd_plugin_register_ds) */
1143
1144 /*
1145  * Collectd::plugin_dispatch_values (name, values).
1146  *
1147  * name:
1148  *   name of the plugin
1149  *
1150  * values:
1151  *   value list to submit
1152  */
1153 static XS (Collectd_plugin_dispatch_values)
1154 {
1155         SV *values     = NULL;
1156         int values_idx = 0;
1157
1158         int ret = 0;
1159
1160         dXSARGS;
1161
1162         if (2 == items) {
1163                 log_warn ("Collectd::plugin_dispatch_values with two arguments "
1164                                 "is deprecated - pass the type through values->{type}.");
1165                 values_idx = 1;
1166         }
1167         else if (1 != items) {
1168                 log_err ("Usage: Collectd::plugin_dispatch_values(values)");
1169                 XSRETURN_EMPTY;
1170         }
1171
1172         log_debug ("Collectd::plugin_dispatch_values: values=\"%s\"",
1173                         SvPV_nolen (ST (values_idx)));
1174
1175         values = ST (values_idx);
1176
1177         if (! (SvROK (values) && (SVt_PVHV == SvTYPE (SvRV (values))))) {
1178                 log_err ("Collectd::plugin_dispatch_values: Invalid values.");
1179                 XSRETURN_EMPTY;
1180         }
1181
1182         if (((2 == items) && (NULL == ST (0))) || (NULL == values))
1183                 XSRETURN_EMPTY;
1184
1185         if ((2 == items) && (NULL == hv_store ((HV *)SvRV (values), "type", 4,
1186                         newSVsv (ST (0)), 0))) {
1187                 log_err ("Collectd::plugin_dispatch_values: Could not store type.");
1188                 XSRETURN_EMPTY;
1189         }
1190
1191         ret = pplugin_dispatch_values (aTHX_ (HV *)SvRV (values));
1192
1193         if (0 == ret)
1194                 XSRETURN_YES;
1195         else
1196                 XSRETURN_EMPTY;
1197 } /* static XS (Collectd_plugin_dispatch_values) */
1198
1199 /* Collectd::plugin_write (plugin, ds, vl).
1200  *
1201  * plugin:
1202  *   name of the plugin to call, may be 'undef'
1203  *
1204  * ds:
1205  *   data-set that describes the submitted values, may be 'undef'
1206  *
1207  * vl:
1208  *   value-list to be written
1209  */
1210 static XS (Collectd__plugin_write)
1211 {
1212         char *plugin;
1213         SV   *ds, *vl;
1214         AV   *ds_array;
1215
1216         int ret;
1217
1218         dXSARGS;
1219
1220         if (3 != items) {
1221                 log_err ("Usage: Collectd::plugin_write(plugin, ds, vl)");
1222                 XSRETURN_EMPTY;
1223         }
1224
1225         log_debug ("Collectd::plugin_write: plugin=\"%s\", ds=\"%s\", vl=\"%s\"",
1226                         SvPV_nolen (ST (0)), SvOK (ST (1)) ? SvPV_nolen (ST (1)) : "",
1227                         SvPV_nolen (ST (2)));
1228
1229         if (! SvOK (ST (0)))
1230                 plugin = NULL;
1231         else
1232                 plugin = SvPV_nolen (ST (0));
1233
1234         ds = ST (1);
1235         if (SvROK (ds) && (SVt_PVAV == SvTYPE (SvRV (ds))))
1236                 ds_array = (AV *)SvRV (ds);
1237         else if (! SvOK (ds))
1238                 ds_array = NULL;
1239         else {
1240                 log_err ("Collectd::plugin_write: Invalid data-set.");
1241                 XSRETURN_EMPTY;
1242         }
1243
1244         vl = ST (2);
1245         if (! (SvROK (vl) && (SVt_PVHV == SvTYPE (SvRV (vl))))) {
1246                 log_err ("Collectd::plugin_write: Invalid value-list.");
1247                 XSRETURN_EMPTY;
1248         }
1249
1250         ret = pplugin_write (aTHX_ plugin, ds_array, (HV *)SvRV (vl));
1251
1252         if (0 == ret)
1253                 XSRETURN_YES;
1254         else
1255                 XSRETURN_EMPTY;
1256 } /* static XS (Collectd__plugin_write) */
1257
1258 /*
1259  * Collectd::_plugin_flush (plugin, timeout, identifier).
1260  *
1261  * plugin:
1262  *   name of the plugin to flush
1263  *
1264  * timeout:
1265  *   timeout to use when flushing the data
1266  *
1267  * identifier:
1268  *   data-set identifier to flush
1269  */
1270 static XS (Collectd__plugin_flush)
1271 {
1272         char *plugin  = NULL;
1273         int   timeout = -1;
1274         char *id      = NULL;
1275
1276         dXSARGS;
1277
1278         if (3 != items) {
1279                 log_err ("Usage: Collectd::_plugin_flush(plugin, timeout, id)");
1280                 XSRETURN_EMPTY;
1281         }
1282
1283         if (SvOK (ST (0)))
1284                 plugin = SvPV_nolen (ST (0));
1285
1286         if (SvOK (ST (1)))
1287                 timeout = (int)SvIV (ST (1));
1288
1289         if (SvOK (ST (2)))
1290                 id = SvPV_nolen (ST (2));
1291
1292         log_debug ("Collectd::_plugin_flush: plugin = \"%s\", timeout = %i, "
1293                         "id = \"%s\"", plugin, timeout, id);
1294
1295         if (0 == plugin_flush (plugin, timeout, id))
1296                 XSRETURN_YES;
1297         else
1298                 XSRETURN_EMPTY;
1299 } /* static XS (Collectd__plugin_flush) */
1300
1301 /*
1302  * Collectd::plugin_dispatch_notification (notif).
1303  *
1304  * notif:
1305  *   notification to dispatch
1306  */
1307 static XS (Collectd_plugin_dispatch_notification)
1308 {
1309         SV *notif = NULL;
1310
1311         int ret = 0;
1312
1313         dXSARGS;
1314
1315         if (1 != items) {
1316                 log_err ("Usage: Collectd::plugin_dispatch_notification(notif)");
1317                 XSRETURN_EMPTY;
1318         }
1319
1320         log_debug ("Collectd::plugin_dispatch_notification: notif = \"%s\"",
1321                         SvPV_nolen (ST (0)));
1322
1323         notif = ST (0);
1324
1325         if (! (SvROK (notif) && (SVt_PVHV == SvTYPE (SvRV (notif))))) {
1326                 log_err ("Collectd::plugin_dispatch_notification: Invalid notif.");
1327                 XSRETURN_EMPTY;
1328         }
1329
1330         ret = pplugin_dispatch_notification (aTHX_ (HV *)SvRV (notif));
1331
1332         if (0 == ret)
1333                 XSRETURN_YES;
1334         else
1335                 XSRETURN_EMPTY;
1336 } /* static XS (Collectd_plugin_dispatch_notification) */
1337
1338 /*
1339  * Collectd::plugin_log (level, message).
1340  *
1341  * level:
1342  *   log level (LOG_DEBUG, ... LOG_ERR)
1343  *
1344  * message:
1345  *   log message
1346  */
1347 static XS (Collectd_plugin_log)
1348 {
1349         dXSARGS;
1350
1351         if (2 != items) {
1352                 log_err ("Usage: Collectd::plugin_log(level, message)");
1353                 XSRETURN_EMPTY;
1354         }
1355
1356         plugin_log (SvIV (ST (0)), "%s", SvPV_nolen (ST (1)));
1357         XSRETURN_YES;
1358 } /* static XS (Collectd_plugin_log) */
1359
1360 /*
1361  * Collectd::call_by_name (...).
1362  *
1363  * Call a Perl sub identified by its name passed through $Collectd::cb_name.
1364  */
1365 static XS (Collectd_call_by_name)
1366 {
1367         SV   *tmp  = NULL;
1368         char *name = NULL;
1369
1370         if (NULL == (tmp = get_sv ("Collectd::cb_name", 0))) {
1371                 sv_setpv (get_sv ("@", 1), "cb_name has not been set");
1372                 CLEAR_STACK_FRAME;
1373                 return;
1374         }
1375
1376         name = SvPV_nolen (tmp);
1377
1378         if (NULL == get_cv (name, 0)) {
1379                 sv_setpvf (get_sv ("@", 1), "unknown callback \"%s\"", name);
1380                 CLEAR_STACK_FRAME;
1381                 return;
1382         }
1383
1384         /* simply pass on the subroutine call without touching the stack,
1385          * thus leaving any arguments and return values in place */
1386         call_pv (name, 0);
1387 } /* static XS (Collectd_call_by_name) */
1388
1389 /*
1390  * collectd's perl interpreter based thread implementation.
1391  *
1392  * This has been inspired by Perl's ithreads introduced in version 5.6.0.
1393  */
1394
1395 /* must be called with perl_threads->mutex locked */
1396 static void c_ithread_destroy (c_ithread_t *ithread)
1397 {
1398         dTHXa (ithread->interp);
1399
1400         assert (NULL != perl_threads);
1401
1402         PERL_SET_CONTEXT (aTHX);
1403         log_debug ("Shutting down Perl interpreter %p...", aTHX);
1404
1405 #if COLLECT_DEBUG
1406         sv_report_used ();
1407
1408         --perl_threads->number_of_threads;
1409 #endif /* COLLECT_DEBUG */
1410
1411         perl_destruct (aTHX);
1412         perl_free (aTHX);
1413
1414         if (NULL == ithread->prev)
1415                 perl_threads->head = ithread->next;
1416         else
1417                 ithread->prev->next = ithread->next;
1418
1419         if (NULL == ithread->next)
1420                 perl_threads->tail = ithread->prev;
1421         else
1422                 ithread->next->prev = ithread->prev;
1423
1424         sfree (ithread);
1425         return;
1426 } /* static void c_ithread_destroy (c_ithread_t *) */
1427
1428 static void c_ithread_destructor (void *arg)
1429 {
1430         c_ithread_t *ithread = (c_ithread_t *)arg;
1431         c_ithread_t *t = NULL;
1432
1433         if (NULL == perl_threads)
1434                 return;
1435
1436         pthread_mutex_lock (&perl_threads->mutex);
1437
1438         for (t = perl_threads->head; NULL != t; t = t->next)
1439                 if (t == ithread)
1440                         break;
1441
1442         /* the ithread no longer exists */
1443         if (NULL == t)
1444                 return;
1445
1446         c_ithread_destroy (ithread);
1447
1448         pthread_mutex_unlock (&perl_threads->mutex);
1449         return;
1450 } /* static void c_ithread_destructor (void *) */
1451
1452 /* must be called with perl_threads->mutex locked */
1453 static c_ithread_t *c_ithread_create (PerlInterpreter *base)
1454 {
1455         c_ithread_t *t = NULL;
1456         dTHXa (NULL);
1457
1458         assert (NULL != perl_threads);
1459
1460         t = (c_ithread_t *)smalloc (sizeof (c_ithread_t));
1461         memset (t, 0, sizeof (c_ithread_t));
1462
1463         t->interp = (NULL == base)
1464                 ? NULL
1465                 : perl_clone (base, CLONEf_KEEP_PTR_TABLE);
1466
1467         aTHX = t->interp;
1468
1469         if ((NULL != base) && (NULL != PL_endav)) {
1470                 av_clear (PL_endav);
1471                 av_undef (PL_endav);
1472                 PL_endav = Nullav;
1473         }
1474
1475 #if COLLECT_DEBUG
1476         ++perl_threads->number_of_threads;
1477 #endif /* COLLECT_DEBUG */
1478
1479         t->next = NULL;
1480
1481         if (NULL == perl_threads->tail) {
1482                 perl_threads->head = t;
1483                 t->prev = NULL;
1484         }
1485         else {
1486                 perl_threads->tail->next = t;
1487                 t->prev = perl_threads->tail;
1488         }
1489
1490         perl_threads->tail = t;
1491
1492         pthread_setspecific (perl_thr_key, (const void *)t);
1493         return t;
1494 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
1495
1496 /*
1497  * Interface to collectd.
1498  */
1499
1500 static int perl_init (void)
1501 {
1502         dTHX;
1503
1504         if (NULL == perl_threads)
1505                 return 0;
1506
1507         if (NULL == aTHX) {
1508                 c_ithread_t *t = NULL;
1509
1510                 pthread_mutex_lock (&perl_threads->mutex);
1511                 t = c_ithread_create (perl_threads->head->interp);
1512                 pthread_mutex_unlock (&perl_threads->mutex);
1513
1514                 aTHX = t->interp;
1515         }
1516
1517         log_debug ("perl_init: c_ithread: interp = %p (active threads: %i)",
1518                         aTHX, perl_threads->number_of_threads);
1519         return pplugin_call_all (aTHX_ PLUGIN_INIT);
1520 } /* static int perl_init (void) */
1521
1522 static int perl_read (void)
1523 {
1524         dTHX;
1525
1526         if (NULL == perl_threads)
1527                 return 0;
1528
1529         if (NULL == aTHX) {
1530                 c_ithread_t *t = NULL;
1531
1532                 pthread_mutex_lock (&perl_threads->mutex);
1533                 t = c_ithread_create (perl_threads->head->interp);
1534                 pthread_mutex_unlock (&perl_threads->mutex);
1535
1536                 aTHX = t->interp;
1537         }
1538
1539         log_debug ("perl_read: c_ithread: interp = %p (active threads: %i)",
1540                         aTHX, perl_threads->number_of_threads);
1541         return pplugin_call_all (aTHX_ PLUGIN_READ);
1542 } /* static int perl_read (void) */
1543
1544 static int perl_write (const data_set_t *ds, const value_list_t *vl)
1545 {
1546         dTHX;
1547
1548         if (NULL == perl_threads)
1549                 return 0;
1550
1551         if (NULL == aTHX) {
1552                 c_ithread_t *t = NULL;
1553
1554                 pthread_mutex_lock (&perl_threads->mutex);
1555                 t = c_ithread_create (perl_threads->head->interp);
1556                 pthread_mutex_unlock (&perl_threads->mutex);
1557
1558                 aTHX = t->interp;
1559         }
1560
1561         log_debug ("perl_write: c_ithread: interp = %p (active threads: %i)",
1562                         aTHX, perl_threads->number_of_threads);
1563         return pplugin_call_all (aTHX_ PLUGIN_WRITE, ds, vl);
1564 } /* static int perl_write (const data_set_t *, const value_list_t *) */
1565
1566 static void perl_log (int level, const char *msg)
1567 {
1568         dTHX;
1569
1570         if (NULL == perl_threads)
1571                 return;
1572
1573         if (NULL == aTHX) {
1574                 c_ithread_t *t = NULL;
1575
1576                 pthread_mutex_lock (&perl_threads->mutex);
1577                 t = c_ithread_create (perl_threads->head->interp);
1578                 pthread_mutex_unlock (&perl_threads->mutex);
1579
1580                 aTHX = t->interp;
1581         }
1582
1583         pplugin_call_all (aTHX_ PLUGIN_LOG, level, msg);
1584         return;
1585 } /* static void perl_log (int, const char *) */
1586
1587 static int perl_notify (const notification_t *notif)
1588 {
1589         dTHX;
1590
1591         if (NULL == perl_threads)
1592                 return 0;
1593
1594         if (NULL == aTHX) {
1595                 c_ithread_t *t = NULL;
1596
1597                 pthread_mutex_lock (&perl_threads->mutex);
1598                 t = c_ithread_create (perl_threads->head->interp);
1599                 pthread_mutex_unlock (&perl_threads->mutex);
1600
1601                 aTHX = t->interp;
1602         }
1603         return pplugin_call_all (aTHX_ PLUGIN_NOTIF, notif);
1604 } /* static int perl_notify (const notification_t *) */
1605
1606 static int perl_flush (int timeout, const char *identifier)
1607 {
1608         dTHX;
1609
1610         if (NULL == perl_threads)
1611                 return 0;
1612
1613         if (NULL == aTHX) {
1614                 c_ithread_t *t = NULL;
1615
1616                 pthread_mutex_lock (&perl_threads->mutex);
1617                 t = c_ithread_create (perl_threads->head->interp);
1618                 pthread_mutex_unlock (&perl_threads->mutex);
1619
1620                 aTHX = t->interp;
1621         }
1622         return pplugin_call_all (aTHX_ PLUGIN_FLUSH, timeout, identifier);
1623 } /* static int perl_flush (const int) */
1624
1625 static int perl_shutdown (void)
1626 {
1627         c_ithread_t *t = NULL;
1628
1629         int ret = 0;
1630
1631         dTHX;
1632
1633         plugin_unregister_complex_config ("perl");
1634
1635         if (NULL == perl_threads)
1636                 return 0;
1637
1638         if (NULL == aTHX) {
1639                 c_ithread_t *t = NULL;
1640
1641                 pthread_mutex_lock (&perl_threads->mutex);
1642                 t = c_ithread_create (perl_threads->head->interp);
1643                 pthread_mutex_unlock (&perl_threads->mutex);
1644
1645                 aTHX = t->interp;
1646         }
1647
1648         log_debug ("perl_shutdown: c_ithread: interp = %p (active threads: %i)",
1649                         aTHX, perl_threads->number_of_threads);
1650
1651         plugin_unregister_log ("perl");
1652         plugin_unregister_notification ("perl");
1653         plugin_unregister_init ("perl");
1654         plugin_unregister_read ("perl");
1655         plugin_unregister_write ("perl");
1656         plugin_unregister_flush ("perl");
1657
1658         ret = pplugin_call_all (aTHX_ PLUGIN_SHUTDOWN);
1659
1660         pthread_mutex_lock (&perl_threads->mutex);
1661         t = perl_threads->tail;
1662
1663         while (NULL != t) {
1664                 c_ithread_t *thr = t;
1665
1666                 /* the pointer has to be advanced before destroying
1667                  * the thread as this will free the memory */
1668                 t = t->prev;
1669
1670                 c_ithread_destroy (thr);
1671         }
1672
1673         pthread_mutex_unlock (&perl_threads->mutex);
1674         pthread_mutex_destroy (&perl_threads->mutex);
1675
1676         sfree (perl_threads);
1677
1678         pthread_key_delete (perl_thr_key);
1679
1680         PERL_SYS_TERM ();
1681
1682         plugin_unregister_shutdown ("perl");
1683         return ret;
1684 } /* static void perl_shutdown (void) */
1685
1686 /*
1687  * Access functions for global variables.
1688  *
1689  * These functions implement the "magic" used to access
1690  * the global variables from Perl.
1691  */
1692
1693 static int g_pv_get (pTHX_ SV *var, MAGIC *mg)
1694 {
1695         char *pv = mg->mg_ptr;
1696         sv_setpv (var, pv);
1697         return 0;
1698 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
1699
1700 static int g_pv_set (pTHX_ SV *var, MAGIC *mg)
1701 {
1702         char *pv = mg->mg_ptr;
1703         sstrncpy (pv, SvPV_nolen (var), DATA_MAX_NAME_LEN);
1704         return 0;
1705 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
1706
1707 static int g_iv_get (pTHX_ SV *var, MAGIC *mg)
1708 {
1709         int *iv = (int *)mg->mg_ptr;
1710         sv_setiv (var, *iv);
1711         return 0;
1712 } /* static int g_iv_get (pTHX_ SV *, MAGIC *) */
1713
1714 static int g_iv_set (pTHX_ SV *var, MAGIC *mg)
1715 {
1716         int *iv = (int *)mg->mg_ptr;
1717         *iv = (int)SvIV (var);
1718         return 0;
1719 } /* static int g_iv_set (pTHX_ SV *, MAGIC *) */
1720
1721 static MGVTBL g_pv_vtbl = {
1722         g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL
1723 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
1724                 , NULL
1725 #endif
1726 };
1727 static MGVTBL g_iv_vtbl = {
1728         g_iv_get, g_iv_set, NULL, NULL, NULL, NULL, NULL
1729 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
1730                 , NULL
1731 #endif
1732 };
1733
1734 /* bootstrap the Collectd module */
1735 static void xs_init (pTHX)
1736 {
1737         HV   *stash = NULL;
1738         SV   *tmp   = NULL;
1739         char *file  = __FILE__;
1740
1741         int i = 0;
1742
1743         dXSUB_SYS;
1744
1745         /* enable usage of Perl modules using shared libraries */
1746         newXS ("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
1747
1748         /* register API */
1749         for (i = 0; NULL != api[i].f; ++i)
1750                 newXS (api[i].name, api[i].f, file);
1751
1752         stash = gv_stashpv ("Collectd", 1);
1753
1754         /* export "constants" */
1755         for (i = 0; '\0' != constants[i].name[0]; ++i)
1756                 newCONSTSUB (stash, constants[i].name, newSViv (constants[i].value));
1757
1758         /* export global variables
1759          * by adding "magic" to the SV's representing the globale variables
1760          * perl is able to automagically call the get/set function when
1761          * accessing any such variable (this is basically the same as using
1762          * tie() in Perl) */
1763         /* global strings */
1764         for (i = 0; '\0' != g_strings[i].name[0]; ++i) {
1765                 tmp = get_sv (g_strings[i].name, 1);
1766                 sv_magicext (tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl,
1767                                 g_strings[i].var, 0);
1768         }
1769
1770         /* global integers */
1771         for (i = 0; '\0' != g_integers[i].name[0]; ++i) {
1772                 tmp = get_sv (g_integers[i].name, 1);
1773                 sv_magicext (tmp, NULL, PERL_MAGIC_ext, &g_iv_vtbl,
1774                                 (char *)g_integers[i].var, 0);
1775         }
1776         return;
1777 } /* static void xs_init (pTHX) */
1778
1779 /* Initialize the global Perl interpreter. */
1780 static int init_pi (int argc, char **argv)
1781 {
1782         dTHXa (NULL);
1783
1784         if (NULL != perl_threads)
1785                 return 0;
1786
1787         log_info ("Initializing Perl interpreter...");
1788 #if COLLECT_DEBUG
1789         {
1790                 int i = 0;
1791
1792                 for (i = 0; i < argc; ++i)
1793                         log_debug ("argv[%i] = \"%s\"", i, argv[i]);
1794         }
1795 #endif /* COLLECT_DEBUG */
1796
1797         if (0 != pthread_key_create (&perl_thr_key, c_ithread_destructor)) {
1798                 log_err ("init_pi: pthread_key_create failed");
1799
1800                 /* this must not happen - cowardly giving up if it does */
1801                 return -1;
1802         }
1803
1804 #ifdef __FreeBSD__
1805         /* On FreeBSD, PERL_SYS_INIT3 expands to some expression which
1806          * triggers a "value computed is not used" warning by gcc. */
1807         (void)
1808 #endif
1809         PERL_SYS_INIT3 (&argc, &argv, &environ);
1810
1811         perl_threads = (c_ithread_list_t *)smalloc (sizeof (c_ithread_list_t));
1812         memset (perl_threads, 0, sizeof (c_ithread_list_t));
1813
1814         pthread_mutex_init (&perl_threads->mutex, NULL);
1815         /* locking the mutex should not be necessary at this point
1816          * but let's just do it for the sake of completeness */
1817         pthread_mutex_lock (&perl_threads->mutex);
1818
1819         perl_threads->head = c_ithread_create (NULL);
1820         perl_threads->tail = perl_threads->head;
1821
1822         if (NULL == (perl_threads->head->interp = perl_alloc ())) {
1823                 log_err ("init_pi: Not enough memory.");
1824                 exit (3);
1825         }
1826
1827         aTHX = perl_threads->head->interp;
1828         pthread_mutex_unlock (&perl_threads->mutex);
1829
1830         perl_construct (aTHX);
1831
1832         PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
1833
1834         if (0 != perl_parse (aTHX_ xs_init, argc, argv, NULL)) {
1835                 SV *err = get_sv ("@", 1);
1836                 log_err ("init_pi: Unable to bootstrap Collectd: %s",
1837                                 SvPV_nolen (err));
1838
1839                 perl_destruct (perl_threads->head->interp);
1840                 perl_free (perl_threads->head->interp);
1841                 sfree (perl_threads);
1842
1843                 pthread_key_delete (perl_thr_key);
1844                 return -1;
1845         }
1846
1847         /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
1848         sv_setpv (get_sv ("0", 0), "collectd");
1849
1850         perl_run (aTHX);
1851
1852         plugin_register_log ("perl", perl_log);
1853         plugin_register_notification ("perl", perl_notify);
1854         plugin_register_init ("perl", perl_init);
1855
1856         plugin_register_read ("perl", perl_read);
1857
1858         plugin_register_write ("perl", perl_write);
1859         plugin_register_flush ("perl", perl_flush);
1860         plugin_register_shutdown ("perl", perl_shutdown);
1861         return 0;
1862 } /* static int init_pi (const char **, const int) */
1863
1864 /*
1865  * LoadPlugin "<Plugin>"
1866  */
1867 static int perl_config_loadplugin (pTHX_ oconfig_item_t *ci)
1868 {
1869         char module_name[DATA_MAX_NAME_LEN];
1870
1871         char *value = NULL;
1872
1873         if ((0 != ci->children_num) || (1 != ci->values_num)
1874                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1875                 log_err ("LoadPlugin expects a single string argument.");
1876                 return 1;
1877         }
1878
1879         value = ci->values[0].value.string;
1880
1881         if (NULL == get_module_name (module_name, sizeof (module_name), value)) {
1882                 log_err ("Invalid module name %s", value);
1883                 return (1);
1884         }
1885
1886         if (0 != init_pi (perl_argc, perl_argv))
1887                 return -1;
1888
1889         assert (NULL != perl_threads);
1890         assert (NULL != perl_threads->head);
1891
1892         aTHX = perl_threads->head->interp;
1893
1894         log_debug ("perl_config: loading perl plugin \"%s\"", value);
1895         load_module (PERL_LOADMOD_NOIMPORT,
1896                         newSVpv (module_name, strlen (module_name)), Nullsv);
1897         return 0;
1898 } /* static int perl_config_loadplugin (oconfig_item_it *) */
1899
1900 /*
1901  * BaseName "<Name>"
1902  */
1903 static int perl_config_basename (pTHX_ oconfig_item_t *ci)
1904 {
1905         char *value = NULL;
1906
1907         if ((0 != ci->children_num) || (1 != ci->values_num)
1908                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1909                 log_err ("BaseName expects a single string argument.");
1910                 return 1;
1911         }
1912
1913         value = ci->values[0].value.string;
1914
1915         log_debug ("perl_config: Setting plugin basename to \"%s\"", value);
1916         sstrncpy (base_name, value, sizeof (base_name));
1917         return 0;
1918 } /* static int perl_config_basename (oconfig_item_it *) */
1919
1920 /*
1921  * EnableDebugger "<Package>"|""
1922  */
1923 static int perl_config_enabledebugger (pTHX_ oconfig_item_t *ci)
1924 {
1925         char *value = NULL;
1926
1927         if ((0 != ci->children_num) || (1 != ci->values_num)
1928                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1929                 log_err ("EnableDebugger expects a single string argument.");
1930                 return 1;
1931         }
1932
1933         if (NULL != perl_threads) {
1934                 log_warn ("EnableDebugger has no effects if used after LoadPlugin.");
1935                 return 1;
1936         }
1937
1938         value = ci->values[0].value.string;
1939
1940         perl_argv = (char **)realloc (perl_argv,
1941                         (++perl_argc + 1) * sizeof (char *));
1942
1943         if (NULL == perl_argv) {
1944                 log_err ("perl_config: Not enough memory.");
1945                 exit (3);
1946         }
1947
1948         if ('\0' == value[0]) {
1949                 perl_argv[perl_argc - 1] = "-d";
1950         }
1951         else {
1952                 perl_argv[perl_argc - 1] = (char *)smalloc (strlen (value) + 4);
1953                 sstrncpy (perl_argv[perl_argc - 1], "-d:", 4);
1954                 sstrncpy (perl_argv[perl_argc - 1] + 3, value, strlen (value) + 1);
1955         }
1956
1957         perl_argv[perl_argc] = NULL;
1958         return 0;
1959 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
1960
1961 /*
1962  * IncludeDir "<Dir>"
1963  */
1964 static int perl_config_includedir (pTHX_ oconfig_item_t *ci)
1965 {
1966         char *value = NULL;
1967
1968         if ((0 != ci->children_num) || (1 != ci->values_num)
1969                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1970                 log_err ("IncludeDir expects a single string argument.");
1971                 return 1;
1972         }
1973
1974         value = ci->values[0].value.string;
1975
1976         if (NULL == aTHX) {
1977                 perl_argv = (char **)realloc (perl_argv,
1978                                 (++perl_argc + 1) * sizeof (char *));
1979
1980                 if (NULL == perl_argv) {
1981                         log_err ("perl_config: Not enough memory.");
1982                         exit (3);
1983                 }
1984
1985                 perl_argv[perl_argc - 1] = (char *)smalloc (strlen (value) + 3);
1986                 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
1987                 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen (value) + 1);
1988
1989                 perl_argv[perl_argc] = NULL;
1990         }
1991         else {
1992                 /* prepend the directory to @INC */
1993                 av_unshift (GvAVn (PL_incgv), 1);
1994                 av_store (GvAVn (PL_incgv), 0, newSVpv (value, strlen (value)));
1995         }
1996         return 0;
1997 } /* static int perl_config_includedir (oconfig_item_it *) */
1998
1999 /*
2000  * <Plugin> block
2001  */
2002 static int perl_config_plugin (pTHX_ oconfig_item_t *ci)
2003 {
2004         int retvals = 0;
2005         int ret     = 0;
2006
2007         char *plugin;
2008         HV   *config;
2009
2010         dSP;
2011
2012         if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2013                 log_err ("LoadPlugin expects a single string argument.");
2014                 return 1;
2015         }
2016
2017         plugin = ci->values[0].value.string;
2018         config = newHV ();
2019
2020         if (0 != oconfig_item2hv (aTHX_ ci, config)) {
2021                 hv_clear (config);
2022                 hv_undef (config);
2023
2024                 log_err ("Unable to convert configuration to a Perl hash value.");
2025                 config = Nullhv;
2026         }
2027
2028         ENTER;
2029         SAVETMPS;
2030
2031         PUSHMARK (SP);
2032
2033         XPUSHs (sv_2mortal (newSVpv (plugin, 0)));
2034         XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
2035
2036         PUTBACK;
2037
2038         retvals = call_pv ("Collectd::_plugin_dispatch_config", G_SCALAR);
2039
2040         SPAGAIN;
2041         if (0 < retvals) {
2042                 SV *tmp = POPs;
2043                 if (! SvTRUE (tmp))
2044                         ret = 1;
2045         }
2046         else
2047                 ret = 1;
2048
2049         PUTBACK;
2050         FREETMPS;
2051         LEAVE;
2052         return ret;
2053 } /* static int perl_config_plugin (oconfig_item_it *) */
2054
2055 static int perl_config (oconfig_item_t *ci)
2056 {
2057         int status = 0;
2058         int i = 0;
2059
2060         dTHXa (NULL);
2061
2062         for (i = 0; i < ci->children_num; ++i) {
2063                 oconfig_item_t *c = ci->children + i;
2064                 int current_status = 0;
2065
2066                 if (NULL != perl_threads)
2067                         aTHX = PERL_GET_CONTEXT;
2068
2069                 if (0 == strcasecmp (c->key, "LoadPlugin"))
2070                         current_status = perl_config_loadplugin (aTHX_ c);
2071                 else if (0 == strcasecmp (c->key, "BaseName"))
2072                         current_status = perl_config_basename (aTHX_ c);
2073                 else if (0 == strcasecmp (c->key, "EnableDebugger"))
2074                         current_status = perl_config_enabledebugger (aTHX_ c);
2075                 else if (0 == strcasecmp (c->key, "IncludeDir"))
2076                         current_status = perl_config_includedir (aTHX_ c);
2077                 else if (0 == strcasecmp (c->key, "Plugin"))
2078                         current_status = perl_config_plugin (aTHX_ c);
2079                 else
2080                 {
2081                         log_warn ("Ignoring unknown config key \"%s\".", c->key);
2082                         current_status = 0;
2083                 }
2084
2085                 /* fatal error - it's up to perl_config_* to clean up */
2086                 if (0 > current_status) {
2087                         log_err ("Configuration failed with a fatal error - "
2088                                         "plugin disabled!");
2089                         return current_status;
2090                 }
2091
2092                 status += current_status;
2093         }
2094         return status;
2095 } /* static int perl_config (oconfig_item_t *) */
2096
2097 void module_register (void)
2098 {
2099         perl_argc = 4;
2100         perl_argv = (char **)smalloc ((perl_argc + 1) * sizeof (char *));
2101
2102         /* default options for the Perl interpreter */
2103         perl_argv[0] = "";
2104         perl_argv[1] = "-MCollectd";
2105         perl_argv[2] = "-e";
2106         perl_argv[3] = "1";
2107         perl_argv[4] = NULL;
2108
2109         plugin_register_complex_config ("perl", perl_config);
2110         return;
2111 } /* void module_register (void) */
2112
2113 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */
2114