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