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