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