perl plugin: Convert notification meta data as well.
[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         if (NULL == notif)
918                 return -1;
919
920         memset (&n, 0, sizeof (n));
921
922         if (0 != hv2notification (aTHX_ notif, &n))
923                 return -1;
924
925         return plugin_dispatch_notification (&n);
926 } /* static int pplugin_dispatch_notification (HV *) */
927
928 /*
929  * Call all working functions of the given type.
930  */
931 static int pplugin_call_all (pTHX_ int type, ...)
932 {
933         int retvals = 0;
934
935         va_list ap;
936         int ret = 0;
937
938         dSP;
939
940         if ((type < 0) || (type >= PLUGIN_TYPES))
941                 return -1;
942
943         va_start (ap, type);
944
945         ENTER;
946         SAVETMPS;
947
948         PUSHMARK (SP);
949
950         XPUSHs (sv_2mortal (newSViv ((IV)type)));
951
952         if (PLUGIN_WRITE == type) {
953                 /*
954                  * $_[0] = $plugin_type;
955                  *
956                  * $_[1] =
957                  * [
958                  *   {
959                  *     name => $ds_name,
960                  *     type => $ds_type,
961                  *     min  => $ds_min,
962                  *     max  => $ds_max
963                  *   },
964                  *   ...
965                  * ];
966                  *
967                  * $_[2] =
968                  * {
969                  *   values => [ $v1, ... ],
970                  *   time   => $time,
971                  *   host   => $hostname,
972                  *   plugin => $plugin,
973                  *   type   => $type,
974                  *   plugin_instance => $instance,
975                  *   type_instance   => $type_instance
976                  * };
977                  */
978                 data_set_t   *ds;
979                 value_list_t *vl;
980
981                 AV *pds = newAV ();
982                 HV *pvl = newHV ();
983
984                 ds = va_arg (ap, data_set_t *);
985                 vl = va_arg (ap, value_list_t *);
986
987                 if (-1 == data_set2av (aTHX_ ds, pds)) {
988                         av_clear (pds);
989                         av_undef (pds);
990                         pds = Nullav;
991                         ret = -1;
992                 }
993
994                 if (-1 == value_list2hv (aTHX_ vl, ds, pvl)) {
995                         hv_clear (pvl);
996                         hv_undef (pvl);
997                         pvl = Nullhv;
998                         ret = -1;
999                 }
1000
1001                 XPUSHs (sv_2mortal (newSVpv (ds->type, 0)));
1002                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1003                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1004         }
1005         else if (PLUGIN_LOG == type) {
1006                 /*
1007                  * $_[0] = $level;
1008                  *
1009                  * $_[1] = $message;
1010                  */
1011                 XPUSHs (sv_2mortal (newSViv (va_arg (ap, int))));
1012                 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1013         }
1014         else if (PLUGIN_NOTIF == type) {
1015                 /*
1016                  * $_[0] =
1017                  * {
1018                  *   severity => $severity,
1019                  *   time     => $time,
1020                  *   message  => $msg,
1021                  *   host     => $host,
1022                  *   plugin   => $plugin,
1023                  *   type     => $type,
1024                  *   plugin_instance => $instance,
1025                  *   type_instance   => $type_instance
1026                  * };
1027                  */
1028                 notification_t *n;
1029                 HV *notif = newHV ();
1030
1031                 n = va_arg (ap, notification_t *);
1032
1033                 if (-1 == notification2hv (aTHX_ n, notif)) {
1034                         hv_clear (notif);
1035                         hv_undef (notif);
1036                         notif = Nullhv;
1037                         ret = -1;
1038                 }
1039
1040                 XPUSHs (sv_2mortal (newRV_noinc ((SV *)notif)));
1041         }
1042         else if (PLUGIN_FLUSH == type) {
1043                 /*
1044                  * $_[0] = $timeout;
1045                  * $_[1] = $identifier;
1046                  */
1047                 XPUSHs (sv_2mortal (newSViv (va_arg (ap, int))));
1048                 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1049         }
1050
1051         PUTBACK;
1052
1053         retvals = call_pv ("Collectd::plugin_call_all", G_SCALAR);
1054
1055         SPAGAIN;
1056         if (0 < retvals) {
1057                 SV *tmp = POPs;
1058                 if (! SvTRUE (tmp))
1059                         ret = -1;
1060         }
1061
1062         PUTBACK;
1063         FREETMPS;
1064         LEAVE;
1065
1066         va_end (ap);
1067         return ret;
1068 } /* static int pplugin_call_all (int, ...) */
1069
1070 /*
1071  * Exported Perl API.
1072  */
1073
1074 /*
1075  * Collectd::plugin_register_data_set (type, dataset).
1076  *
1077  * type:
1078  *   type of the dataset
1079  *
1080  * dataset:
1081  *   dataset to be registered
1082  */
1083 static XS (Collectd_plugin_register_ds)
1084 {
1085         SV  *data = NULL;
1086         int ret   = 0;
1087
1088         dXSARGS;
1089
1090         if (2 != items) {
1091                 log_err ("Usage: Collectd::plugin_register_data_set(type, dataset)");
1092                 XSRETURN_EMPTY;
1093         }
1094
1095         log_debug ("Collectd::plugin_register_data_set: "
1096                         "type = \"%s\", dataset = \"%s\"",
1097                         SvPV_nolen (ST (0)), SvPV_nolen (ST (1)));
1098
1099         data = ST (1);
1100
1101         if (SvROK (data) && (SVt_PVAV == SvTYPE (SvRV (data)))) {
1102                 ret = pplugin_register_data_set (aTHX_ SvPV_nolen (ST (0)),
1103                                 (AV *)SvRV (data));
1104         }
1105         else {
1106                 log_err ("Collectd::plugin_register_data_set: Invalid data.");
1107                 XSRETURN_EMPTY;
1108         }
1109
1110         if (0 == ret)
1111                 XSRETURN_YES;
1112         else
1113                 XSRETURN_EMPTY;
1114 } /* static XS (Collectd_plugin_register_ds) */
1115
1116 /*
1117  * Collectd::plugin_unregister_data_set (type).
1118  *
1119  * type:
1120  *   type of the dataset
1121  */
1122 static XS (Collectd_plugin_unregister_ds)
1123 {
1124         dXSARGS;
1125
1126         if (1 != items) {
1127                 log_err ("Usage: Collectd::plugin_unregister_data_set(type)");
1128                 XSRETURN_EMPTY;
1129         }
1130
1131         log_debug ("Collectd::plugin_unregister_data_set: type = \"%s\"",
1132                         SvPV_nolen (ST (0)));
1133
1134         if (0 == pplugin_unregister_data_set (SvPV_nolen (ST (0))))
1135                 XSRETURN_YES;
1136         else
1137                 XSRETURN_EMPTY;
1138 } /* static XS (Collectd_plugin_register_ds) */
1139
1140 /*
1141  * Collectd::plugin_dispatch_values (name, values).
1142  *
1143  * name:
1144  *   name of the plugin
1145  *
1146  * values:
1147  *   value list to submit
1148  */
1149 static XS (Collectd_plugin_dispatch_values)
1150 {
1151         SV *values     = NULL;
1152         int values_idx = 0;
1153
1154         int ret = 0;
1155
1156         dXSARGS;
1157
1158         if (2 == items) {
1159                 log_warn ("Collectd::plugin_dispatch_values with two arguments "
1160                                 "is deprecated - pass the type through values->{type}.");
1161                 values_idx = 1;
1162         }
1163         else if (1 != items) {
1164                 log_err ("Usage: Collectd::plugin_dispatch_values(values)");
1165                 XSRETURN_EMPTY;
1166         }
1167
1168         log_debug ("Collectd::plugin_dispatch_values: values=\"%s\"",
1169                         SvPV_nolen (ST (values_idx)));
1170
1171         values = ST (values_idx);
1172
1173         if (! (SvROK (values) && (SVt_PVHV == SvTYPE (SvRV (values))))) {
1174                 log_err ("Collectd::plugin_dispatch_values: Invalid values.");
1175                 XSRETURN_EMPTY;
1176         }
1177
1178         if (((2 == items) && (NULL == ST (0))) || (NULL == values))
1179                 XSRETURN_EMPTY;
1180
1181         if ((2 == items) && (NULL == hv_store ((HV *)SvRV (values), "type", 4,
1182                         newSVsv (ST (0)), 0))) {
1183                 log_err ("Collectd::plugin_dispatch_values: Could not store type.");
1184                 XSRETURN_EMPTY;
1185         }
1186
1187         ret = pplugin_dispatch_values (aTHX_ (HV *)SvRV (values));
1188
1189         if (0 == ret)
1190                 XSRETURN_YES;
1191         else
1192                 XSRETURN_EMPTY;
1193 } /* static XS (Collectd_plugin_dispatch_values) */
1194
1195 /* Collectd::plugin_write (plugin, ds, vl).
1196  *
1197  * plugin:
1198  *   name of the plugin to call, may be 'undef'
1199  *
1200  * ds:
1201  *   data-set that describes the submitted values, may be 'undef'
1202  *
1203  * vl:
1204  *   value-list to be written
1205  */
1206 static XS (Collectd__plugin_write)
1207 {
1208         char *plugin;
1209         SV   *ds, *vl;
1210         AV   *ds_array;
1211
1212         int ret;
1213
1214         dXSARGS;
1215
1216         if (3 != items) {
1217                 log_err ("Usage: Collectd::plugin_write(plugin, ds, vl)");
1218                 XSRETURN_EMPTY;
1219         }
1220
1221         log_debug ("Collectd::plugin_write: plugin=\"%s\", ds=\"%s\", vl=\"%s\"",
1222                         SvPV_nolen (ST (0)), SvOK (ST (1)) ? SvPV_nolen (ST (1)) : "",
1223                         SvPV_nolen (ST (2)));
1224
1225         if (! SvOK (ST (0)))
1226                 plugin = NULL;
1227         else
1228                 plugin = SvPV_nolen (ST (0));
1229
1230         ds = ST (1);
1231         if (SvROK (ds) && (SVt_PVAV == SvTYPE (SvRV (ds))))
1232                 ds_array = (AV *)SvRV (ds);
1233         else if (! SvOK (ds))
1234                 ds_array = NULL;
1235         else {
1236                 log_err ("Collectd::plugin_write: Invalid data-set.");
1237                 XSRETURN_EMPTY;
1238         }
1239
1240         vl = ST (2);
1241         if (! (SvROK (vl) && (SVt_PVHV == SvTYPE (SvRV (vl))))) {
1242                 log_err ("Collectd::plugin_write: Invalid value-list.");
1243                 XSRETURN_EMPTY;
1244         }
1245
1246         ret = pplugin_write (aTHX_ plugin, ds_array, (HV *)SvRV (vl));
1247
1248         if (0 == ret)
1249                 XSRETURN_YES;
1250         else
1251                 XSRETURN_EMPTY;
1252 } /* static XS (Collectd__plugin_write) */
1253
1254 /*
1255  * Collectd::_plugin_flush (plugin, timeout, identifier).
1256  *
1257  * plugin:
1258  *   name of the plugin to flush
1259  *
1260  * timeout:
1261  *   timeout to use when flushing the data
1262  *
1263  * identifier:
1264  *   data-set identifier to flush
1265  */
1266 static XS (Collectd__plugin_flush)
1267 {
1268         char *plugin  = NULL;
1269         int   timeout = -1;
1270         char *id      = NULL;
1271
1272         dXSARGS;
1273
1274         if (3 != items) {
1275                 log_err ("Usage: Collectd::_plugin_flush(plugin, timeout, id)");
1276                 XSRETURN_EMPTY;
1277         }
1278
1279         if (SvOK (ST (0)))
1280                 plugin = SvPV_nolen (ST (0));
1281
1282         if (SvOK (ST (1)))
1283                 timeout = (int)SvIV (ST (1));
1284
1285         if (SvOK (ST (2)))
1286                 id = SvPV_nolen (ST (2));
1287
1288         log_debug ("Collectd::_plugin_flush: plugin = \"%s\", timeout = %i, "
1289                         "id = \"%s\"", plugin, timeout, id);
1290
1291         if (0 == plugin_flush (plugin, timeout, id))
1292                 XSRETURN_YES;
1293         else
1294                 XSRETURN_EMPTY;
1295 } /* static XS (Collectd__plugin_flush) */
1296
1297 /*
1298  * Collectd::plugin_dispatch_notification (notif).
1299  *
1300  * notif:
1301  *   notification to dispatch
1302  */
1303 static XS (Collectd_plugin_dispatch_notification)
1304 {
1305         SV *notif = NULL;
1306
1307         int ret = 0;
1308
1309         dXSARGS;
1310
1311         if (1 != items) {
1312                 log_err ("Usage: Collectd::plugin_dispatch_notification(notif)");
1313                 XSRETURN_EMPTY;
1314         }
1315
1316         log_debug ("Collectd::plugin_dispatch_notification: notif = \"%s\"",
1317                         SvPV_nolen (ST (0)));
1318
1319         notif = ST (0);
1320
1321         if (! (SvROK (notif) && (SVt_PVHV == SvTYPE (SvRV (notif))))) {
1322                 log_err ("Collectd::plugin_dispatch_notification: Invalid notif.");
1323                 XSRETURN_EMPTY;
1324         }
1325
1326         ret = pplugin_dispatch_notification (aTHX_ (HV *)SvRV (notif));
1327
1328         if (0 == ret)
1329                 XSRETURN_YES;
1330         else
1331                 XSRETURN_EMPTY;
1332 } /* static XS (Collectd_plugin_dispatch_notification) */
1333
1334 /*
1335  * Collectd::plugin_log (level, message).
1336  *
1337  * level:
1338  *   log level (LOG_DEBUG, ... LOG_ERR)
1339  *
1340  * message:
1341  *   log message
1342  */
1343 static XS (Collectd_plugin_log)
1344 {
1345         dXSARGS;
1346
1347         if (2 != items) {
1348                 log_err ("Usage: Collectd::plugin_log(level, message)");
1349                 XSRETURN_EMPTY;
1350         }
1351
1352         plugin_log (SvIV (ST (0)), "%s", SvPV_nolen (ST (1)));
1353         XSRETURN_YES;
1354 } /* static XS (Collectd_plugin_log) */
1355
1356 /*
1357  * Collectd::call_by_name (...).
1358  *
1359  * Call a Perl sub identified by its name passed through $Collectd::cb_name.
1360  */
1361 static XS (Collectd_call_by_name)
1362 {
1363         SV   *tmp  = NULL;
1364         char *name = NULL;
1365
1366         if (NULL == (tmp = get_sv ("Collectd::cb_name", 0))) {
1367                 sv_setpv (get_sv ("@", 1), "cb_name has not been set");
1368                 CLEAR_STACK_FRAME;
1369                 return;
1370         }
1371
1372         name = SvPV_nolen (tmp);
1373
1374         if (NULL == get_cv (name, 0)) {
1375                 sv_setpvf (get_sv ("@", 1), "unknown callback \"%s\"", name);
1376                 CLEAR_STACK_FRAME;
1377                 return;
1378         }
1379
1380         /* simply pass on the subroutine call without touching the stack,
1381          * thus leaving any arguments and return values in place */
1382         call_pv (name, 0);
1383 } /* static XS (Collectd_call_by_name) */
1384
1385 /*
1386  * collectd's perl interpreter based thread implementation.
1387  *
1388  * This has been inspired by Perl's ithreads introduced in version 5.6.0.
1389  */
1390
1391 /* must be called with perl_threads->mutex locked */
1392 static void c_ithread_destroy (c_ithread_t *ithread)
1393 {
1394         dTHXa (ithread->interp);
1395
1396         assert (NULL != perl_threads);
1397
1398         PERL_SET_CONTEXT (aTHX);
1399         log_debug ("Shutting down Perl interpreter %p...", aTHX);
1400
1401 #if COLLECT_DEBUG
1402         sv_report_used ();
1403
1404         --perl_threads->number_of_threads;
1405 #endif /* COLLECT_DEBUG */
1406
1407         perl_destruct (aTHX);
1408         perl_free (aTHX);
1409
1410         if (NULL == ithread->prev)
1411                 perl_threads->head = ithread->next;
1412         else
1413                 ithread->prev->next = ithread->next;
1414
1415         if (NULL == ithread->next)
1416                 perl_threads->tail = ithread->prev;
1417         else
1418                 ithread->next->prev = ithread->prev;
1419
1420         sfree (ithread);
1421         return;
1422 } /* static void c_ithread_destroy (c_ithread_t *) */
1423
1424 static void c_ithread_destructor (void *arg)
1425 {
1426         c_ithread_t *ithread = (c_ithread_t *)arg;
1427         c_ithread_t *t = NULL;
1428
1429         if (NULL == perl_threads)
1430                 return;
1431
1432         pthread_mutex_lock (&perl_threads->mutex);
1433
1434         for (t = perl_threads->head; NULL != t; t = t->next)
1435                 if (t == ithread)
1436                         break;
1437
1438         /* the ithread no longer exists */
1439         if (NULL == t)
1440                 return;
1441
1442         c_ithread_destroy (ithread);
1443
1444         pthread_mutex_unlock (&perl_threads->mutex);
1445         return;
1446 } /* static void c_ithread_destructor (void *) */
1447
1448 /* must be called with perl_threads->mutex locked */
1449 static c_ithread_t *c_ithread_create (PerlInterpreter *base)
1450 {
1451         c_ithread_t *t = NULL;
1452         dTHXa (NULL);
1453
1454         assert (NULL != perl_threads);
1455
1456         t = (c_ithread_t *)smalloc (sizeof (c_ithread_t));
1457         memset (t, 0, sizeof (c_ithread_t));
1458
1459         t->interp = (NULL == base)
1460                 ? NULL
1461                 : perl_clone (base, CLONEf_KEEP_PTR_TABLE);
1462
1463         aTHX = t->interp;
1464
1465         if ((NULL != base) && (NULL != PL_endav)) {
1466                 av_clear (PL_endav);
1467                 av_undef (PL_endav);
1468                 PL_endav = Nullav;
1469         }
1470
1471 #if COLLECT_DEBUG
1472         ++perl_threads->number_of_threads;
1473 #endif /* COLLECT_DEBUG */
1474
1475         t->next = NULL;
1476
1477         if (NULL == perl_threads->tail) {
1478                 perl_threads->head = t;
1479                 t->prev = NULL;
1480         }
1481         else {
1482                 perl_threads->tail->next = t;
1483                 t->prev = perl_threads->tail;
1484         }
1485
1486         perl_threads->tail = t;
1487
1488         pthread_setspecific (perl_thr_key, (const void *)t);
1489         return t;
1490 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
1491
1492 /*
1493  * Interface to collectd.
1494  */
1495
1496 static int perl_init (void)
1497 {
1498         dTHX;
1499
1500         if (NULL == perl_threads)
1501                 return 0;
1502
1503         if (NULL == aTHX) {
1504                 c_ithread_t *t = NULL;
1505
1506                 pthread_mutex_lock (&perl_threads->mutex);
1507                 t = c_ithread_create (perl_threads->head->interp);
1508                 pthread_mutex_unlock (&perl_threads->mutex);
1509
1510                 aTHX = t->interp;
1511         }
1512
1513         log_debug ("perl_init: c_ithread: interp = %p (active threads: %i)",
1514                         aTHX, perl_threads->number_of_threads);
1515         return pplugin_call_all (aTHX_ PLUGIN_INIT);
1516 } /* static int perl_init (void) */
1517
1518 static int perl_read (void)
1519 {
1520         dTHX;
1521
1522         if (NULL == perl_threads)
1523                 return 0;
1524
1525         if (NULL == aTHX) {
1526                 c_ithread_t *t = NULL;
1527
1528                 pthread_mutex_lock (&perl_threads->mutex);
1529                 t = c_ithread_create (perl_threads->head->interp);
1530                 pthread_mutex_unlock (&perl_threads->mutex);
1531
1532                 aTHX = t->interp;
1533         }
1534
1535         log_debug ("perl_read: c_ithread: interp = %p (active threads: %i)",
1536                         aTHX, perl_threads->number_of_threads);
1537         return pplugin_call_all (aTHX_ PLUGIN_READ);
1538 } /* static int perl_read (void) */
1539
1540 static int perl_write (const data_set_t *ds, const value_list_t *vl)
1541 {
1542         dTHX;
1543
1544         if (NULL == perl_threads)
1545                 return 0;
1546
1547         if (NULL == aTHX) {
1548                 c_ithread_t *t = NULL;
1549
1550                 pthread_mutex_lock (&perl_threads->mutex);
1551                 t = c_ithread_create (perl_threads->head->interp);
1552                 pthread_mutex_unlock (&perl_threads->mutex);
1553
1554                 aTHX = t->interp;
1555         }
1556
1557         log_debug ("perl_write: c_ithread: interp = %p (active threads: %i)",
1558                         aTHX, perl_threads->number_of_threads);
1559         return pplugin_call_all (aTHX_ PLUGIN_WRITE, ds, vl);
1560 } /* static int perl_write (const data_set_t *, const value_list_t *) */
1561
1562 static void perl_log (int level, const char *msg)
1563 {
1564         dTHX;
1565
1566         if (NULL == perl_threads)
1567                 return;
1568
1569         if (NULL == aTHX) {
1570                 c_ithread_t *t = NULL;
1571
1572                 pthread_mutex_lock (&perl_threads->mutex);
1573                 t = c_ithread_create (perl_threads->head->interp);
1574                 pthread_mutex_unlock (&perl_threads->mutex);
1575
1576                 aTHX = t->interp;
1577         }
1578
1579         pplugin_call_all (aTHX_ PLUGIN_LOG, level, msg);
1580         return;
1581 } /* static void perl_log (int, const char *) */
1582
1583 static int perl_notify (const notification_t *notif)
1584 {
1585         dTHX;
1586
1587         if (NULL == perl_threads)
1588                 return 0;
1589
1590         if (NULL == aTHX) {
1591                 c_ithread_t *t = NULL;
1592
1593                 pthread_mutex_lock (&perl_threads->mutex);
1594                 t = c_ithread_create (perl_threads->head->interp);
1595                 pthread_mutex_unlock (&perl_threads->mutex);
1596
1597                 aTHX = t->interp;
1598         }
1599         return pplugin_call_all (aTHX_ PLUGIN_NOTIF, notif);
1600 } /* static int perl_notify (const notification_t *) */
1601
1602 static int perl_flush (int timeout, const char *identifier)
1603 {
1604         dTHX;
1605
1606         if (NULL == perl_threads)
1607                 return 0;
1608
1609         if (NULL == aTHX) {
1610                 c_ithread_t *t = NULL;
1611
1612                 pthread_mutex_lock (&perl_threads->mutex);
1613                 t = c_ithread_create (perl_threads->head->interp);
1614                 pthread_mutex_unlock (&perl_threads->mutex);
1615
1616                 aTHX = t->interp;
1617         }
1618         return pplugin_call_all (aTHX_ PLUGIN_FLUSH, timeout, identifier);
1619 } /* static int perl_flush (const int) */
1620
1621 static int perl_shutdown (void)
1622 {
1623         c_ithread_t *t = NULL;
1624
1625         int ret = 0;
1626
1627         dTHX;
1628
1629         plugin_unregister_complex_config ("perl");
1630
1631         if (NULL == perl_threads)
1632                 return 0;
1633
1634         if (NULL == aTHX) {
1635                 c_ithread_t *t = NULL;
1636
1637                 pthread_mutex_lock (&perl_threads->mutex);
1638                 t = c_ithread_create (perl_threads->head->interp);
1639                 pthread_mutex_unlock (&perl_threads->mutex);
1640
1641                 aTHX = t->interp;
1642         }
1643
1644         log_debug ("perl_shutdown: c_ithread: interp = %p (active threads: %i)",
1645                         aTHX, perl_threads->number_of_threads);
1646
1647         plugin_unregister_log ("perl");
1648         plugin_unregister_notification ("perl");
1649         plugin_unregister_init ("perl");
1650         plugin_unregister_read ("perl");
1651         plugin_unregister_write ("perl");
1652         plugin_unregister_flush ("perl");
1653
1654         ret = pplugin_call_all (aTHX_ PLUGIN_SHUTDOWN);
1655
1656         pthread_mutex_lock (&perl_threads->mutex);
1657         t = perl_threads->tail;
1658
1659         while (NULL != t) {
1660                 c_ithread_t *thr = t;
1661
1662                 /* the pointer has to be advanced before destroying
1663                  * the thread as this will free the memory */
1664                 t = t->prev;
1665
1666                 c_ithread_destroy (thr);
1667         }
1668
1669         pthread_mutex_unlock (&perl_threads->mutex);
1670         pthread_mutex_destroy (&perl_threads->mutex);
1671
1672         sfree (perl_threads);
1673
1674         pthread_key_delete (perl_thr_key);
1675
1676         PERL_SYS_TERM ();
1677
1678         plugin_unregister_shutdown ("perl");
1679         return ret;
1680 } /* static void perl_shutdown (void) */
1681
1682 /*
1683  * Access functions for global variables.
1684  *
1685  * These functions implement the "magic" used to access
1686  * the global variables from Perl.
1687  */
1688
1689 static int g_pv_get (pTHX_ SV *var, MAGIC *mg)
1690 {
1691         char *pv = mg->mg_ptr;
1692         sv_setpv (var, pv);
1693         return 0;
1694 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
1695
1696 static int g_pv_set (pTHX_ SV *var, MAGIC *mg)
1697 {
1698         char *pv = mg->mg_ptr;
1699         sstrncpy (pv, SvPV_nolen (var), DATA_MAX_NAME_LEN);
1700         return 0;
1701 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
1702
1703 static int g_iv_get (pTHX_ SV *var, MAGIC *mg)
1704 {
1705         int *iv = (int *)mg->mg_ptr;
1706         sv_setiv (var, *iv);
1707         return 0;
1708 } /* static int g_iv_get (pTHX_ SV *, MAGIC *) */
1709
1710 static int g_iv_set (pTHX_ SV *var, MAGIC *mg)
1711 {
1712         int *iv = (int *)mg->mg_ptr;
1713         *iv = (int)SvIV (var);
1714         return 0;
1715 } /* static int g_iv_set (pTHX_ SV *, MAGIC *) */
1716
1717 static MGVTBL g_pv_vtbl = {
1718         g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL
1719 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
1720                 , NULL
1721 #endif
1722 };
1723 static MGVTBL g_iv_vtbl = {
1724         g_iv_get, g_iv_set, NULL, NULL, NULL, NULL, NULL
1725 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
1726                 , NULL
1727 #endif
1728 };
1729
1730 /* bootstrap the Collectd module */
1731 static void xs_init (pTHX)
1732 {
1733         HV   *stash = NULL;
1734         SV   *tmp   = NULL;
1735         char *file  = __FILE__;
1736
1737         int i = 0;
1738
1739         dXSUB_SYS;
1740
1741         /* enable usage of Perl modules using shared libraries */
1742         newXS ("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
1743
1744         /* register API */
1745         for (i = 0; NULL != api[i].f; ++i)
1746                 newXS (api[i].name, api[i].f, file);
1747
1748         stash = gv_stashpv ("Collectd", 1);
1749
1750         /* export "constants" */
1751         for (i = 0; '\0' != constants[i].name[0]; ++i)
1752                 newCONSTSUB (stash, constants[i].name, newSViv (constants[i].value));
1753
1754         /* export global variables
1755          * by adding "magic" to the SV's representing the globale variables
1756          * perl is able to automagically call the get/set function when
1757          * accessing any such variable (this is basically the same as using
1758          * tie() in Perl) */
1759         /* global strings */
1760         for (i = 0; '\0' != g_strings[i].name[0]; ++i) {
1761                 tmp = get_sv (g_strings[i].name, 1);
1762                 sv_magicext (tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl,
1763                                 g_strings[i].var, 0);
1764         }
1765
1766         /* global integers */
1767         for (i = 0; '\0' != g_integers[i].name[0]; ++i) {
1768                 tmp = get_sv (g_integers[i].name, 1);
1769                 sv_magicext (tmp, NULL, PERL_MAGIC_ext, &g_iv_vtbl,
1770                                 (char *)g_integers[i].var, 0);
1771         }
1772         return;
1773 } /* static void xs_init (pTHX) */
1774
1775 /* Initialize the global Perl interpreter. */
1776 static int init_pi (int argc, char **argv)
1777 {
1778         dTHXa (NULL);
1779
1780         if (NULL != perl_threads)
1781                 return 0;
1782
1783         log_info ("Initializing Perl interpreter...");
1784 #if COLLECT_DEBUG
1785         {
1786                 int i = 0;
1787
1788                 for (i = 0; i < argc; ++i)
1789                         log_debug ("argv[%i] = \"%s\"", i, argv[i]);
1790         }
1791 #endif /* COLLECT_DEBUG */
1792
1793         if (0 != pthread_key_create (&perl_thr_key, c_ithread_destructor)) {
1794                 log_err ("init_pi: pthread_key_create failed");
1795
1796                 /* this must not happen - cowardly giving up if it does */
1797                 return -1;
1798         }
1799
1800 #ifdef __FreeBSD__
1801         /* On FreeBSD, PERL_SYS_INIT3 expands to some expression which
1802          * triggers a "value computed is not used" warning by gcc. */
1803         (void)
1804 #endif
1805         PERL_SYS_INIT3 (&argc, &argv, &environ);
1806
1807         perl_threads = (c_ithread_list_t *)smalloc (sizeof (c_ithread_list_t));
1808         memset (perl_threads, 0, sizeof (c_ithread_list_t));
1809
1810         pthread_mutex_init (&perl_threads->mutex, NULL);
1811         /* locking the mutex should not be necessary at this point
1812          * but let's just do it for the sake of completeness */
1813         pthread_mutex_lock (&perl_threads->mutex);
1814
1815         perl_threads->head = c_ithread_create (NULL);
1816         perl_threads->tail = perl_threads->head;
1817
1818         if (NULL == (perl_threads->head->interp = perl_alloc ())) {
1819                 log_err ("init_pi: Not enough memory.");
1820                 exit (3);
1821         }
1822
1823         aTHX = perl_threads->head->interp;
1824         pthread_mutex_unlock (&perl_threads->mutex);
1825
1826         perl_construct (aTHX);
1827
1828         PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
1829
1830         if (0 != perl_parse (aTHX_ xs_init, argc, argv, NULL)) {
1831                 SV *err = get_sv ("@", 1);
1832                 log_err ("init_pi: Unable to bootstrap Collectd: %s",
1833                                 SvPV_nolen (err));
1834
1835                 perl_destruct (perl_threads->head->interp);
1836                 perl_free (perl_threads->head->interp);
1837                 sfree (perl_threads);
1838
1839                 pthread_key_delete (perl_thr_key);
1840                 return -1;
1841         }
1842
1843         /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
1844         sv_setpv (get_sv ("0", 0), "collectd");
1845
1846         perl_run (aTHX);
1847
1848         plugin_register_log ("perl", perl_log);
1849         plugin_register_notification ("perl", perl_notify);
1850         plugin_register_init ("perl", perl_init);
1851
1852         plugin_register_read ("perl", perl_read);
1853
1854         plugin_register_write ("perl", perl_write);
1855         plugin_register_flush ("perl", perl_flush);
1856         plugin_register_shutdown ("perl", perl_shutdown);
1857         return 0;
1858 } /* static int init_pi (const char **, const int) */
1859
1860 /*
1861  * LoadPlugin "<Plugin>"
1862  */
1863 static int perl_config_loadplugin (pTHX_ oconfig_item_t *ci)
1864 {
1865         char module_name[DATA_MAX_NAME_LEN];
1866
1867         char *value = NULL;
1868
1869         if ((0 != ci->children_num) || (1 != ci->values_num)
1870                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1871                 log_err ("LoadPlugin expects a single string argument.");
1872                 return 1;
1873         }
1874
1875         value = ci->values[0].value.string;
1876
1877         if (NULL == get_module_name (module_name, sizeof (module_name), value)) {
1878                 log_err ("Invalid module name %s", value);
1879                 return (1);
1880         }
1881
1882         if (0 != init_pi (perl_argc, perl_argv))
1883                 return -1;
1884
1885         assert (NULL != perl_threads);
1886         assert (NULL != perl_threads->head);
1887
1888         aTHX = perl_threads->head->interp;
1889
1890         log_debug ("perl_config: loading perl plugin \"%s\"", value);
1891         load_module (PERL_LOADMOD_NOIMPORT,
1892                         newSVpv (module_name, strlen (module_name)), Nullsv);
1893         return 0;
1894 } /* static int perl_config_loadplugin (oconfig_item_it *) */
1895
1896 /*
1897  * BaseName "<Name>"
1898  */
1899 static int perl_config_basename (pTHX_ oconfig_item_t *ci)
1900 {
1901         char *value = NULL;
1902
1903         if ((0 != ci->children_num) || (1 != ci->values_num)
1904                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1905                 log_err ("BaseName expects a single string argument.");
1906                 return 1;
1907         }
1908
1909         value = ci->values[0].value.string;
1910
1911         log_debug ("perl_config: Setting plugin basename to \"%s\"", value);
1912         sstrncpy (base_name, value, sizeof (base_name));
1913         return 0;
1914 } /* static int perl_config_basename (oconfig_item_it *) */
1915
1916 /*
1917  * EnableDebugger "<Package>"|""
1918  */
1919 static int perl_config_enabledebugger (pTHX_ oconfig_item_t *ci)
1920 {
1921         char *value = NULL;
1922
1923         if ((0 != ci->children_num) || (1 != ci->values_num)
1924                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1925                 log_err ("EnableDebugger expects a single string argument.");
1926                 return 1;
1927         }
1928
1929         if (NULL != perl_threads) {
1930                 log_warn ("EnableDebugger has no effects if used after LoadPlugin.");
1931                 return 1;
1932         }
1933
1934         value = ci->values[0].value.string;
1935
1936         perl_argv = (char **)realloc (perl_argv,
1937                         (++perl_argc + 1) * sizeof (char *));
1938
1939         if (NULL == perl_argv) {
1940                 log_err ("perl_config: Not enough memory.");
1941                 exit (3);
1942         }
1943
1944         if ('\0' == value[0]) {
1945                 perl_argv[perl_argc - 1] = "-d";
1946         }
1947         else {
1948                 perl_argv[perl_argc - 1] = (char *)smalloc (strlen (value) + 4);
1949                 sstrncpy (perl_argv[perl_argc - 1], "-d:", 4);
1950                 sstrncpy (perl_argv[perl_argc - 1] + 3, value, strlen (value) + 1);
1951         }
1952
1953         perl_argv[perl_argc] = NULL;
1954         return 0;
1955 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
1956
1957 /*
1958  * IncludeDir "<Dir>"
1959  */
1960 static int perl_config_includedir (pTHX_ oconfig_item_t *ci)
1961 {
1962         char *value = NULL;
1963
1964         if ((0 != ci->children_num) || (1 != ci->values_num)
1965                         || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1966                 log_err ("IncludeDir expects a single string argument.");
1967                 return 1;
1968         }
1969
1970         value = ci->values[0].value.string;
1971
1972         if (NULL == aTHX) {
1973                 perl_argv = (char **)realloc (perl_argv,
1974                                 (++perl_argc + 1) * sizeof (char *));
1975
1976                 if (NULL == perl_argv) {
1977                         log_err ("perl_config: Not enough memory.");
1978                         exit (3);
1979                 }
1980
1981                 perl_argv[perl_argc - 1] = (char *)smalloc (strlen (value) + 3);
1982                 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
1983                 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen (value) + 1);
1984
1985                 perl_argv[perl_argc] = NULL;
1986         }
1987         else {
1988                 /* prepend the directory to @INC */
1989                 av_unshift (GvAVn (PL_incgv), 1);
1990                 av_store (GvAVn (PL_incgv), 0, newSVpv (value, strlen (value)));
1991         }
1992         return 0;
1993 } /* static int perl_config_includedir (oconfig_item_it *) */
1994
1995 /*
1996  * <Plugin> block
1997  */
1998 static int perl_config_plugin (pTHX_ oconfig_item_t *ci)
1999 {
2000         int retvals = 0;
2001         int ret     = 0;
2002
2003         char *plugin;
2004         HV   *config;
2005
2006         dSP;
2007
2008         if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2009                 log_err ("LoadPlugin expects a single string argument.");
2010                 return 1;
2011         }
2012
2013         plugin = ci->values[0].value.string;
2014         config = newHV ();
2015
2016         if (0 != oconfig_item2hv (aTHX_ ci, config)) {
2017                 hv_clear (config);
2018                 hv_undef (config);
2019
2020                 log_err ("Unable to convert configuration to a Perl hash value.");
2021                 config = Nullhv;
2022         }
2023
2024         ENTER;
2025         SAVETMPS;
2026
2027         PUSHMARK (SP);
2028
2029         XPUSHs (sv_2mortal (newSVpv (plugin, 0)));
2030         XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
2031
2032         PUTBACK;
2033
2034         retvals = call_pv ("Collectd::_plugin_dispatch_config", G_SCALAR);
2035
2036         SPAGAIN;
2037         if (0 < retvals) {
2038                 SV *tmp = POPs;
2039                 if (! SvTRUE (tmp))
2040                         ret = 1;
2041         }
2042         else
2043                 ret = 1;
2044
2045         PUTBACK;
2046         FREETMPS;
2047         LEAVE;
2048         return ret;
2049 } /* static int perl_config_plugin (oconfig_item_it *) */
2050
2051 static int perl_config (oconfig_item_t *ci)
2052 {
2053         int status = 0;
2054         int i = 0;
2055
2056         dTHXa (NULL);
2057
2058         for (i = 0; i < ci->children_num; ++i) {
2059                 oconfig_item_t *c = ci->children + i;
2060                 int current_status = 0;
2061
2062                 if (NULL != perl_threads)
2063                         aTHX = PERL_GET_CONTEXT;
2064
2065                 if (0 == strcasecmp (c->key, "LoadPlugin"))
2066                         current_status = perl_config_loadplugin (aTHX_ c);
2067                 else if (0 == strcasecmp (c->key, "BaseName"))
2068                         current_status = perl_config_basename (aTHX_ c);
2069                 else if (0 == strcasecmp (c->key, "EnableDebugger"))
2070                         current_status = perl_config_enabledebugger (aTHX_ c);
2071                 else if (0 == strcasecmp (c->key, "IncludeDir"))
2072                         current_status = perl_config_includedir (aTHX_ c);
2073                 else if (0 == strcasecmp (c->key, "Plugin"))
2074                         current_status = perl_config_plugin (aTHX_ c);
2075                 else
2076                 {
2077                         log_warn ("Ignoring unknown config key \"%s\".", c->key);
2078                         current_status = 0;
2079                 }
2080
2081                 /* fatal error - it's up to perl_config_* to clean up */
2082                 if (0 > current_status) {
2083                         log_err ("Configuration failed with a fatal error - "
2084                                         "plugin disabled!");
2085                         return current_status;
2086                 }
2087
2088                 status += current_status;
2089         }
2090         return status;
2091 } /* static int perl_config (oconfig_item_t *) */
2092
2093 void module_register (void)
2094 {
2095         perl_argc = 4;
2096         perl_argv = (char **)smalloc ((perl_argc + 1) * sizeof (char *));
2097
2098         /* default options for the Perl interpreter */
2099         perl_argv[0] = "";
2100         perl_argv[1] = "-MCollectd";
2101         perl_argv[2] = "-e";
2102         perl_argv[3] = "1";
2103         perl_argv[4] = NULL;
2104
2105         plugin_register_complex_config ("perl", perl_config);
2106         return;
2107 } /* void module_register (void) */
2108
2109 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */
2110