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