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