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