src/daemon/collectd.c: do not refer to syslog in error message
[collectd.git] / src / perl.c
1 /**
2  * collectd - src/perl.c
3  * Copyright (C) 2007-2009  Sebastian Harl
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Sebastian Harl <sh at tokkee.org>
25  **/
26
27 /*
28  * This plugin embeds a Perl interpreter into collectd and provides an
29  * interface for collectd plugins written in perl.
30  */
31
32 /* do not automatically get the thread specific Perl interpreter */
33 #define PERL_NO_GET_CONTEXT
34
35 #define DONT_POISON_SPRINTF_YET 1
36 #include "collectd.h"
37
38 #undef DONT_POISON_SPRINTF_YET
39
40 #if HAVE_STDBOOL_H
41 #include <stdbool.h>
42 #endif
43
44 #include <EXTERN.h>
45 #include <perl.h>
46
47 #if defined(COLLECT_DEBUG) && COLLECT_DEBUG && defined(__GNUC__) && __GNUC__
48 #undef sprintf
49 #pragma GCC poison sprintf
50 #endif
51
52 #include <XSUB.h>
53
54 /* Some versions of Perl define their own version of DEBUG... :-/ */
55 #ifdef DEBUG
56 #undef DEBUG
57 #endif /* DEBUG */
58
59 /* ... while we want the definition found in plugin.h. */
60 #include "common.h"
61 #include "plugin.h"
62
63 #include "filter_chain.h"
64
65 #if !defined(USE_ITHREADS)
66 #error "Perl does not support ithreads!"
67 #endif /* !defined(USE_ITHREADS) */
68
69 /* clear the Perl sub's stack frame
70  * (this should only be used inside an XSUB) */
71 #define CLEAR_STACK_FRAME PL_stack_sp = PL_stack_base + *PL_markstack_ptr
72
73 #define PLUGIN_INIT 0
74 #define PLUGIN_READ 1
75 #define PLUGIN_WRITE 2
76 #define PLUGIN_SHUTDOWN 3
77 #define PLUGIN_LOG 4
78 #define PLUGIN_NOTIF 5
79 #define PLUGIN_FLUSH 6
80
81 #define PLUGIN_TYPES 7
82
83 #define PLUGIN_CONFIG 254
84 #define PLUGIN_DATASET 255
85
86 #define FC_MATCH 0
87 #define FC_TARGET 1
88
89 #define FC_TYPES 2
90
91 #define FC_CB_CREATE 0
92 #define FC_CB_DESTROY 1
93 #define FC_CB_EXEC 2
94
95 #define FC_CB_TYPES 3
96
97 #define log_debug(...) DEBUG("perl: " __VA_ARGS__)
98 #define log_info(...) INFO("perl: " __VA_ARGS__)
99 #define log_warn(...) WARNING("perl: " __VA_ARGS__)
100 #define log_err(...) ERROR("perl: " __VA_ARGS__)
101
102 /* this is defined in DynaLoader.a */
103 void boot_DynaLoader(PerlInterpreter *, CV *);
104
105 static XS(Collectd_plugin_register_ds);
106 static XS(Collectd_plugin_unregister_ds);
107 static XS(Collectd_plugin_dispatch_values);
108 static XS(Collectd_plugin_get_interval);
109 static XS(Collectd__plugin_write);
110 static XS(Collectd__plugin_flush);
111 static XS(Collectd_plugin_dispatch_notification);
112 static XS(Collectd_plugin_log);
113 static XS(Collectd__fc_register);
114 static XS(Collectd_call_by_name);
115
116 /*
117  * private data types
118  */
119
120 typedef struct c_ithread_s {
121   /* the thread's Perl interpreter */
122   PerlInterpreter *interp;
123   _Bool running; /* thread is inside Perl interpreter */
124   _Bool shutdown;
125   pthread_t pthread;
126
127   /* double linked list of threads */
128   struct c_ithread_s *prev;
129   struct c_ithread_s *next;
130 } c_ithread_t;
131
132 typedef struct {
133   c_ithread_t *head;
134   c_ithread_t *tail;
135
136 #if COLLECT_DEBUG
137   /* some usage stats */
138   int number_of_threads;
139 #endif /* COLLECT_DEBUG */
140
141   pthread_mutex_t mutex;
142   pthread_mutexattr_t mutexattr;
143 } c_ithread_list_t;
144
145 /* name / user_data for Perl matches / targets */
146 typedef struct {
147   char *name;
148   SV *user_data;
149 } pfc_user_data_t;
150
151 #define PFC_USER_DATA_FREE(data)                                               \
152   do {                                                                         \
153     sfree((data)->name);                                                       \
154     if (NULL != (data)->user_data)                                             \
155       sv_free((data)->user_data);                                              \
156     sfree(data);                                                               \
157   } while (0)
158
159 /*
160  * Public variable
161  */
162 extern char **environ;
163
164 /*
165  * private variables
166  */
167
168 /* if perl_threads != NULL perl_threads->head must
169  * point to the "base" thread */
170 static c_ithread_list_t *perl_threads = NULL;
171
172 /* the key used to store each pthread's ithread */
173 static pthread_key_t perl_thr_key;
174
175 static int perl_argc = 0;
176 static char **perl_argv = NULL;
177
178 static char base_name[DATA_MAX_NAME_LEN] = "";
179
180 static struct {
181   char name[64];
182   XS((*f));
183 } api[] = {
184     {"Collectd::plugin_register_data_set", Collectd_plugin_register_ds},
185     {"Collectd::plugin_unregister_data_set", Collectd_plugin_unregister_ds},
186     {"Collectd::plugin_dispatch_values", Collectd_plugin_dispatch_values},
187     {"Collectd::plugin_get_interval", Collectd_plugin_get_interval},
188     {"Collectd::_plugin_write", Collectd__plugin_write},
189     {"Collectd::_plugin_flush", Collectd__plugin_flush},
190     {"Collectd::plugin_dispatch_notification",
191      Collectd_plugin_dispatch_notification},
192     {"Collectd::plugin_log", Collectd_plugin_log},
193     {"Collectd::_fc_register", Collectd__fc_register},
194     {"Collectd::call_by_name", Collectd_call_by_name},
195     {"", NULL}};
196
197 struct {
198   char name[64];
199   int value;
200 } constants[] = {{"Collectd::TYPE_INIT", PLUGIN_INIT},
201                  {"Collectd::TYPE_READ", PLUGIN_READ},
202                  {"Collectd::TYPE_WRITE", PLUGIN_WRITE},
203                  {"Collectd::TYPE_SHUTDOWN", PLUGIN_SHUTDOWN},
204                  {"Collectd::TYPE_LOG", PLUGIN_LOG},
205                  {"Collectd::TYPE_NOTIF", PLUGIN_NOTIF},
206                  {"Collectd::TYPE_FLUSH", PLUGIN_FLUSH},
207                  {"Collectd::TYPE_CONFIG", PLUGIN_CONFIG},
208                  {"Collectd::TYPE_DATASET", PLUGIN_DATASET},
209                  {"Collectd::DS_TYPE_COUNTER", DS_TYPE_COUNTER},
210                  {"Collectd::DS_TYPE_GAUGE", DS_TYPE_GAUGE},
211                  {"Collectd::DS_TYPE_DERIVE", DS_TYPE_DERIVE},
212                  {"Collectd::DS_TYPE_ABSOLUTE", DS_TYPE_ABSOLUTE},
213                  {"Collectd::LOG_ERR", LOG_ERR},
214                  {"Collectd::LOG_WARNING", LOG_WARNING},
215                  {"Collectd::LOG_NOTICE", LOG_NOTICE},
216                  {"Collectd::LOG_INFO", LOG_INFO},
217                  {"Collectd::LOG_DEBUG", LOG_DEBUG},
218                  {"Collectd::FC_MATCH", FC_MATCH},
219                  {"Collectd::FC_TARGET", FC_TARGET},
220                  {"Collectd::FC_CB_CREATE", FC_CB_CREATE},
221                  {"Collectd::FC_CB_DESTROY", FC_CB_DESTROY},
222                  {"Collectd::FC_CB_EXEC", FC_CB_EXEC},
223                  {"Collectd::FC_MATCH_NO_MATCH", FC_MATCH_NO_MATCH},
224                  {"Collectd::FC_MATCH_MATCHES", FC_MATCH_MATCHES},
225                  {"Collectd::FC_TARGET_CONTINUE", FC_TARGET_CONTINUE},
226                  {"Collectd::FC_TARGET_STOP", FC_TARGET_STOP},
227                  {"Collectd::FC_TARGET_RETURN", FC_TARGET_RETURN},
228                  {"Collectd::NOTIF_FAILURE", NOTIF_FAILURE},
229                  {"Collectd::NOTIF_WARNING", NOTIF_WARNING},
230                  {"Collectd::NOTIF_OKAY", NOTIF_OKAY},
231                  {"", 0}};
232
233 struct {
234   char name[64];
235   char *var;
236 } g_strings[] = {{"Collectd::hostname_g", hostname_g}, {"", NULL}};
237
238 /*
239  * Helper functions for data type conversion.
240  */
241
242 /*
243  * data source:
244  * [
245  *   {
246  *     name => $ds_name,
247  *     type => $ds_type,
248  *     min  => $ds_min,
249  *     max  => $ds_max
250  *   },
251  *   ...
252  * ]
253  */
254 static int hv2data_source(pTHX_ HV *hash, data_source_t *ds) {
255   SV **tmp = NULL;
256
257   if ((NULL == hash) || (NULL == ds))
258     return -1;
259
260   if (NULL != (tmp = hv_fetch(hash, "name", 4, 0))) {
261     sstrncpy(ds->name, SvPV_nolen(*tmp), sizeof(ds->name));
262   } else {
263     log_err("hv2data_source: No DS name given.");
264     return -1;
265   }
266
267   if (NULL != (tmp = hv_fetch(hash, "type", 4, 0))) {
268     ds->type = SvIV(*tmp);
269
270     if ((DS_TYPE_COUNTER != ds->type) && (DS_TYPE_GAUGE != ds->type) &&
271         (DS_TYPE_DERIVE != ds->type) && (DS_TYPE_ABSOLUTE != ds->type)) {
272       log_err("hv2data_source: Invalid DS type.");
273       return -1;
274     }
275   } else {
276     ds->type = DS_TYPE_COUNTER;
277   }
278
279   if (NULL != (tmp = hv_fetch(hash, "min", 3, 0)))
280     ds->min = SvNV(*tmp);
281   else
282     ds->min = NAN;
283
284   if (NULL != (tmp = hv_fetch(hash, "max", 3, 0)))
285     ds->max = SvNV(*tmp);
286   else
287     ds->max = NAN;
288   return 0;
289 } /* static int hv2data_source (HV *, data_source_t *) */
290
291 /* av2value converts at most "len" elements from "array" to "value". Returns the
292  * number of elements converted or zero on error. */
293 static size_t av2value(pTHX_ char *name, AV *array, value_t *value,
294                        size_t array_len) {
295   const data_set_t *ds;
296
297   if ((NULL == name) || (NULL == array) || (NULL == value) || (array_len == 0))
298     return 0;
299
300   ds = plugin_get_ds(name);
301   if (NULL == ds) {
302     log_err("av2value: Unknown dataset \"%s\"", name);
303     return 0;
304   }
305
306   if (array_len < ds->ds_num) {
307     log_warn("av2value: array does not contain enough elements for type "
308              "\"%s\": got %zu, want %zu",
309              name, array_len, ds->ds_num);
310     return 0;
311   } else if (array_len > ds->ds_num) {
312     log_warn("av2value: array contains excess elements for type \"%s\": got "
313              "%zu, want %zu",
314              name, array_len, ds->ds_num);
315   }
316
317   for (size_t i = 0; i < ds->ds_num; ++i) {
318     SV **tmp = av_fetch(array, i, 0);
319
320     if (NULL != tmp) {
321       if (DS_TYPE_COUNTER == ds->ds[i].type)
322         value[i].counter = SvIV(*tmp);
323       else if (DS_TYPE_GAUGE == ds->ds[i].type)
324         value[i].gauge = SvNV(*tmp);
325       else if (DS_TYPE_DERIVE == ds->ds[i].type)
326         value[i].derive = SvIV(*tmp);
327       else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
328         value[i].absolute = SvIV(*tmp);
329     } else {
330       return 0;
331     }
332   }
333
334   return ds->ds_num;
335 } /* static size_t av2value (char *, AV *, value_t *, size_t) */
336
337 /*
338  * value list:
339  * {
340  *   values => [ @values ],
341  *   time   => $time,
342  *   host   => $host,
343  *   plugin => $plugin,
344  *   plugin_instance => $pinstance,
345  *   type_instance   => $tinstance,
346  * }
347  */
348 static int hv2value_list(pTHX_ HV *hash, value_list_t *vl) {
349   SV **tmp;
350
351   if ((NULL == hash) || (NULL == vl))
352     return -1;
353
354   if (NULL == (tmp = hv_fetch(hash, "type", 4, 0))) {
355     log_err("hv2value_list: No type given.");
356     return -1;
357   }
358
359   sstrncpy(vl->type, SvPV_nolen(*tmp), sizeof(vl->type));
360
361   if ((NULL == (tmp = hv_fetch(hash, "values", 6, 0))) ||
362       (!(SvROK(*tmp) && (SVt_PVAV == SvTYPE(SvRV(*tmp)))))) {
363     log_err("hv2value_list: No valid values given.");
364     return -1;
365   }
366
367   {
368     AV *array = (AV *)SvRV(*tmp);
369     /* av_len returns the highest index, not the actual length. */
370     size_t array_len = (size_t)(av_len(array) + 1);
371     if (array_len == 0)
372       return -1;
373
374     vl->values = calloc(array_len, sizeof(*vl->values));
375     vl->values_len =
376         av2value(aTHX_ vl->type, (AV *)SvRV(*tmp), vl->values, array_len);
377     if (vl->values_len == 0) {
378       sfree(vl->values);
379       return -1;
380     }
381   }
382
383   if (NULL != (tmp = hv_fetch(hash, "time", 4, 0))) {
384     double t = SvNV(*tmp);
385     vl->time = DOUBLE_TO_CDTIME_T(t);
386   }
387
388   if (NULL != (tmp = hv_fetch(hash, "interval", 8, 0))) {
389     double t = SvNV(*tmp);
390     vl->interval = DOUBLE_TO_CDTIME_T(t);
391   }
392
393   if (NULL != (tmp = hv_fetch(hash, "host", 4, 0)))
394     sstrncpy(vl->host, SvPV_nolen(*tmp), sizeof(vl->host));
395   else
396     sstrncpy(vl->host, hostname_g, sizeof(vl->host));
397
398   if (NULL != (tmp = hv_fetch(hash, "plugin", 6, 0)))
399     sstrncpy(vl->plugin, SvPV_nolen(*tmp), sizeof(vl->plugin));
400
401   if (NULL != (tmp = hv_fetch(hash, "plugin_instance", 15, 0)))
402     sstrncpy(vl->plugin_instance, SvPV_nolen(*tmp),
403              sizeof(vl->plugin_instance));
404
405   if (NULL != (tmp = hv_fetch(hash, "type_instance", 13, 0)))
406     sstrncpy(vl->type_instance, SvPV_nolen(*tmp), sizeof(vl->type_instance));
407   return 0;
408 } /* static int hv2value_list (pTHX_ HV *, value_list_t *) */
409
410 static int av2data_set(pTHX_ AV *array, char *name, data_set_t *ds) {
411   int len;
412
413   if ((NULL == array) || (NULL == name) || (NULL == ds))
414     return -1;
415
416   len = av_len(array);
417
418   if (-1 == len) {
419     log_err("av2data_set: Invalid data set.");
420     return -1;
421   }
422
423   ds->ds = smalloc((len + 1) * sizeof(*ds->ds));
424   ds->ds_num = len + 1;
425
426   for (int i = 0; i <= len; ++i) {
427     SV **elem = av_fetch(array, i, 0);
428
429     if (NULL == elem) {
430       log_err("av2data_set: Failed to fetch data source %i.", i);
431       return -1;
432     }
433
434     if (!(SvROK(*elem) && (SVt_PVHV == SvTYPE(SvRV(*elem))))) {
435       log_err("av2data_set: Invalid data source.");
436       return -1;
437     }
438
439     if (-1 == hv2data_source(aTHX_(HV *) SvRV(*elem), &ds->ds[i]))
440       return -1;
441
442     log_debug("av2data_set: "
443               "DS.name = \"%s\", DS.type = %i, DS.min = %f, DS.max = %f",
444               ds->ds[i].name, ds->ds[i].type, ds->ds[i].min, ds->ds[i].max);
445   }
446
447   sstrncpy(ds->type, name, sizeof(ds->type));
448   return 0;
449 } /* static int av2data_set (pTHX_ AV *, data_set_t *) */
450
451 /*
452  * notification:
453  * {
454  *   severity => $severity,
455  *   time     => $time,
456  *   message  => $msg,
457  *   host     => $host,
458  *   plugin   => $plugin,
459  *   type     => $type,
460  *   plugin_instance => $instance,
461  *   type_instance   => $type_instance,
462  *   meta     => [ { name => <name>, value => <value> }, ... ]
463  * }
464  */
465 static int av2notification_meta(pTHX_ AV *array, notification_meta_t **meta) {
466   notification_meta_t **m = meta;
467
468   int len = av_len(array);
469
470   for (int i = 0; i <= len; ++i) {
471     SV **tmp = av_fetch(array, i, 0);
472     HV *hash;
473
474     if (NULL == tmp)
475       return -1;
476
477     if (!(SvROK(*tmp) && (SVt_PVHV == SvTYPE(SvRV(*tmp))))) {
478       log_warn("av2notification_meta: Skipping invalid "
479                "meta information.");
480       continue;
481     }
482
483     hash = (HV *)SvRV(*tmp);
484
485     *m = smalloc(sizeof(**m));
486
487     if (NULL == (tmp = hv_fetch(hash, "name", 4, 0))) {
488       log_warn("av2notification_meta: Skipping invalid "
489                "meta information.");
490       free(*m);
491       continue;
492     }
493     sstrncpy((*m)->name, SvPV_nolen(*tmp), sizeof((*m)->name));
494
495     if (NULL == (tmp = hv_fetch(hash, "value", 5, 0))) {
496       log_warn("av2notification_meta: Skipping invalid "
497                "meta information.");
498       free(*m);
499       continue;
500     }
501
502     if (SvNOK(*tmp)) {
503       (*m)->nm_value.nm_double = SvNVX(*tmp);
504       (*m)->type = NM_TYPE_DOUBLE;
505     } else if (SvUOK(*tmp)) {
506       (*m)->nm_value.nm_unsigned_int = SvUVX(*tmp);
507       (*m)->type = NM_TYPE_UNSIGNED_INT;
508     } else if (SvIOK(*tmp)) {
509       (*m)->nm_value.nm_signed_int = SvIVX(*tmp);
510       (*m)->type = NM_TYPE_SIGNED_INT;
511     } else {
512       (*m)->nm_value.nm_string = sstrdup(SvPV_nolen(*tmp));
513       (*m)->type = NM_TYPE_STRING;
514     }
515
516     (*m)->next = NULL;
517     m = &((*m)->next);
518   }
519   return 0;
520 } /* static int av2notification_meta (AV *, notification_meta_t *) */
521
522 static int hv2notification(pTHX_ HV *hash, notification_t *n) {
523   SV **tmp = NULL;
524
525   if ((NULL == hash) || (NULL == n))
526     return -1;
527
528   if (NULL != (tmp = hv_fetch(hash, "severity", 8, 0)))
529     n->severity = SvIV(*tmp);
530   else
531     n->severity = NOTIF_FAILURE;
532
533   if (NULL != (tmp = hv_fetch(hash, "time", 4, 0))) {
534     double t = SvNV(*tmp);
535     n->time = DOUBLE_TO_CDTIME_T(t);
536   } else
537     n->time = cdtime();
538
539   if (NULL != (tmp = hv_fetch(hash, "message", 7, 0)))
540     sstrncpy(n->message, SvPV_nolen(*tmp), sizeof(n->message));
541
542   if (NULL != (tmp = hv_fetch(hash, "host", 4, 0)))
543     sstrncpy(n->host, SvPV_nolen(*tmp), sizeof(n->host));
544   else
545     sstrncpy(n->host, hostname_g, sizeof(n->host));
546
547   if (NULL != (tmp = hv_fetch(hash, "plugin", 6, 0)))
548     sstrncpy(n->plugin, SvPV_nolen(*tmp), sizeof(n->plugin));
549
550   if (NULL != (tmp = hv_fetch(hash, "plugin_instance", 15, 0)))
551     sstrncpy(n->plugin_instance, SvPV_nolen(*tmp), sizeof(n->plugin_instance));
552
553   if (NULL != (tmp = hv_fetch(hash, "type", 4, 0)))
554     sstrncpy(n->type, SvPV_nolen(*tmp), sizeof(n->type));
555
556   if (NULL != (tmp = hv_fetch(hash, "type_instance", 13, 0)))
557     sstrncpy(n->type_instance, SvPV_nolen(*tmp), sizeof(n->type_instance));
558
559   n->meta = NULL;
560   while (NULL != (tmp = hv_fetch(hash, "meta", 4, 0))) {
561     if (!(SvROK(*tmp) && (SVt_PVAV == SvTYPE(SvRV(*tmp))))) {
562       log_warn("hv2notification: Ignoring invalid meta information.");
563       break;
564     }
565
566     if (0 != av2notification_meta(aTHX_(AV *) SvRV(*tmp), &n->meta)) {
567       plugin_notification_meta_free(n->meta);
568       n->meta = NULL;
569       return -1;
570     }
571     break;
572   }
573   return 0;
574 } /* static int hv2notification (pTHX_ HV *, notification_t *) */
575
576 static int data_set2av(pTHX_ data_set_t *ds, AV *array) {
577   if ((NULL == ds) || (NULL == array))
578     return -1;
579
580   av_extend(array, ds->ds_num);
581
582   for (size_t i = 0; i < ds->ds_num; ++i) {
583     HV *source = newHV();
584
585     if (NULL == hv_store(source, "name", 4, newSVpv(ds->ds[i].name, 0), 0))
586       return -1;
587
588     if (NULL == hv_store(source, "type", 4, newSViv(ds->ds[i].type), 0))
589       return -1;
590
591     if (!isnan(ds->ds[i].min))
592       if (NULL == hv_store(source, "min", 3, newSVnv(ds->ds[i].min), 0))
593         return -1;
594
595     if (!isnan(ds->ds[i].max))
596       if (NULL == hv_store(source, "max", 3, newSVnv(ds->ds[i].max), 0))
597         return -1;
598
599     if (NULL == av_store(array, i, newRV_noinc((SV *)source)))
600       return -1;
601   }
602   return 0;
603 } /* static int data_set2av (data_set_t *, AV *) */
604
605 static int value_list2hv(pTHX_ value_list_t *vl, data_set_t *ds, HV *hash) {
606   AV *values = NULL;
607   size_t i;
608
609   if ((NULL == vl) || (NULL == ds) || (NULL == hash))
610     return -1;
611
612   values = newAV();
613   /* av_extend takes the last *index* to which the array should be extended. */
614   av_extend(values, vl->values_len - 1);
615
616   assert(ds->ds_num == vl->values_len);
617   for (i = 0; i < vl->values_len; ++i) {
618     SV *val = NULL;
619
620     if (DS_TYPE_COUNTER == ds->ds[i].type)
621       val = newSViv(vl->values[i].counter);
622     else if (DS_TYPE_GAUGE == ds->ds[i].type)
623       val = newSVnv(vl->values[i].gauge);
624     else if (DS_TYPE_DERIVE == ds->ds[i].type)
625       val = newSViv(vl->values[i].derive);
626     else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
627       val = newSViv(vl->values[i].absolute);
628
629     if (NULL == av_store(values, i, val)) {
630       av_undef(values);
631       return -1;
632     }
633   }
634
635   if (NULL == hv_store(hash, "values", 6, newRV_noinc((SV *)values), 0))
636     return -1;
637
638   if (0 != vl->time) {
639     double t = CDTIME_T_TO_DOUBLE(vl->time);
640     if (NULL == hv_store(hash, "time", 4, newSVnv(t), 0))
641       return -1;
642   }
643
644   {
645     double t = CDTIME_T_TO_DOUBLE(vl->interval);
646     if (NULL == hv_store(hash, "interval", 8, newSVnv(t), 0))
647       return -1;
648   }
649
650   if ('\0' != vl->host[0])
651     if (NULL == hv_store(hash, "host", 4, newSVpv(vl->host, 0), 0))
652       return -1;
653
654   if ('\0' != vl->plugin[0])
655     if (NULL == hv_store(hash, "plugin", 6, newSVpv(vl->plugin, 0), 0))
656       return -1;
657
658   if ('\0' != vl->plugin_instance[0])
659     if (NULL == hv_store(hash, "plugin_instance", 15,
660                          newSVpv(vl->plugin_instance, 0), 0))
661       return -1;
662
663   if ('\0' != vl->type[0])
664     if (NULL == hv_store(hash, "type", 4, newSVpv(vl->type, 0), 0))
665       return -1;
666
667   if ('\0' != vl->type_instance[0])
668     if (NULL ==
669         hv_store(hash, "type_instance", 13, newSVpv(vl->type_instance, 0), 0))
670       return -1;
671   return 0;
672 } /* static int value2av (value_list_t *, data_set_t *, HV *) */
673
674 static int notification_meta2av(pTHX_ notification_meta_t *meta, AV *array) {
675   int meta_num = 0;
676
677   while (meta) {
678     ++meta_num;
679     meta = meta->next;
680   }
681
682   av_extend(array, meta_num);
683
684   for (int i = 0; NULL != meta; meta = meta->next, ++i) {
685     HV *m = newHV();
686     SV *value;
687
688     if (NULL == hv_store(m, "name", 4, newSVpv(meta->name, 0), 0))
689       return -1;
690
691     if (NM_TYPE_STRING == meta->type)
692       value = newSVpv(meta->nm_value.nm_string, 0);
693     else if (NM_TYPE_SIGNED_INT == meta->type)
694       value = newSViv(meta->nm_value.nm_signed_int);
695     else if (NM_TYPE_UNSIGNED_INT == meta->type)
696       value = newSVuv(meta->nm_value.nm_unsigned_int);
697     else if (NM_TYPE_DOUBLE == meta->type)
698       value = newSVnv(meta->nm_value.nm_double);
699     else if (NM_TYPE_BOOLEAN == meta->type)
700       value = meta->nm_value.nm_boolean ? &PL_sv_yes : &PL_sv_no;
701     else
702       return -1;
703
704     if (NULL == hv_store(m, "value", 5, value, 0)) {
705       sv_free(value);
706       return -1;
707     }
708
709     if (NULL == av_store(array, i, newRV_noinc((SV *)m))) {
710       hv_clear(m);
711       hv_undef(m);
712       return -1;
713     }
714   }
715   return 0;
716 } /* static int notification_meta2av (notification_meta_t *, AV *) */
717
718 static int notification2hv(pTHX_ notification_t *n, HV *hash) {
719   if (NULL == hv_store(hash, "severity", 8, newSViv(n->severity), 0))
720     return -1;
721
722   if (0 != n->time) {
723     double t = CDTIME_T_TO_DOUBLE(n->time);
724     if (NULL == hv_store(hash, "time", 4, newSVnv(t), 0))
725       return -1;
726   }
727
728   if ('\0' != *n->message)
729     if (NULL == hv_store(hash, "message", 7, newSVpv(n->message, 0), 0))
730       return -1;
731
732   if ('\0' != *n->host)
733     if (NULL == hv_store(hash, "host", 4, newSVpv(n->host, 0), 0))
734       return -1;
735
736   if ('\0' != *n->plugin)
737     if (NULL == hv_store(hash, "plugin", 6, newSVpv(n->plugin, 0), 0))
738       return -1;
739
740   if ('\0' != *n->plugin_instance)
741     if (NULL == hv_store(hash, "plugin_instance", 15,
742                          newSVpv(n->plugin_instance, 0), 0))
743       return -1;
744
745   if ('\0' != *n->type)
746     if (NULL == hv_store(hash, "type", 4, newSVpv(n->type, 0), 0))
747       return -1;
748
749   if ('\0' != *n->type_instance)
750     if (NULL ==
751         hv_store(hash, "type_instance", 13, newSVpv(n->type_instance, 0), 0))
752       return -1;
753
754   if (NULL != n->meta) {
755     AV *meta = newAV();
756     if ((0 != notification_meta2av(aTHX_ n->meta, meta)) ||
757         (NULL == hv_store(hash, "meta", 4, newRV_noinc((SV *)meta), 0))) {
758       av_clear(meta);
759       av_undef(meta);
760       return -1;
761     }
762   }
763   return 0;
764 } /* static int notification2hv (notification_t *, HV *) */
765
766 static int oconfig_item2hv(pTHX_ oconfig_item_t *ci, HV *hash) {
767   AV *values;
768   AV *children;
769
770   if (NULL == hv_store(hash, "key", 3, newSVpv(ci->key, 0), 0))
771     return -1;
772
773   values = newAV();
774   if (0 < ci->values_num)
775     av_extend(values, ci->values_num);
776
777   if (NULL == hv_store(hash, "values", 6, newRV_noinc((SV *)values), 0)) {
778     av_clear(values);
779     av_undef(values);
780     return -1;
781   }
782
783   for (int i = 0; i < ci->values_num; ++i) {
784     SV *value;
785
786     switch (ci->values[i].type) {
787     case OCONFIG_TYPE_STRING:
788       value = newSVpv(ci->values[i].value.string, 0);
789       break;
790     case OCONFIG_TYPE_NUMBER:
791       value = newSVnv((NV)ci->values[i].value.number);
792       break;
793     case OCONFIG_TYPE_BOOLEAN:
794       value = ci->values[i].value.boolean ? &PL_sv_yes : &PL_sv_no;
795       break;
796     default:
797       log_err("oconfig_item2hv: Invalid value type %i.", ci->values[i].type);
798       value = &PL_sv_undef;
799     }
800
801     if (NULL == av_store(values, i, value)) {
802       sv_free(value);
803       return -1;
804     }
805   }
806
807   /* ignoring 'parent' member which is uninteresting in this case */
808
809   children = newAV();
810   if (0 < ci->children_num)
811     av_extend(children, ci->children_num);
812
813   if (NULL == hv_store(hash, "children", 8, newRV_noinc((SV *)children), 0)) {
814     av_clear(children);
815     av_undef(children);
816     return -1;
817   }
818
819   for (int i = 0; i < ci->children_num; ++i) {
820     HV *child = newHV();
821
822     if (0 != oconfig_item2hv(aTHX_ ci->children + i, child)) {
823       hv_clear(child);
824       hv_undef(child);
825       return -1;
826     }
827
828     if (NULL == av_store(children, i, newRV_noinc((SV *)child))) {
829       hv_clear(child);
830       hv_undef(child);
831       return -1;
832     }
833   }
834   return 0;
835 } /* static int oconfig_item2hv (pTHX_ oconfig_item_t *, HV *) */
836
837 /*
838  * Internal functions.
839  */
840
841 static char *get_module_name(char *buf, size_t buf_len, const char *module) {
842   int status = 0;
843   if (base_name[0] == '\0')
844     status = ssnprintf(buf, buf_len, "%s", module);
845   else
846     status = ssnprintf(buf, buf_len, "%s::%s", base_name, module);
847   if ((status < 0) || ((unsigned int)status >= buf_len))
848     return (NULL);
849   return (buf);
850 } /* char *get_module_name */
851
852 /*
853  * Add a plugin's data set definition.
854  */
855 static int pplugin_register_data_set(pTHX_ char *name, AV *dataset) {
856   int ret = 0;
857
858   data_set_t ds;
859
860   if ((NULL == name) || (NULL == dataset))
861     return -1;
862
863   if (0 != av2data_set(aTHX_ dataset, name, &ds))
864     return -1;
865
866   ret = plugin_register_data_set(&ds);
867
868   free(ds.ds);
869   return ret;
870 } /* static int pplugin_register_data_set (char *, SV *) */
871
872 /*
873  * Remove a plugin's data set definition.
874  */
875 static int pplugin_unregister_data_set(char *name) {
876   if (NULL == name)
877     return 0;
878   return plugin_unregister_data_set(name);
879 } /* static int pplugin_unregister_data_set (char *) */
880
881 /*
882  * Submit the values to the write functions.
883  */
884 static int pplugin_dispatch_values(pTHX_ HV *values) {
885   value_list_t vl = VALUE_LIST_INIT;
886
887   int ret = 0;
888
889   if (NULL == values)
890     return -1;
891
892   if (0 != hv2value_list(aTHX_ values, &vl))
893     return -1;
894
895   ret = plugin_dispatch_values(&vl);
896
897   sfree(vl.values);
898   return ret;
899 } /* static int pplugin_dispatch_values (char *, HV *) */
900
901 /*
902  * Submit the values to a single write function.
903  */
904 static int pplugin_write(pTHX_ const char *plugin, AV *data_set, HV *values) {
905   data_set_t ds;
906   value_list_t vl = VALUE_LIST_INIT;
907
908   int ret;
909
910   if (NULL == values)
911     return -1;
912
913   if (0 != hv2value_list(aTHX_ values, &vl))
914     return -1;
915
916   if ((NULL != data_set) && (0 != av2data_set(aTHX_ data_set, vl.type, &ds)))
917     return -1;
918
919   ret = plugin_write(plugin, NULL == data_set ? NULL : &ds, &vl);
920   if (0 != ret)
921     log_warn("Dispatching value to plugin \"%s\" failed with status %i.",
922              NULL == plugin ? "<any>" : plugin, ret);
923
924   if (NULL != data_set)
925     sfree(ds.ds);
926   sfree(vl.values);
927   return ret;
928 } /* static int pplugin_write (const char *plugin, HV *, HV *) */
929
930 /*
931  * Dispatch a notification.
932  */
933 static int pplugin_dispatch_notification(pTHX_ HV *notif) {
934   notification_t n = {0};
935
936   int ret;
937
938   if (NULL == notif)
939     return -1;
940
941   if (0 != hv2notification(aTHX_ notif, &n))
942     return -1;
943
944   ret = plugin_dispatch_notification(&n);
945   plugin_notification_meta_free(n.meta);
946   return ret;
947 } /* static int pplugin_dispatch_notification (HV *) */
948
949 /*
950  * Call perl sub with thread locking flags handled.
951  */
952 static int call_pv_locked(pTHX_ const char *sub_name) {
953   _Bool old_running;
954   int ret;
955
956   c_ithread_t *t = (c_ithread_t *)pthread_getspecific(perl_thr_key);
957   if (t == NULL) /* thread destroyed */
958     return 0;
959
960   old_running = t->running;
961   t->running = 1;
962
963   if (t->shutdown) {
964     t->running = old_running;
965     return 0;
966   }
967
968   ret = call_pv(sub_name, G_SCALAR);
969
970   t->running = old_running;
971   return ret;
972 } /* static int call_pv_locked (pTHX, *sub_name) */
973
974 /*
975  * Call all working functions of the given type.
976  */
977 static int pplugin_call_all(pTHX_ int type, ...) {
978   int retvals = 0;
979
980   va_list ap;
981   int ret = 0;
982
983   dSP;
984
985   if ((type < 0) || (type >= PLUGIN_TYPES))
986     return -1;
987
988   va_start(ap, type);
989
990   ENTER;
991   SAVETMPS;
992
993   PUSHMARK(SP);
994
995   XPUSHs(sv_2mortal(newSViv((IV)type)));
996
997   if (PLUGIN_WRITE == type) {
998     /*
999      * $_[0] = $plugin_type;
1000      *
1001      * $_[1] =
1002      * [
1003      *   {
1004      *     name => $ds_name,
1005      *     type => $ds_type,
1006      *     min  => $ds_min,
1007      *     max  => $ds_max
1008      *   },
1009      *   ...
1010      * ];
1011      *
1012      * $_[2] =
1013      * {
1014      *   values => [ $v1, ... ],
1015      *   time   => $time,
1016      *   host   => $hostname,
1017      *   plugin => $plugin,
1018      *   type   => $type,
1019      *   plugin_instance => $instance,
1020      *   type_instance   => $type_instance
1021      * };
1022      */
1023     data_set_t *ds;
1024     value_list_t *vl;
1025
1026     AV *pds = newAV();
1027     HV *pvl = newHV();
1028
1029     ds = va_arg(ap, data_set_t *);
1030     vl = va_arg(ap, value_list_t *);
1031
1032     if (-1 == data_set2av(aTHX_ ds, pds)) {
1033       av_clear(pds);
1034       av_undef(pds);
1035       pds = (AV *)&PL_sv_undef;
1036       ret = -1;
1037     }
1038
1039     if (-1 == value_list2hv(aTHX_ vl, ds, pvl)) {
1040       hv_clear(pvl);
1041       hv_undef(pvl);
1042       pvl = (HV *)&PL_sv_undef;
1043       ret = -1;
1044     }
1045
1046     XPUSHs(sv_2mortal(newSVpv(ds->type, 0)));
1047     XPUSHs(sv_2mortal(newRV_noinc((SV *)pds)));
1048     XPUSHs(sv_2mortal(newRV_noinc((SV *)pvl)));
1049   } else if (PLUGIN_LOG == type) {
1050     /*
1051      * $_[0] = $level;
1052      *
1053      * $_[1] = $message;
1054      */
1055     XPUSHs(sv_2mortal(newSViv(va_arg(ap, int))));
1056     XPUSHs(sv_2mortal(newSVpv(va_arg(ap, char *), 0)));
1057   } else if (PLUGIN_NOTIF == type) {
1058     /*
1059      * $_[0] =
1060      * {
1061      *   severity => $severity,
1062      *   time     => $time,
1063      *   message  => $msg,
1064      *   host     => $host,
1065      *   plugin   => $plugin,
1066      *   type     => $type,
1067      *   plugin_instance => $instance,
1068      *   type_instance   => $type_instance
1069      * };
1070      */
1071     notification_t *n;
1072     HV *notif = newHV();
1073
1074     n = va_arg(ap, notification_t *);
1075
1076     if (-1 == notification2hv(aTHX_ n, notif)) {
1077       hv_clear(notif);
1078       hv_undef(notif);
1079       notif = (HV *)&PL_sv_undef;
1080       ret = -1;
1081     }
1082
1083     XPUSHs(sv_2mortal(newRV_noinc((SV *)notif)));
1084   } else if (PLUGIN_FLUSH == type) {
1085     cdtime_t timeout;
1086
1087     /*
1088      * $_[0] = $timeout;
1089      * $_[1] = $identifier;
1090      */
1091     timeout = va_arg(ap, cdtime_t);
1092
1093     XPUSHs(sv_2mortal(newSVnv(CDTIME_T_TO_DOUBLE(timeout))));
1094     XPUSHs(sv_2mortal(newSVpv(va_arg(ap, char *), 0)));
1095   }
1096
1097   PUTBACK;
1098
1099   retvals = call_pv_locked(aTHX_ "Collectd::plugin_call_all");
1100
1101   SPAGAIN;
1102   if (0 < retvals) {
1103     SV *tmp = POPs;
1104     if (!SvTRUE(tmp))
1105       ret = -1;
1106   }
1107
1108   PUTBACK;
1109   FREETMPS;
1110   LEAVE;
1111
1112   va_end(ap);
1113   return ret;
1114 } /* static int pplugin_call_all (int, ...) */
1115
1116 /*
1117  * collectd's Perl interpreter based thread implementation.
1118  *
1119  * This has been inspired by Perl's ithreads introduced in version 5.6.0.
1120  */
1121
1122 /* must be called with perl_threads->mutex locked */
1123 static void c_ithread_destroy(c_ithread_t *ithread) {
1124   dTHXa(ithread->interp);
1125
1126   assert(NULL != perl_threads);
1127
1128   PERL_SET_CONTEXT(aTHX);
1129   log_debug("Shutting down Perl interpreter %p...", aTHX);
1130
1131 #if COLLECT_DEBUG
1132   sv_report_used();
1133
1134   --perl_threads->number_of_threads;
1135 #endif /* COLLECT_DEBUG */
1136
1137   perl_destruct(aTHX);
1138   perl_free(aTHX);
1139
1140   if (NULL == ithread->prev)
1141     perl_threads->head = ithread->next;
1142   else
1143     ithread->prev->next = ithread->next;
1144
1145   if (NULL == ithread->next)
1146     perl_threads->tail = ithread->prev;
1147   else
1148     ithread->next->prev = ithread->prev;
1149
1150   sfree(ithread);
1151   return;
1152 } /* static void c_ithread_destroy (c_ithread_t *) */
1153
1154 static void c_ithread_destructor(void *arg) {
1155   c_ithread_t *ithread = (c_ithread_t *)arg;
1156   c_ithread_t *t = NULL;
1157
1158   if (NULL == perl_threads)
1159     return;
1160
1161   pthread_mutex_lock(&perl_threads->mutex);
1162
1163   for (t = perl_threads->head; NULL != t; t = t->next)
1164     if (t == ithread)
1165       break;
1166
1167   /* the ithread no longer exists */
1168   if (NULL == t) {
1169     pthread_mutex_unlock(&perl_threads->mutex);
1170     return;
1171   }
1172
1173   c_ithread_destroy(ithread);
1174
1175   pthread_mutex_unlock(&perl_threads->mutex);
1176   return;
1177 } /* static void c_ithread_destructor (void *) */
1178
1179 /* must be called with perl_threads->mutex locked */
1180 static c_ithread_t *c_ithread_create(PerlInterpreter *base) {
1181   c_ithread_t *t = NULL;
1182   dTHXa(NULL);
1183
1184   assert(NULL != perl_threads);
1185
1186   t = smalloc(sizeof(*t));
1187   memset(t, 0, sizeof(c_ithread_t));
1188
1189   t->interp = (NULL == base) ? NULL : perl_clone(base, CLONEf_KEEP_PTR_TABLE);
1190
1191   aTHX = t->interp;
1192
1193   if ((NULL != base) && (NULL != PL_endav)) {
1194     av_clear(PL_endav);
1195     av_undef(PL_endav);
1196     PL_endav = Nullav;
1197   }
1198
1199 #if COLLECT_DEBUG
1200   ++perl_threads->number_of_threads;
1201 #endif /* COLLECT_DEBUG */
1202
1203   t->next = NULL;
1204
1205   if (NULL == perl_threads->tail) {
1206     perl_threads->head = t;
1207     t->prev = NULL;
1208   } else {
1209     perl_threads->tail->next = t;
1210     t->prev = perl_threads->tail;
1211   }
1212
1213   t->pthread = pthread_self();
1214   t->running = 0;
1215   t->shutdown = 0;
1216   perl_threads->tail = t;
1217
1218   pthread_setspecific(perl_thr_key, (const void *)t);
1219   return t;
1220 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
1221
1222 /*
1223  * Filter chains implementation.
1224  */
1225
1226 static int fc_call(pTHX_ int type, int cb_type, pfc_user_data_t *data, ...) {
1227   int retvals = 0;
1228
1229   va_list ap;
1230   int ret = 0;
1231
1232   notification_meta_t **meta = NULL;
1233   AV *pmeta = NULL;
1234
1235   dSP;
1236
1237   if ((type < 0) || (type >= FC_TYPES))
1238     return -1;
1239
1240   if ((cb_type < 0) || (cb_type >= FC_CB_TYPES))
1241     return -1;
1242
1243   va_start(ap, data);
1244
1245   ENTER;
1246   SAVETMPS;
1247
1248   PUSHMARK(SP);
1249
1250   XPUSHs(sv_2mortal(newSViv((IV)type)));
1251   XPUSHs(sv_2mortal(newSVpv(data->name, 0)));
1252   XPUSHs(sv_2mortal(newSViv((IV)cb_type)));
1253
1254   if (FC_CB_CREATE == cb_type) {
1255     /*
1256      * $_[0] = $ci;
1257      * $_[1] = $user_data;
1258      */
1259     oconfig_item_t *ci;
1260     HV *config = newHV();
1261
1262     ci = va_arg(ap, oconfig_item_t *);
1263
1264     if (0 != oconfig_item2hv(aTHX_ ci, config)) {
1265       hv_clear(config);
1266       hv_undef(config);
1267       config = (HV *)&PL_sv_undef;
1268       ret = -1;
1269     }
1270
1271     XPUSHs(sv_2mortal(newRV_noinc((SV *)config)));
1272   } else if (FC_CB_DESTROY == cb_type) {
1273     /*
1274      * $_[1] = $user_data;
1275      */
1276
1277     /* nothing to be done - the user data pointer
1278      * is pushed onto the stack later */
1279   } else if (FC_CB_EXEC == cb_type) {
1280     /*
1281      * $_[0] = $ds;
1282      * $_[1] = $vl;
1283      * $_[2] = $meta;
1284      * $_[3] = $user_data;
1285      */
1286     data_set_t *ds;
1287     value_list_t *vl;
1288
1289     AV *pds = newAV();
1290     HV *pvl = newHV();
1291
1292     ds = va_arg(ap, data_set_t *);
1293     vl = va_arg(ap, value_list_t *);
1294     meta = va_arg(ap, notification_meta_t **);
1295
1296     if (0 != data_set2av(aTHX_ ds, pds)) {
1297       av_clear(pds);
1298       av_undef(pds);
1299       pds = (AV *)&PL_sv_undef;
1300       ret = -1;
1301     }
1302
1303     if (0 != value_list2hv(aTHX_ vl, ds, pvl)) {
1304       hv_clear(pvl);
1305       hv_undef(pvl);
1306       pvl = (HV *)&PL_sv_undef;
1307       ret = -1;
1308     }
1309
1310     if (NULL != meta) {
1311       pmeta = newAV();
1312
1313       if (0 != notification_meta2av(aTHX_ * meta, pmeta)) {
1314         av_clear(pmeta);
1315         av_undef(pmeta);
1316         pmeta = (AV *)&PL_sv_undef;
1317         ret = -1;
1318       }
1319     } else {
1320       pmeta = (AV *)&PL_sv_undef;
1321     }
1322
1323     XPUSHs(sv_2mortal(newRV_noinc((SV *)pds)));
1324     XPUSHs(sv_2mortal(newRV_noinc((SV *)pvl)));
1325     XPUSHs(sv_2mortal(newRV_noinc((SV *)pmeta)));
1326   }
1327
1328   XPUSHs(sv_2mortal(newRV_inc(data->user_data)));
1329
1330   PUTBACK;
1331
1332   retvals = call_pv_locked(aTHX_ "Collectd::fc_call");
1333
1334   if ((FC_CB_EXEC == cb_type) && (meta != NULL)) {
1335     assert(pmeta != NULL);
1336
1337     plugin_notification_meta_free(*meta);
1338     av2notification_meta(aTHX_ pmeta, meta);
1339   }
1340
1341   SPAGAIN;
1342   if (0 < retvals) {
1343     SV *tmp = POPs;
1344
1345     /* the exec callbacks return a status, while
1346      * the others return a boolean value */
1347     if (FC_CB_EXEC == cb_type)
1348       ret = SvIV(tmp);
1349     else if (!SvTRUE(tmp))
1350       ret = -1;
1351   }
1352
1353   PUTBACK;
1354   FREETMPS;
1355   LEAVE;
1356
1357   va_end(ap);
1358   return ret;
1359 } /* static int fc_call (int, int, pfc_user_data_t *, ...) */
1360
1361 static int fc_create(int type, const oconfig_item_t *ci, void **user_data) {
1362   pfc_user_data_t *data;
1363
1364   int ret = 0;
1365
1366   dTHX;
1367
1368   if (NULL == perl_threads)
1369     return 0;
1370
1371   if (NULL == aTHX) {
1372     c_ithread_t *t = NULL;
1373
1374     pthread_mutex_lock(&perl_threads->mutex);
1375     t = c_ithread_create(perl_threads->head->interp);
1376     pthread_mutex_unlock(&perl_threads->mutex);
1377
1378     aTHX = t->interp;
1379   }
1380
1381   log_debug("fc_create: c_ithread: interp = %p (active threads: %i)", aTHX,
1382             perl_threads->number_of_threads);
1383
1384   if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1385     log_warn("A \"%s\" block expects a single string argument.",
1386              (FC_MATCH == type) ? "Match" : "Target");
1387     return -1;
1388   }
1389
1390   data = smalloc(sizeof(*data));
1391   data->name = sstrdup(ci->values[0].value.string);
1392   data->user_data = newSV(0);
1393
1394   ret = fc_call(aTHX_ type, FC_CB_CREATE, data, ci);
1395
1396   if (0 != ret)
1397     PFC_USER_DATA_FREE(data);
1398   else
1399     *user_data = data;
1400   return ret;
1401 } /* static int fc_create (int, const oconfig_item_t *, void **) */
1402
1403 static int fc_destroy(int type, void **user_data) {
1404   pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1405
1406   int ret = 0;
1407
1408   dTHX;
1409
1410   if ((NULL == perl_threads) || (NULL == data))
1411     return 0;
1412
1413   if (NULL == aTHX) {
1414     c_ithread_t *t = NULL;
1415
1416     pthread_mutex_lock(&perl_threads->mutex);
1417     t = c_ithread_create(perl_threads->head->interp);
1418     pthread_mutex_unlock(&perl_threads->mutex);
1419
1420     aTHX = t->interp;
1421   }
1422
1423   log_debug("fc_destroy: c_ithread: interp = %p (active threads: %i)", aTHX,
1424             perl_threads->number_of_threads);
1425
1426   ret = fc_call(aTHX_ type, FC_CB_DESTROY, data);
1427
1428   PFC_USER_DATA_FREE(data);
1429   *user_data = NULL;
1430   return ret;
1431 } /* static int fc_destroy (int, void **) */
1432
1433 static int fc_exec(int type, const data_set_t *ds, const value_list_t *vl,
1434                    notification_meta_t **meta, void **user_data) {
1435   pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1436
1437   dTHX;
1438
1439   if (NULL == perl_threads)
1440     return 0;
1441
1442   assert(NULL != data);
1443
1444   if (NULL == aTHX) {
1445     c_ithread_t *t = NULL;
1446
1447     pthread_mutex_lock(&perl_threads->mutex);
1448     t = c_ithread_create(perl_threads->head->interp);
1449     pthread_mutex_unlock(&perl_threads->mutex);
1450
1451     aTHX = t->interp;
1452   }
1453
1454   log_debug("fc_exec: c_ithread: interp = %p (active threads: %i)", aTHX,
1455             perl_threads->number_of_threads);
1456
1457   return fc_call(aTHX_ type, FC_CB_EXEC, data, ds, vl, meta);
1458 } /* static int fc_exec (int, const data_set_t *, const value_list_t *,
1459                 notification_meta_t **, void **) */
1460
1461 static int pmatch_create(const oconfig_item_t *ci, void **user_data) {
1462   return fc_create(FC_MATCH, ci, user_data);
1463 } /* static int pmatch_create (const oconfig_item_t *, void **) */
1464
1465 static int pmatch_destroy(void **user_data) {
1466   return fc_destroy(FC_MATCH, user_data);
1467 } /* static int pmatch_destroy (void **) */
1468
1469 static int pmatch_match(const data_set_t *ds, const value_list_t *vl,
1470                         notification_meta_t **meta, void **user_data) {
1471   return fc_exec(FC_MATCH, ds, vl, meta, user_data);
1472 } /* static int pmatch_match (const data_set_t *, const value_list_t *,
1473                 notification_meta_t **, void **) */
1474
1475 static match_proc_t pmatch = {pmatch_create, pmatch_destroy, pmatch_match};
1476
1477 static int ptarget_create(const oconfig_item_t *ci, void **user_data) {
1478   return fc_create(FC_TARGET, ci, user_data);
1479 } /* static int ptarget_create (const oconfig_item_t *, void **) */
1480
1481 static int ptarget_destroy(void **user_data) {
1482   return fc_destroy(FC_TARGET, user_data);
1483 } /* static int ptarget_destroy (void **) */
1484
1485 static int ptarget_invoke(const data_set_t *ds, value_list_t *vl,
1486                           notification_meta_t **meta, void **user_data) {
1487   return fc_exec(FC_TARGET, ds, vl, meta, user_data);
1488 } /* static int ptarget_invoke (const data_set_t *, value_list_t *,
1489                 notification_meta_t **, void **) */
1490
1491 static target_proc_t ptarget = {ptarget_create, ptarget_destroy,
1492                                 ptarget_invoke};
1493
1494 /*
1495  * Exported Perl API.
1496  */
1497
1498 /*
1499  * Collectd::plugin_register_data_set (type, dataset).
1500  *
1501  * type:
1502  *   type of the dataset
1503  *
1504  * dataset:
1505  *   dataset to be registered
1506  */
1507 static XS(Collectd_plugin_register_ds) {
1508   SV *data = NULL;
1509   int ret = 0;
1510
1511   dXSARGS;
1512
1513   log_warn("Using plugin_register() to register new data-sets is "
1514            "deprecated - add new entries to a custom types.db instead.");
1515
1516   if (2 != items) {
1517     log_err("Usage: Collectd::plugin_register_data_set(type, dataset)");
1518     XSRETURN_EMPTY;
1519   }
1520
1521   log_debug("Collectd::plugin_register_data_set: "
1522             "type = \"%s\", dataset = \"%s\"",
1523             SvPV_nolen(ST(0)), SvPV_nolen(ST(1)));
1524
1525   data = ST(1);
1526
1527   if (SvROK(data) && (SVt_PVAV == SvTYPE(SvRV(data)))) {
1528     ret = pplugin_register_data_set(aTHX_ SvPV_nolen(ST(0)), (AV *)SvRV(data));
1529   } else {
1530     log_err("Collectd::plugin_register_data_set: Invalid data.");
1531     XSRETURN_EMPTY;
1532   }
1533
1534   if (0 == ret)
1535     XSRETURN_YES;
1536   else
1537     XSRETURN_EMPTY;
1538 } /* static XS (Collectd_plugin_register_ds) */
1539
1540 /*
1541  * Collectd::plugin_unregister_data_set (type).
1542  *
1543  * type:
1544  *   type of the dataset
1545  */
1546 static XS(Collectd_plugin_unregister_ds) {
1547   dXSARGS;
1548
1549   if (1 != items) {
1550     log_err("Usage: Collectd::plugin_unregister_data_set(type)");
1551     XSRETURN_EMPTY;
1552   }
1553
1554   log_debug("Collectd::plugin_unregister_data_set: type = \"%s\"",
1555             SvPV_nolen(ST(0)));
1556
1557   if (0 == pplugin_unregister_data_set(SvPV_nolen(ST(0))))
1558     XSRETURN_YES;
1559   else
1560     XSRETURN_EMPTY;
1561 } /* static XS (Collectd_plugin_register_ds) */
1562
1563 /*
1564  * Collectd::plugin_dispatch_values (name, values).
1565  *
1566  * name:
1567  *   name of the plugin
1568  *
1569  * values:
1570  *   value list to submit
1571  */
1572 static XS(Collectd_plugin_dispatch_values) {
1573   SV *values = NULL;
1574
1575   int ret = 0;
1576
1577   dXSARGS;
1578
1579   if (1 != items) {
1580     log_err("Usage: Collectd::plugin_dispatch_values(values)");
1581     XSRETURN_EMPTY;
1582   }
1583
1584   log_debug("Collectd::plugin_dispatch_values: values=\"%s\"",
1585             SvPV_nolen(ST(/* stack index = */ 0)));
1586
1587   values = ST(/* stack index = */ 0);
1588
1589   if (NULL == values)
1590     XSRETURN_EMPTY;
1591
1592   /* Make sure the argument is a hash reference. */
1593   if (!(SvROK(values) && (SVt_PVHV == SvTYPE(SvRV(values))))) {
1594     log_err("Collectd::plugin_dispatch_values: Invalid values.");
1595     XSRETURN_EMPTY;
1596   }
1597
1598   ret = pplugin_dispatch_values(aTHX_(HV *) SvRV(values));
1599
1600   if (0 == ret)
1601     XSRETURN_YES;
1602   else
1603     XSRETURN_EMPTY;
1604 } /* static XS (Collectd_plugin_dispatch_values) */
1605
1606 /*
1607  * Collectd::plugin_get_interval ().
1608  */
1609 static XS(Collectd_plugin_get_interval) {
1610   dXSARGS;
1611
1612   /* make sure we don't get any unused variable warnings for 'items';
1613    * don't abort, though */
1614   if (items)
1615     log_err("Usage: Collectd::plugin_get_interval()");
1616
1617   XSRETURN_NV((NV)CDTIME_T_TO_DOUBLE(plugin_get_interval()));
1618 } /* static XS (Collectd_plugin_get_interval) */
1619
1620 /* Collectd::plugin_write (plugin, ds, vl).
1621  *
1622  * plugin:
1623  *   name of the plugin to call, may be 'undef'
1624  *
1625  * ds:
1626  *   data-set that describes the submitted values, may be 'undef'
1627  *
1628  * vl:
1629  *   value-list to be written
1630  */
1631 static XS(Collectd__plugin_write) {
1632   char *plugin;
1633   SV *ds, *vl;
1634   AV *ds_array;
1635
1636   int ret;
1637
1638   dXSARGS;
1639
1640   if (3 != items) {
1641     log_err("Usage: Collectd::plugin_write(plugin, ds, vl)");
1642     XSRETURN_EMPTY;
1643   }
1644
1645   log_debug("Collectd::plugin_write: plugin=\"%s\", ds=\"%s\", vl=\"%s\"",
1646             SvPV_nolen(ST(0)), SvOK(ST(1)) ? SvPV_nolen(ST(1)) : "",
1647             SvPV_nolen(ST(2)));
1648
1649   if (!SvOK(ST(0)))
1650     plugin = NULL;
1651   else
1652     plugin = SvPV_nolen(ST(0));
1653
1654   ds = ST(1);
1655   if (SvROK(ds) && (SVt_PVAV == SvTYPE(SvRV(ds))))
1656     ds_array = (AV *)SvRV(ds);
1657   else if (!SvOK(ds))
1658     ds_array = NULL;
1659   else {
1660     log_err("Collectd::plugin_write: Invalid data-set.");
1661     XSRETURN_EMPTY;
1662   }
1663
1664   vl = ST(2);
1665   if (!(SvROK(vl) && (SVt_PVHV == SvTYPE(SvRV(vl))))) {
1666     log_err("Collectd::plugin_write: Invalid value-list.");
1667     XSRETURN_EMPTY;
1668   }
1669
1670   ret = pplugin_write(aTHX_ plugin, ds_array, (HV *)SvRV(vl));
1671
1672   if (0 == ret)
1673     XSRETURN_YES;
1674   else
1675     XSRETURN_EMPTY;
1676 } /* static XS (Collectd__plugin_write) */
1677
1678 /*
1679  * Collectd::_plugin_flush (plugin, timeout, identifier).
1680  *
1681  * plugin:
1682  *   name of the plugin to flush
1683  *
1684  * timeout:
1685  *   timeout to use when flushing the data
1686  *
1687  * identifier:
1688  *   data-set identifier to flush
1689  */
1690 static XS(Collectd__plugin_flush) {
1691   char *plugin = NULL;
1692   int timeout = -1;
1693   char *id = NULL;
1694
1695   dXSARGS;
1696
1697   if (3 != items) {
1698     log_err("Usage: Collectd::_plugin_flush(plugin, timeout, id)");
1699     XSRETURN_EMPTY;
1700   }
1701
1702   if (SvOK(ST(0)))
1703     plugin = SvPV_nolen(ST(0));
1704
1705   if (SvOK(ST(1)))
1706     timeout = (int)SvIV(ST(1));
1707
1708   if (SvOK(ST(2)))
1709     id = SvPV_nolen(ST(2));
1710
1711   log_debug("Collectd::_plugin_flush: plugin = \"%s\", timeout = %i, "
1712             "id = \"%s\"",
1713             plugin, timeout, id);
1714
1715   if (0 == plugin_flush(plugin, timeout, id))
1716     XSRETURN_YES;
1717   else
1718     XSRETURN_EMPTY;
1719 } /* static XS (Collectd__plugin_flush) */
1720
1721 /*
1722  * Collectd::plugin_dispatch_notification (notif).
1723  *
1724  * notif:
1725  *   notification to dispatch
1726  */
1727 static XS(Collectd_plugin_dispatch_notification) {
1728   SV *notif = NULL;
1729
1730   int ret = 0;
1731
1732   dXSARGS;
1733
1734   if (1 != items) {
1735     log_err("Usage: Collectd::plugin_dispatch_notification(notif)");
1736     XSRETURN_EMPTY;
1737   }
1738
1739   log_debug("Collectd::plugin_dispatch_notification: notif = \"%s\"",
1740             SvPV_nolen(ST(0)));
1741
1742   notif = ST(0);
1743
1744   if (!(SvROK(notif) && (SVt_PVHV == SvTYPE(SvRV(notif))))) {
1745     log_err("Collectd::plugin_dispatch_notification: Invalid notif.");
1746     XSRETURN_EMPTY;
1747   }
1748
1749   ret = pplugin_dispatch_notification(aTHX_(HV *) SvRV(notif));
1750
1751   if (0 == ret)
1752     XSRETURN_YES;
1753   else
1754     XSRETURN_EMPTY;
1755 } /* static XS (Collectd_plugin_dispatch_notification) */
1756
1757 /*
1758  * Collectd::plugin_log (level, message).
1759  *
1760  * level:
1761  *   log level (LOG_DEBUG, ... LOG_ERR)
1762  *
1763  * message:
1764  *   log message
1765  */
1766 static XS(Collectd_plugin_log) {
1767   dXSARGS;
1768
1769   if (2 != items) {
1770     log_err("Usage: Collectd::plugin_log(level, message)");
1771     XSRETURN_EMPTY;
1772   }
1773
1774   plugin_log(SvIV(ST(0)), "%s", SvPV_nolen(ST(1)));
1775   XSRETURN_YES;
1776 } /* static XS (Collectd_plugin_log) */
1777
1778 /*
1779  * Collectd::_fc_register (type, name)
1780  *
1781  * type:
1782  *   match | target
1783  *
1784  * name:
1785  *   name of the match
1786  */
1787 static XS(Collectd__fc_register) {
1788   int type;
1789   char *name;
1790
1791   int ret = 0;
1792
1793   dXSARGS;
1794
1795   if (2 != items) {
1796     log_err("Usage: Collectd::_fc_register(type, name)");
1797     XSRETURN_EMPTY;
1798   }
1799
1800   type = SvIV(ST(0));
1801   name = SvPV_nolen(ST(1));
1802
1803   if (FC_MATCH == type)
1804     ret = fc_register_match(name, pmatch);
1805   else if (FC_TARGET == type)
1806     ret = fc_register_target(name, ptarget);
1807
1808   if (0 == ret)
1809     XSRETURN_YES;
1810   else
1811     XSRETURN_EMPTY;
1812 } /* static XS (Collectd_fc_register) */
1813
1814 /*
1815  * Collectd::call_by_name (...).
1816  *
1817  * Call a Perl sub identified by its name passed through $Collectd::cb_name.
1818  */
1819 static XS(Collectd_call_by_name) {
1820   SV *tmp = NULL;
1821   char *name = NULL;
1822
1823   if (NULL == (tmp = get_sv("Collectd::cb_name", 0))) {
1824     sv_setpv(get_sv("@", 1), "cb_name has not been set");
1825     CLEAR_STACK_FRAME;
1826     return;
1827   }
1828
1829   name = SvPV_nolen(tmp);
1830
1831   if (NULL == get_cv(name, 0)) {
1832     sv_setpvf(get_sv("@", 1), "unknown callback \"%s\"", name);
1833     CLEAR_STACK_FRAME;
1834     return;
1835   }
1836
1837   /* simply pass on the subroutine call without touching the stack,
1838    * thus leaving any arguments and return values in place */
1839   call_pv(name, 0);
1840 } /* static XS (Collectd_call_by_name) */
1841
1842 /*
1843  * Interface to collectd.
1844  */
1845
1846 static int perl_init(void) {
1847   int status;
1848   dTHX;
1849
1850   if (NULL == perl_threads)
1851     return 0;
1852
1853   if (NULL == aTHX) {
1854     c_ithread_t *t = NULL;
1855
1856     pthread_mutex_lock(&perl_threads->mutex);
1857     t = c_ithread_create(perl_threads->head->interp);
1858     pthread_mutex_unlock(&perl_threads->mutex);
1859
1860     aTHX = t->interp;
1861   }
1862
1863   log_debug("perl_init: c_ithread: interp = %p (active threads: %i)", aTHX,
1864             perl_threads->number_of_threads);
1865
1866   /* Lock the base thread to avoid race conditions with c_ithread_create().
1867    * See https://github.com/collectd/collectd/issues/9 and
1868    *     https://github.com/collectd/collectd/issues/1706 for details.
1869   */
1870   assert(aTHX == perl_threads->head->interp);
1871   pthread_mutex_lock(&perl_threads->mutex);
1872
1873   status = pplugin_call_all(aTHX_ PLUGIN_INIT);
1874
1875   pthread_mutex_unlock(&perl_threads->mutex);
1876
1877   return status;
1878 } /* static int perl_init (void) */
1879
1880 static int perl_read(void) {
1881   dTHX;
1882
1883   if (NULL == perl_threads)
1884     return 0;
1885
1886   if (NULL == aTHX) {
1887     c_ithread_t *t = NULL;
1888
1889     pthread_mutex_lock(&perl_threads->mutex);
1890     t = c_ithread_create(perl_threads->head->interp);
1891     pthread_mutex_unlock(&perl_threads->mutex);
1892
1893     aTHX = t->interp;
1894   }
1895
1896   /* Assert that we're not running as the base thread. Otherwise, we might
1897    * run into concurrency issues with c_ithread_create(). See
1898    * https://github.com/collectd/collectd/issues/9 for details. */
1899   assert(aTHX != perl_threads->head->interp);
1900
1901   log_debug("perl_read: c_ithread: interp = %p (active threads: %i)", aTHX,
1902             perl_threads->number_of_threads);
1903   return pplugin_call_all(aTHX_ PLUGIN_READ);
1904 } /* static int perl_read (void) */
1905
1906 static int perl_write(const data_set_t *ds, const value_list_t *vl,
1907                       user_data_t __attribute__((unused)) * user_data) {
1908   int status;
1909   dTHX;
1910
1911   if (NULL == perl_threads)
1912     return 0;
1913
1914   if (NULL == aTHX) {
1915     c_ithread_t *t = NULL;
1916
1917     pthread_mutex_lock(&perl_threads->mutex);
1918     t = c_ithread_create(perl_threads->head->interp);
1919     pthread_mutex_unlock(&perl_threads->mutex);
1920
1921     aTHX = t->interp;
1922   }
1923
1924   /* Lock the base thread if this is not called from one of the read threads
1925    * to avoid race conditions with c_ithread_create(). See
1926    * https://github.com/collectd/collectd/issues/9 for details. */
1927   if (aTHX == perl_threads->head->interp)
1928     pthread_mutex_lock(&perl_threads->mutex);
1929
1930   log_debug("perl_write: c_ithread: interp = %p (active threads: %i)", aTHX,
1931             perl_threads->number_of_threads);
1932   status = pplugin_call_all(aTHX_ PLUGIN_WRITE, ds, vl);
1933
1934   if (aTHX == perl_threads->head->interp)
1935     pthread_mutex_unlock(&perl_threads->mutex);
1936
1937   return status;
1938 } /* static int perl_write (const data_set_t *, const value_list_t *) */
1939
1940 static void perl_log(int level, const char *msg,
1941                      user_data_t __attribute__((unused)) * user_data) {
1942   dTHX;
1943
1944   if (NULL == perl_threads)
1945     return;
1946
1947   if (NULL == aTHX) {
1948     c_ithread_t *t = NULL;
1949
1950     pthread_mutex_lock(&perl_threads->mutex);
1951     t = c_ithread_create(perl_threads->head->interp);
1952     pthread_mutex_unlock(&perl_threads->mutex);
1953
1954     aTHX = t->interp;
1955   }
1956
1957   /* Lock the base thread if this is not called from one of the read threads
1958    * to avoid race conditions with c_ithread_create(). See
1959    * https://github.com/collectd/collectd/issues/9 for details.
1960   */
1961
1962   if (aTHX == perl_threads->head->interp)
1963     pthread_mutex_lock(&perl_threads->mutex);
1964
1965   pplugin_call_all(aTHX_ PLUGIN_LOG, level, msg);
1966
1967   if (aTHX == perl_threads->head->interp)
1968     pthread_mutex_unlock(&perl_threads->mutex);
1969
1970   return;
1971 } /* static void perl_log (int, const char *) */
1972
1973 static int perl_notify(const notification_t *notif,
1974                        user_data_t __attribute__((unused)) * user_data) {
1975   dTHX;
1976
1977   if (NULL == perl_threads)
1978     return 0;
1979
1980   if (NULL == aTHX) {
1981     c_ithread_t *t = NULL;
1982
1983     pthread_mutex_lock(&perl_threads->mutex);
1984     t = c_ithread_create(perl_threads->head->interp);
1985     pthread_mutex_unlock(&perl_threads->mutex);
1986
1987     aTHX = t->interp;
1988   }
1989   return pplugin_call_all(aTHX_ PLUGIN_NOTIF, notif);
1990 } /* static int perl_notify (const notification_t *) */
1991
1992 static int perl_flush(cdtime_t timeout, const char *identifier,
1993                       user_data_t __attribute__((unused)) * user_data) {
1994   dTHX;
1995
1996   if (NULL == perl_threads)
1997     return 0;
1998
1999   if (NULL == aTHX) {
2000     c_ithread_t *t = NULL;
2001
2002     pthread_mutex_lock(&perl_threads->mutex);
2003     t = c_ithread_create(perl_threads->head->interp);
2004     pthread_mutex_unlock(&perl_threads->mutex);
2005
2006     aTHX = t->interp;
2007   }
2008   return pplugin_call_all(aTHX_ PLUGIN_FLUSH, timeout, identifier);
2009 } /* static int perl_flush (const int) */
2010
2011 static int perl_shutdown(void) {
2012   c_ithread_t *t;
2013   int ret;
2014
2015   dTHX;
2016
2017   plugin_unregister_complex_config("perl");
2018
2019   if (NULL == perl_threads)
2020     return 0;
2021
2022   if (NULL == aTHX) {
2023     pthread_mutex_lock(&perl_threads->mutex);
2024     t = c_ithread_create(perl_threads->head->interp);
2025     pthread_mutex_unlock(&perl_threads->mutex);
2026
2027     aTHX = t->interp;
2028   }
2029
2030   log_debug("perl_shutdown: c_ithread: interp = %p (active threads: %i)", aTHX,
2031             perl_threads->number_of_threads);
2032
2033   plugin_unregister_log("perl");
2034   plugin_unregister_notification("perl");
2035   plugin_unregister_init("perl");
2036   plugin_unregister_read("perl");
2037   plugin_unregister_write("perl");
2038   plugin_unregister_flush("perl");
2039
2040   ret = pplugin_call_all(aTHX_ PLUGIN_SHUTDOWN);
2041
2042   pthread_mutex_lock(&perl_threads->mutex);
2043   t = perl_threads->tail;
2044
2045   while (NULL != t) {
2046     struct timespec ts_wait;
2047     c_ithread_t *thr = t;
2048
2049     /* the pointer has to be advanced before destroying
2050      * the thread as this will free the memory */
2051     t = t->prev;
2052
2053     thr->shutdown = 1;
2054     if (thr->running) {
2055       /* Give some time to thread to exit from Perl interpreter */
2056       WARNING("perl shutdown: Thread is running inside Perl. Waiting.");
2057       ts_wait.tv_sec = 0;
2058       ts_wait.tv_nsec = 500000;
2059       nanosleep(&ts_wait, NULL);
2060     }
2061     if (thr->running) {
2062       pthread_kill(thr->pthread, SIGTERM);
2063       ERROR("perl shutdown: Thread hangs inside Perl. Thread killed.");
2064     }
2065     c_ithread_destroy(thr);
2066   }
2067
2068   pthread_mutex_unlock(&perl_threads->mutex);
2069   pthread_mutex_destroy(&perl_threads->mutex);
2070   pthread_mutexattr_destroy(&perl_threads->mutexattr);
2071
2072   sfree(perl_threads);
2073
2074   pthread_key_delete(perl_thr_key);
2075
2076   PERL_SYS_TERM();
2077
2078   plugin_unregister_shutdown("perl");
2079   return ret;
2080 } /* static void perl_shutdown (void) */
2081
2082 /*
2083  * Access functions for global variables.
2084  *
2085  * These functions implement the "magic" used to access
2086  * the global variables from Perl.
2087  */
2088
2089 static int g_pv_get(pTHX_ SV *var, MAGIC *mg) {
2090   char *pv = mg->mg_ptr;
2091   sv_setpv(var, pv);
2092   return 0;
2093 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
2094
2095 static int g_pv_set(pTHX_ SV *var, MAGIC *mg) {
2096   char *pv = mg->mg_ptr;
2097   sstrncpy(pv, SvPV_nolen(var), DATA_MAX_NAME_LEN);
2098   return 0;
2099 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
2100
2101 static int g_interval_get(pTHX_ SV *var, MAGIC *mg) {
2102   log_warn("Accessing $interval_g is deprecated (and might not "
2103            "give the desired results) - plugin_get_interval() should "
2104            "be used instead.");
2105   sv_setnv(var, CDTIME_T_TO_DOUBLE(interval_g));
2106   return 0;
2107 } /* static int g_interval_get (pTHX_ SV *, MAGIC *) */
2108
2109 static int g_interval_set(pTHX_ SV *var, MAGIC *mg) {
2110   double nv = (double)SvNV(var);
2111   log_warn("Accessing $interval_g is deprecated (and might not "
2112            "give the desired results) - plugin_get_interval() should "
2113            "be used instead.");
2114   interval_g = DOUBLE_TO_CDTIME_T(nv);
2115   return 0;
2116 } /* static int g_interval_set (pTHX_ SV *, MAGIC *) */
2117
2118 static MGVTBL g_pv_vtbl = {g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL
2119 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2120                            ,
2121                            NULL
2122 #endif
2123 };
2124 static MGVTBL g_interval_vtbl = {g_interval_get, g_interval_set, NULL, NULL,
2125                                  NULL, NULL, NULL
2126 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2127                                  ,
2128                                  NULL
2129 #endif
2130 };
2131
2132 /* bootstrap the Collectd module */
2133 static void xs_init(pTHX) {
2134   HV *stash = NULL;
2135   SV *tmp = NULL;
2136   char *file = __FILE__;
2137
2138   dXSUB_SYS;
2139
2140   /* enable usage of Perl modules using shared libraries */
2141   newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2142
2143   /* register API */
2144   for (int i = 0; NULL != api[i].f; ++i)
2145     newXS(api[i].name, api[i].f, file);
2146
2147   stash = gv_stashpv("Collectd", 1);
2148
2149   /* export "constants" */
2150   for (int i = 0; '\0' != constants[i].name[0]; ++i)
2151     newCONSTSUB(stash, constants[i].name, newSViv(constants[i].value));
2152
2153   /* export global variables
2154    * by adding "magic" to the SV's representing the globale variables
2155    * perl is able to automagically call the get/set function when
2156    * accessing any such variable (this is basically the same as using
2157    * tie() in Perl) */
2158   /* global strings */
2159   for (int i = 0; '\0' != g_strings[i].name[0]; ++i) {
2160     tmp = get_sv(g_strings[i].name, 1);
2161     sv_magicext(tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl, g_strings[i].var, 0);
2162   }
2163
2164   tmp = get_sv("Collectd::interval_g", /* create = */ 1);
2165   sv_magicext(tmp, NULL, /* how = */ PERL_MAGIC_ext,
2166               /* vtbl = */ &g_interval_vtbl,
2167               /* name = */ NULL, /* namelen = */ 0);
2168
2169   return;
2170 } /* static void xs_init (pTHX) */
2171
2172 /* Initialize the global Perl interpreter. */
2173 static int init_pi(int argc, char **argv) {
2174   dTHXa(NULL);
2175
2176   if (NULL != perl_threads)
2177     return 0;
2178
2179   log_info("Initializing Perl interpreter...");
2180 #if COLLECT_DEBUG
2181   {
2182     for (int i = 0; i < argc; ++i)
2183       log_debug("argv[%i] = \"%s\"", i, argv[i]);
2184   }
2185 #endif /* COLLECT_DEBUG */
2186
2187   if (0 != pthread_key_create(&perl_thr_key, c_ithread_destructor)) {
2188     log_err("init_pi: pthread_key_create failed");
2189
2190     /* this must not happen - cowardly giving up if it does */
2191     return -1;
2192   }
2193
2194 #ifdef __FreeBSD__
2195   /* On FreeBSD, PERL_SYS_INIT3 expands to some expression which
2196    * triggers a "value computed is not used" warning by gcc. */
2197   (void)
2198 #endif
2199       PERL_SYS_INIT3(&argc, &argv, &environ);
2200
2201   perl_threads = smalloc(sizeof(*perl_threads));
2202   memset(perl_threads, 0, sizeof(c_ithread_list_t));
2203
2204   pthread_mutexattr_init(&perl_threads->mutexattr);
2205   pthread_mutexattr_settype(&perl_threads->mutexattr, PTHREAD_MUTEX_RECURSIVE);
2206   pthread_mutex_init(&perl_threads->mutex, &perl_threads->mutexattr);
2207   /* locking the mutex should not be necessary at this point
2208    * but let's just do it for the sake of completeness */
2209   pthread_mutex_lock(&perl_threads->mutex);
2210
2211   perl_threads->head = c_ithread_create(NULL);
2212   perl_threads->tail = perl_threads->head;
2213
2214   if (NULL == (perl_threads->head->interp = perl_alloc())) {
2215     log_err("init_pi: Not enough memory.");
2216     exit(3);
2217   }
2218
2219   aTHX = perl_threads->head->interp;
2220   pthread_mutex_unlock(&perl_threads->mutex);
2221
2222   perl_construct(aTHX);
2223
2224   PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
2225
2226   if (0 != perl_parse(aTHX_ xs_init, argc, argv, NULL)) {
2227     SV *err = get_sv("@", 1);
2228     log_err("init_pi: Unable to bootstrap Collectd: %s", SvPV_nolen(err));
2229
2230     perl_destruct(perl_threads->head->interp);
2231     perl_free(perl_threads->head->interp);
2232     sfree(perl_threads);
2233
2234     pthread_key_delete(perl_thr_key);
2235     return -1;
2236   }
2237
2238   /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
2239   sv_setpv(get_sv("0", 0), "collectd");
2240
2241   perl_run(aTHX);
2242
2243   plugin_register_log("perl", perl_log, /* user_data = */ NULL);
2244   plugin_register_notification("perl", perl_notify,
2245                                /* user_data = */ NULL);
2246   plugin_register_init("perl", perl_init);
2247
2248   plugin_register_read("perl", perl_read);
2249
2250   plugin_register_write("perl", perl_write, /* user_data = */ NULL);
2251   plugin_register_flush("perl", perl_flush, /* user_data = */ NULL);
2252   plugin_register_shutdown("perl", perl_shutdown);
2253   return 0;
2254 } /* static int init_pi (const char **, const int) */
2255
2256 /*
2257  * LoadPlugin "<Plugin>"
2258  */
2259 static int perl_config_loadplugin(pTHX_ oconfig_item_t *ci) {
2260   char module_name[DATA_MAX_NAME_LEN];
2261
2262   char *value = NULL;
2263
2264   if ((0 != ci->children_num) || (1 != ci->values_num) ||
2265       (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2266     log_err("LoadPlugin expects a single string argument.");
2267     return 1;
2268   }
2269
2270   value = ci->values[0].value.string;
2271
2272   if (NULL == get_module_name(module_name, sizeof(module_name), value)) {
2273     log_err("Invalid module name %s", value);
2274     return (1);
2275   }
2276
2277   if (0 != init_pi(perl_argc, perl_argv))
2278     return -1;
2279
2280   assert(NULL != perl_threads);
2281   assert(NULL != perl_threads->head);
2282
2283   aTHX = perl_threads->head->interp;
2284
2285   log_debug("perl_config: Loading Perl plugin \"%s\"", value);
2286   load_module(PERL_LOADMOD_NOIMPORT, newSVpv(module_name, strlen(module_name)),
2287               Nullsv);
2288   return 0;
2289 } /* static int perl_config_loadplugin (oconfig_item_it *) */
2290
2291 /*
2292  * BaseName "<Name>"
2293  */
2294 static int perl_config_basename(pTHX_ oconfig_item_t *ci) {
2295   char *value = NULL;
2296
2297   if ((0 != ci->children_num) || (1 != ci->values_num) ||
2298       (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2299     log_err("BaseName expects a single string argument.");
2300     return 1;
2301   }
2302
2303   value = ci->values[0].value.string;
2304
2305   log_debug("perl_config: Setting plugin basename to \"%s\"", value);
2306   sstrncpy(base_name, value, sizeof(base_name));
2307   return 0;
2308 } /* static int perl_config_basename (oconfig_item_it *) */
2309
2310 /*
2311  * EnableDebugger "<Package>"|""
2312  */
2313 static int perl_config_enabledebugger(pTHX_ oconfig_item_t *ci) {
2314   char *value = NULL;
2315
2316   if ((0 != ci->children_num) || (1 != ci->values_num) ||
2317       (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2318     log_err("EnableDebugger expects a single string argument.");
2319     return 1;
2320   }
2321
2322   if (NULL != perl_threads) {
2323     log_warn("EnableDebugger has no effects if used after LoadPlugin.");
2324     return 1;
2325   }
2326
2327   value = ci->values[0].value.string;
2328
2329   perl_argv = realloc(perl_argv, (++perl_argc + 1) * sizeof(char *));
2330
2331   if (NULL == perl_argv) {
2332     log_err("perl_config: Not enough memory.");
2333     exit(3);
2334   }
2335
2336   if ('\0' == value[0]) {
2337     perl_argv[perl_argc - 1] = "-d";
2338   } else {
2339     perl_argv[perl_argc - 1] = smalloc(strlen(value) + 4);
2340     sstrncpy(perl_argv[perl_argc - 1], "-d:", 4);
2341     sstrncpy(perl_argv[perl_argc - 1] + 3, value, strlen(value) + 1);
2342   }
2343
2344   perl_argv[perl_argc] = NULL;
2345   return 0;
2346 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
2347
2348 /*
2349  * IncludeDir "<Dir>"
2350  */
2351 static int perl_config_includedir(pTHX_ oconfig_item_t *ci) {
2352   char *value = NULL;
2353
2354   if ((0 != ci->children_num) || (1 != ci->values_num) ||
2355       (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2356     log_err("IncludeDir expects a single string argument.");
2357     return 1;
2358   }
2359
2360   value = ci->values[0].value.string;
2361
2362   if (NULL == aTHX) {
2363     perl_argv = realloc(perl_argv, (++perl_argc + 1) * sizeof(char *));
2364
2365     if (NULL == perl_argv) {
2366       log_err("perl_config: Not enough memory.");
2367       exit(3);
2368     }
2369
2370     perl_argv[perl_argc - 1] = smalloc(strlen(value) + 3);
2371     sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
2372     sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen(value) + 1);
2373
2374     perl_argv[perl_argc] = NULL;
2375   } else {
2376     /* prepend the directory to @INC */
2377     av_unshift(GvAVn(PL_incgv), 1);
2378     av_store(GvAVn(PL_incgv), 0, newSVpv(value, strlen(value)));
2379   }
2380   return 0;
2381 } /* static int perl_config_includedir (oconfig_item_it *) */
2382
2383 /*
2384  * <Plugin> block
2385  */
2386 static int perl_config_plugin(pTHX_ oconfig_item_t *ci) {
2387   int retvals = 0;
2388   int ret = 0;
2389
2390   char *plugin;
2391   HV *config;
2392
2393   dSP;
2394
2395   if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2396     log_err("LoadPlugin expects a single string argument.");
2397     return 1;
2398   }
2399
2400   plugin = ci->values[0].value.string;
2401   config = newHV();
2402
2403   if (0 != oconfig_item2hv(aTHX_ ci, config)) {
2404     hv_clear(config);
2405     hv_undef(config);
2406
2407     log_err("Unable to convert configuration to a Perl hash value.");
2408     config = (HV *)&PL_sv_undef;
2409   }
2410
2411   ENTER;
2412   SAVETMPS;
2413
2414   PUSHMARK(SP);
2415
2416   XPUSHs(sv_2mortal(newSVpv(plugin, 0)));
2417   XPUSHs(sv_2mortal(newRV_noinc((SV *)config)));
2418
2419   PUTBACK;
2420
2421   retvals = call_pv("Collectd::_plugin_dispatch_config", G_SCALAR);
2422
2423   SPAGAIN;
2424   if (0 < retvals) {
2425     SV *tmp = POPs;
2426     if (!SvTRUE(tmp))
2427       ret = 1;
2428   } else
2429     ret = 1;
2430
2431   PUTBACK;
2432   FREETMPS;
2433   LEAVE;
2434   return ret;
2435 } /* static int perl_config_plugin (oconfig_item_it *) */
2436
2437 static int perl_config(oconfig_item_t *ci) {
2438   int status = 0;
2439
2440   dTHXa(NULL);
2441
2442   for (int i = 0; i < ci->children_num; ++i) {
2443     oconfig_item_t *c = ci->children + i;
2444     int current_status = 0;
2445
2446     if (NULL != perl_threads) {
2447       if ((aTHX = PERL_GET_CONTEXT) == NULL)
2448         return -1;
2449     }
2450
2451     if (0 == strcasecmp(c->key, "LoadPlugin"))
2452       current_status = perl_config_loadplugin(aTHX_ c);
2453     else if (0 == strcasecmp(c->key, "BaseName"))
2454       current_status = perl_config_basename(aTHX_ c);
2455     else if (0 == strcasecmp(c->key, "EnableDebugger"))
2456       current_status = perl_config_enabledebugger(aTHX_ c);
2457     else if (0 == strcasecmp(c->key, "IncludeDir"))
2458       current_status = perl_config_includedir(aTHX_ c);
2459     else if (0 == strcasecmp(c->key, "Plugin"))
2460       current_status = perl_config_plugin(aTHX_ c);
2461     else {
2462       log_warn("Ignoring unknown config key \"%s\".", c->key);
2463       current_status = 0;
2464     }
2465
2466     /* fatal error - it's up to perl_config_* to clean up */
2467     if (0 > current_status) {
2468       log_err("Configuration failed with a fatal error - "
2469               "plugin disabled!");
2470       return current_status;
2471     }
2472
2473     status += current_status;
2474   }
2475   return status;
2476 } /* static int perl_config (oconfig_item_t *) */
2477
2478 void module_register(void) {
2479   perl_argc = 4;
2480   perl_argv = smalloc((perl_argc + 1) * sizeof(*perl_argv));
2481
2482   /* default options for the Perl interpreter */
2483   perl_argv[0] = "";
2484   perl_argv[1] = "-MCollectd";
2485   perl_argv[2] = "-e";
2486   perl_argv[3] = "1";
2487   perl_argv[4] = NULL;
2488
2489   plugin_register_complex_config("perl", perl_config);
2490   return;
2491 } /* void module_register (void) */
2492
2493 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */