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