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