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