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