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