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