2 * collectd - src/perl.c
3 * Copyright (C) 2007-2009 Sebastian Harl
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:
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
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.
24 * Sebastian Harl <sh at tokkee.org>
28 * This plugin embeds a Perl interpreter into collectd and provides an
29 * interface for collectd plugins written in perl.
32 /* do not automatically get the thread specific Perl interpreter */
33 #define PERL_NO_GET_CONTEXT
35 #define DONT_POISON_SPRINTF_YET 1
37 #undef DONT_POISON_SPRINTF_YET
39 #include "configfile.h"
48 #if defined(COLLECT_DEBUG) && COLLECT_DEBUG && defined(__GNUC__) && __GNUC__
50 # pragma GCC poison sprintf
55 /* Some versions of Perl define their own version of DEBUG... :-/ */
60 /* ... while we want the definition found in plugin.h. */
64 #include "filter_chain.h"
66 #if !defined(USE_ITHREADS)
67 # error "Perl does not support ithreads!"
68 #endif /* !defined(USE_ITHREADS) */
70 /* clear the Perl sub's stack frame
71 * (this should only be used inside an XSUB) */
72 #define CLEAR_STACK_FRAME PL_stack_sp = PL_stack_base + *PL_markstack_ptr
76 #define PLUGIN_WRITE 2
77 #define PLUGIN_SHUTDOWN 3
79 #define PLUGIN_NOTIF 5
80 #define PLUGIN_FLUSH 6
82 #define PLUGIN_TYPES 7
84 #define PLUGIN_CONFIG 254
85 #define PLUGIN_DATASET 255
92 #define FC_CB_CREATE 0
93 #define FC_CB_DESTROY 1
98 #define log_debug(...) DEBUG ("perl: " __VA_ARGS__)
99 #define log_info(...) INFO ("perl: " __VA_ARGS__)
100 #define log_warn(...) WARNING ("perl: " __VA_ARGS__)
101 #define log_err(...) ERROR ("perl: " __VA_ARGS__)
103 /* this is defined in DynaLoader.a */
104 void boot_DynaLoader (PerlInterpreter *, CV *);
106 static XS (Collectd_plugin_register_ds);
107 static XS (Collectd_plugin_unregister_ds);
108 static XS (Collectd_plugin_dispatch_values);
109 static XS (Collectd_plugin_get_interval);
110 static XS (Collectd__plugin_write);
111 static XS (Collectd__plugin_flush);
112 static XS (Collectd_plugin_dispatch_notification);
113 static XS (Collectd_plugin_log);
114 static XS (Collectd__fc_register);
115 static XS (Collectd_call_by_name);
121 typedef struct c_ithread_s {
122 /* the thread's Perl interpreter */
123 PerlInterpreter *interp;
124 _Bool running; /* thread is inside Perl interpreter */
128 /* double linked list of threads */
129 struct c_ithread_s *prev;
130 struct c_ithread_s *next;
138 /* some usage stats */
139 int number_of_threads;
140 #endif /* COLLECT_DEBUG */
142 pthread_mutex_t mutex;
143 pthread_mutexattr_t mutexattr;
146 /* name / user_data for Perl matches / targets */
152 #define PFC_USER_DATA_FREE(data) \
154 sfree ((data)->name); \
155 if (NULL != (data)->user_data) \
156 sv_free ((data)->user_data); \
163 extern char **environ;
169 /* if perl_threads != NULL perl_threads->head must
170 * point to the "base" thread */
171 static c_ithread_list_t *perl_threads = NULL;
173 /* the key used to store each pthread's ithread */
174 static pthread_key_t perl_thr_key;
176 static int perl_argc = 0;
177 static char **perl_argv = NULL;
179 static char base_name[DATA_MAX_NAME_LEN] = "";
186 { "Collectd::plugin_register_data_set", Collectd_plugin_register_ds },
187 { "Collectd::plugin_unregister_data_set", Collectd_plugin_unregister_ds },
188 { "Collectd::plugin_dispatch_values", Collectd_plugin_dispatch_values },
189 { "Collectd::plugin_get_interval", Collectd_plugin_get_interval },
190 { "Collectd::_plugin_write", Collectd__plugin_write },
191 { "Collectd::_plugin_flush", Collectd__plugin_flush },
192 { "Collectd::plugin_dispatch_notification",
193 Collectd_plugin_dispatch_notification },
194 { "Collectd::plugin_log", Collectd_plugin_log },
195 { "Collectd::_fc_register", Collectd__fc_register },
196 { "Collectd::call_by_name", Collectd_call_by_name },
205 { "Collectd::TYPE_INIT", PLUGIN_INIT },
206 { "Collectd::TYPE_READ", PLUGIN_READ },
207 { "Collectd::TYPE_WRITE", PLUGIN_WRITE },
208 { "Collectd::TYPE_SHUTDOWN", PLUGIN_SHUTDOWN },
209 { "Collectd::TYPE_LOG", PLUGIN_LOG },
210 { "Collectd::TYPE_NOTIF", PLUGIN_NOTIF },
211 { "Collectd::TYPE_FLUSH", PLUGIN_FLUSH },
212 { "Collectd::TYPE_CONFIG", PLUGIN_CONFIG },
213 { "Collectd::TYPE_DATASET", PLUGIN_DATASET },
214 { "Collectd::DS_TYPE_COUNTER", DS_TYPE_COUNTER },
215 { "Collectd::DS_TYPE_GAUGE", DS_TYPE_GAUGE },
216 { "Collectd::DS_TYPE_DERIVE", DS_TYPE_DERIVE },
217 { "Collectd::DS_TYPE_ABSOLUTE", DS_TYPE_ABSOLUTE },
218 { "Collectd::LOG_ERR", LOG_ERR },
219 { "Collectd::LOG_WARNING", LOG_WARNING },
220 { "Collectd::LOG_NOTICE", LOG_NOTICE },
221 { "Collectd::LOG_INFO", LOG_INFO },
222 { "Collectd::LOG_DEBUG", LOG_DEBUG },
223 { "Collectd::FC_MATCH", FC_MATCH },
224 { "Collectd::FC_TARGET", FC_TARGET },
225 { "Collectd::FC_CB_CREATE", FC_CB_CREATE },
226 { "Collectd::FC_CB_DESTROY", FC_CB_DESTROY },
227 { "Collectd::FC_CB_EXEC", FC_CB_EXEC },
228 { "Collectd::FC_MATCH_NO_MATCH", FC_MATCH_NO_MATCH },
229 { "Collectd::FC_MATCH_MATCHES", FC_MATCH_MATCHES },
230 { "Collectd::FC_TARGET_CONTINUE", FC_TARGET_CONTINUE },
231 { "Collectd::FC_TARGET_STOP", FC_TARGET_STOP },
232 { "Collectd::FC_TARGET_RETURN", FC_TARGET_RETURN },
233 { "Collectd::NOTIF_FAILURE", NOTIF_FAILURE },
234 { "Collectd::NOTIF_WARNING", NOTIF_WARNING },
235 { "Collectd::NOTIF_OKAY", NOTIF_OKAY },
244 { "Collectd::hostname_g", hostname_g },
249 * Helper functions for data type conversion.
264 static int hv2data_source (pTHX_ HV *hash, data_source_t *ds)
268 if ((NULL == hash) || (NULL == ds))
271 if (NULL != (tmp = hv_fetch (hash, "name", 4, 0))) {
272 sstrncpy (ds->name, SvPV_nolen (*tmp), sizeof (ds->name));
275 log_err ("hv2data_source: No DS name given.");
279 if (NULL != (tmp = hv_fetch (hash, "type", 4, 0))) {
280 ds->type = SvIV (*tmp);
282 if ((DS_TYPE_COUNTER != ds->type)
283 && (DS_TYPE_GAUGE != ds->type)
284 && (DS_TYPE_DERIVE != ds->type)
285 && (DS_TYPE_ABSOLUTE != ds->type)) {
286 log_err ("hv2data_source: Invalid DS type.");
291 ds->type = DS_TYPE_COUNTER;
294 if (NULL != (tmp = hv_fetch (hash, "min", 3, 0)))
295 ds->min = SvNV (*tmp);
299 if (NULL != (tmp = hv_fetch (hash, "max", 3, 0)))
300 ds->max = SvNV (*tmp);
304 } /* static int hv2data_source (HV *, data_source_t *) */
306 /* av2value converts at most "len" elements from "array" to "value". Returns the
307 * number of elements converted or zero on error. */
308 static size_t av2value (pTHX_ char *name, AV *array, value_t *value, size_t array_len)
310 const data_set_t *ds;
313 if ((NULL == name) || (NULL == array) || (NULL == value) || (array_len == 0))
316 ds = plugin_get_ds (name);
318 log_err ("av2value: Unknown dataset \"%s\"", name);
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);
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);
331 for (i = 0; i < ds->ds_num; ++i) {
332 SV **tmp = av_fetch (array, i, 0);
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);
350 } /* static size_t av2value (char *, AV *, value_t *, size_t) */
355 * values => [ @values ],
359 * plugin_instance => $pinstance,
360 * type_instance => $tinstance,
363 static int hv2value_list (pTHX_ HV *hash, value_list_t *vl)
367 if ((NULL == hash) || (NULL == vl))
370 if (NULL == (tmp = hv_fetch (hash, "type", 4, 0))) {
371 log_err ("hv2value_list: No type given.");
375 sstrncpy (vl->type, SvPV_nolen (*tmp), sizeof (vl->type));
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.");
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);
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) {
398 if (NULL != (tmp = hv_fetch (hash, "time", 4, 0)))
400 double t = SvNV (*tmp);
401 vl->time = DOUBLE_TO_CDTIME_T (t);
404 if (NULL != (tmp = hv_fetch (hash, "interval", 8, 0)))
406 double t = SvNV (*tmp);
407 vl->interval = DOUBLE_TO_CDTIME_T (t);
410 if (NULL != (tmp = hv_fetch (hash, "host", 4, 0)))
411 sstrncpy (vl->host, SvPV_nolen (*tmp), sizeof (vl->host));
413 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
415 if (NULL != (tmp = hv_fetch (hash, "plugin", 6, 0)))
416 sstrncpy (vl->plugin, SvPV_nolen (*tmp), sizeof (vl->plugin));
418 if (NULL != (tmp = hv_fetch (hash, "plugin_instance", 15, 0)))
419 sstrncpy (vl->plugin_instance, SvPV_nolen (*tmp),
420 sizeof (vl->plugin_instance));
422 if (NULL != (tmp = hv_fetch (hash, "type_instance", 13, 0)))
423 sstrncpy (vl->type_instance, SvPV_nolen (*tmp),
424 sizeof (vl->type_instance));
426 } /* static int hv2value_list (pTHX_ HV *, value_list_t *) */
428 static int av2data_set (pTHX_ AV *array, char *name, data_set_t *ds)
432 if ((NULL == array) || (NULL == name) || (NULL == ds))
435 len = av_len (array);
438 log_err ("av2data_set: Invalid data set.");
442 ds->ds = smalloc ((len + 1) * sizeof (*ds->ds));
443 ds->ds_num = len + 1;
445 for (i = 0; i <= len; ++i) {
446 SV **elem = av_fetch (array, i, 0);
449 log_err ("av2data_set: Failed to fetch data source %i.", i);
453 if (! (SvROK (*elem) && (SVt_PVHV == SvTYPE (SvRV (*elem))))) {
454 log_err ("av2data_set: Invalid data source.");
458 if (-1 == hv2data_source (aTHX_ (HV *)SvRV (*elem), &ds->ds[i]))
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);
466 sstrncpy (ds->type, name, sizeof (ds->type));
468 } /* static int av2data_set (pTHX_ AV *, data_set_t *) */
473 * severity => $severity,
479 * plugin_instance => $instance,
480 * type_instance => $type_instance,
481 * meta => [ { name => <name>, value => <value> }, ... ]
484 static int av2notification_meta (pTHX_ AV *array, notification_meta_t **meta)
486 notification_meta_t **m = meta;
488 int len = av_len (array);
491 for (i = 0; i <= len; ++i) {
492 SV **tmp = av_fetch (array, i, 0);
498 if (! (SvROK (*tmp) && (SVt_PVHV == SvTYPE (SvRV (*tmp))))) {
499 log_warn ("av2notification_meta: Skipping invalid "
500 "meta information.");
504 hash = (HV *)SvRV (*tmp);
506 *m = smalloc (sizeof (**m));
508 if (NULL == (tmp = hv_fetch (hash, "name", 4, 0))) {
509 log_warn ("av2notification_meta: Skipping invalid "
510 "meta information.");
514 sstrncpy ((*m)->name, SvPV_nolen (*tmp), sizeof ((*m)->name));
516 if (NULL == (tmp = hv_fetch (hash, "value", 5, 0))) {
517 log_warn ("av2notification_meta: Skipping invalid "
518 "meta information.");
524 (*m)->nm_value.nm_double = SvNVX (*tmp);
525 (*m)->type = NM_TYPE_DOUBLE;
527 else if (SvUOK (*tmp)) {
528 (*m)->nm_value.nm_unsigned_int = SvUVX (*tmp);
529 (*m)->type = NM_TYPE_UNSIGNED_INT;
531 else if (SvIOK (*tmp)) {
532 (*m)->nm_value.nm_signed_int = SvIVX (*tmp);
533 (*m)->type = NM_TYPE_SIGNED_INT;
536 (*m)->nm_value.nm_string = sstrdup (SvPV_nolen (*tmp));
537 (*m)->type = NM_TYPE_STRING;
544 } /* static int av2notification_meta (AV *, notification_meta_t *) */
546 static int hv2notification (pTHX_ HV *hash, notification_t *n)
550 if ((NULL == hash) || (NULL == n))
553 if (NULL != (tmp = hv_fetch (hash, "severity", 8, 0)))
554 n->severity = SvIV (*tmp);
556 n->severity = NOTIF_FAILURE;
558 if (NULL != (tmp = hv_fetch (hash, "time", 4, 0)))
560 double t = SvNV (*tmp);
561 n->time = DOUBLE_TO_CDTIME_T (t);
566 if (NULL != (tmp = hv_fetch (hash, "message", 7, 0)))
567 sstrncpy (n->message, SvPV_nolen (*tmp), sizeof (n->message));
569 if (NULL != (tmp = hv_fetch (hash, "host", 4, 0)))
570 sstrncpy (n->host, SvPV_nolen (*tmp), sizeof (n->host));
572 sstrncpy (n->host, hostname_g, sizeof (n->host));
574 if (NULL != (tmp = hv_fetch (hash, "plugin", 6, 0)))
575 sstrncpy (n->plugin, SvPV_nolen (*tmp), sizeof (n->plugin));
577 if (NULL != (tmp = hv_fetch (hash, "plugin_instance", 15, 0)))
578 sstrncpy (n->plugin_instance, SvPV_nolen (*tmp),
579 sizeof (n->plugin_instance));
581 if (NULL != (tmp = hv_fetch (hash, "type", 4, 0)))
582 sstrncpy (n->type, SvPV_nolen (*tmp), sizeof (n->type));
584 if (NULL != (tmp = hv_fetch (hash, "type_instance", 13, 0)))
585 sstrncpy (n->type_instance, SvPV_nolen (*tmp),
586 sizeof (n->type_instance));
589 while (NULL != (tmp = hv_fetch (hash, "meta", 4, 0))) {
590 if (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp))))) {
591 log_warn ("hv2notification: Ignoring invalid meta information.");
595 if (0 != av2notification_meta (aTHX_ (AV *)SvRV (*tmp), &n->meta)) {
596 plugin_notification_meta_free (n->meta);
603 } /* static int hv2notification (pTHX_ HV *, notification_t *) */
605 static int data_set2av (pTHX_ data_set_t *ds, AV *array)
609 if ((NULL == ds) || (NULL == array))
612 av_extend (array, ds->ds_num);
614 for (i = 0; i < ds->ds_num; ++i) {
615 HV *source = newHV ();
617 if (NULL == hv_store (source, "name", 4,
618 newSVpv (ds->ds[i].name, 0), 0))
621 if (NULL == hv_store (source, "type", 4, newSViv (ds->ds[i].type), 0))
624 if (! isnan (ds->ds[i].min))
625 if (NULL == hv_store (source, "min", 3,
626 newSVnv (ds->ds[i].min), 0))
629 if (! isnan (ds->ds[i].max))
630 if (NULL == hv_store (source, "max", 3,
631 newSVnv (ds->ds[i].max), 0))
634 if (NULL == av_store (array, i, newRV_noinc ((SV *)source)))
638 } /* static int data_set2av (data_set_t *, AV *) */
640 static int value_list2hv (pTHX_ value_list_t *vl, data_set_t *ds, HV *hash)
645 if ((NULL == vl) || (NULL == ds) || (NULL == hash))
649 /* av_extend takes the last *index* to which the array should be extended. */
650 av_extend (values, vl->values_len - 1);
652 assert (ds->ds_num == vl->values_len);
653 for (i = 0; i < vl->values_len; ++i) {
656 if (DS_TYPE_COUNTER == ds->ds[i].type)
657 val = newSViv (vl->values[i].counter);
658 else if (DS_TYPE_GAUGE == ds->ds[i].type)
659 val = newSVnv (vl->values[i].gauge);
660 else if (DS_TYPE_DERIVE == ds->ds[i].type)
661 val = newSViv (vl->values[i].derive);
662 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
663 val = newSViv (vl->values[i].absolute);
665 if (NULL == av_store (values, i, val)) {
671 if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0))
676 double t = CDTIME_T_TO_DOUBLE (vl->time);
677 if (NULL == hv_store (hash, "time", 4, newSVnv (t), 0))
682 double t = CDTIME_T_TO_DOUBLE (vl->interval);
683 if (NULL == hv_store (hash, "interval", 8, newSVnv (t), 0))
687 if ('\0' != vl->host[0])
688 if (NULL == hv_store (hash, "host", 4, newSVpv (vl->host, 0), 0))
691 if ('\0' != vl->plugin[0])
692 if (NULL == hv_store (hash, "plugin", 6, newSVpv (vl->plugin, 0), 0))
695 if ('\0' != vl->plugin_instance[0])
696 if (NULL == hv_store (hash, "plugin_instance", 15,
697 newSVpv (vl->plugin_instance, 0), 0))
700 if ('\0' != vl->type[0])
701 if (NULL == hv_store (hash, "type", 4, newSVpv (vl->type, 0), 0))
704 if ('\0' != vl->type_instance[0])
705 if (NULL == hv_store (hash, "type_instance", 13,
706 newSVpv (vl->type_instance, 0), 0))
709 } /* static int value2av (value_list_t *, data_set_t *, HV *) */
711 static int notification_meta2av (pTHX_ notification_meta_t *meta, AV *array)
721 av_extend (array, meta_num);
723 for (i = 0; NULL != meta; meta = meta->next, ++i) {
727 if (NULL == hv_store (m, "name", 4, newSVpv (meta->name, 0), 0))
730 if (NM_TYPE_STRING == meta->type)
731 value = newSVpv (meta->nm_value.nm_string, 0);
732 else if (NM_TYPE_SIGNED_INT == meta->type)
733 value = newSViv (meta->nm_value.nm_signed_int);
734 else if (NM_TYPE_UNSIGNED_INT == meta->type)
735 value = newSVuv (meta->nm_value.nm_unsigned_int);
736 else if (NM_TYPE_DOUBLE == meta->type)
737 value = newSVnv (meta->nm_value.nm_double);
738 else if (NM_TYPE_BOOLEAN == meta->type)
739 value = meta->nm_value.nm_boolean ? &PL_sv_yes : &PL_sv_no;
743 if (NULL == hv_store (m, "value", 5, value, 0)) {
748 if (NULL == av_store (array, i, newRV_noinc ((SV *)m))) {
755 } /* static int notification_meta2av (notification_meta_t *, AV *) */
757 static int notification2hv (pTHX_ notification_t *n, HV *hash)
759 if (NULL == hv_store (hash, "severity", 8, newSViv (n->severity), 0))
764 double t = CDTIME_T_TO_DOUBLE (n->time);
765 if (NULL == hv_store (hash, "time", 4, newSVnv (t), 0))
769 if ('\0' != *n->message)
770 if (NULL == hv_store (hash, "message", 7, newSVpv (n->message, 0), 0))
773 if ('\0' != *n->host)
774 if (NULL == hv_store (hash, "host", 4, newSVpv (n->host, 0), 0))
777 if ('\0' != *n->plugin)
778 if (NULL == hv_store (hash, "plugin", 6, newSVpv (n->plugin, 0), 0))
781 if ('\0' != *n->plugin_instance)
782 if (NULL == hv_store (hash, "plugin_instance", 15,
783 newSVpv (n->plugin_instance, 0), 0))
786 if ('\0' != *n->type)
787 if (NULL == hv_store (hash, "type", 4, newSVpv (n->type, 0), 0))
790 if ('\0' != *n->type_instance)
791 if (NULL == hv_store (hash, "type_instance", 13,
792 newSVpv (n->type_instance, 0), 0))
795 if (NULL != n->meta) {
797 if ((0 != notification_meta2av (aTHX_ n->meta, meta))
798 || (NULL == hv_store (hash, "meta", 4,
799 newRV_noinc ((SV *)meta), 0))) {
806 } /* static int notification2hv (notification_t *, HV *) */
808 static int oconfig_item2hv (pTHX_ oconfig_item_t *ci, HV *hash)
815 if (NULL == hv_store (hash, "key", 3, newSVpv (ci->key, 0), 0))
819 if (0 < ci->values_num)
820 av_extend (values, ci->values_num);
822 if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0)) {
828 for (i = 0; i < ci->values_num; ++i) {
831 switch (ci->values[i].type) {
832 case OCONFIG_TYPE_STRING:
833 value = newSVpv (ci->values[i].value.string, 0);
835 case OCONFIG_TYPE_NUMBER:
836 value = newSVnv ((NV)ci->values[i].value.number);
838 case OCONFIG_TYPE_BOOLEAN:
839 value = ci->values[i].value.boolean ? &PL_sv_yes : &PL_sv_no;
842 log_err ("oconfig_item2hv: Invalid value type %i.",
844 value = &PL_sv_undef;
847 if (NULL == av_store (values, i, value)) {
853 /* ignoring 'parent' member which is uninteresting in this case */
856 if (0 < ci->children_num)
857 av_extend (children, ci->children_num);
859 if (NULL == hv_store (hash, "children", 8, newRV_noinc ((SV *)children), 0)) {
865 for (i = 0; i < ci->children_num; ++i) {
866 HV *child = newHV ();
868 if (0 != oconfig_item2hv (aTHX_ ci->children + i, child)) {
874 if (NULL == av_store (children, i, newRV_noinc ((SV *)child))) {
881 } /* static int oconfig_item2hv (pTHX_ oconfig_item_t *, HV *) */
884 * Internal functions.
887 static char *get_module_name (char *buf, size_t buf_len, const char *module) {
889 if (base_name[0] == '\0')
890 status = ssnprintf (buf, buf_len, "%s", module);
892 status = ssnprintf (buf, buf_len, "%s::%s", base_name, module);
893 if ((status < 0) || ((unsigned int)status >= buf_len))
896 } /* char *get_module_name */
899 * Add a plugin's data set definition.
901 static int pplugin_register_data_set (pTHX_ char *name, AV *dataset)
907 if ((NULL == name) || (NULL == dataset))
910 if (0 != av2data_set (aTHX_ dataset, name, &ds))
913 ret = plugin_register_data_set (&ds);
917 } /* static int pplugin_register_data_set (char *, SV *) */
920 * Remove a plugin's data set definition.
922 static int pplugin_unregister_data_set (char *name)
926 return plugin_unregister_data_set (name);
927 } /* static int pplugin_unregister_data_set (char *) */
930 * Submit the values to the write functions.
932 static int pplugin_dispatch_values (pTHX_ HV *values)
934 value_list_t vl = VALUE_LIST_INIT;
941 if (0 != hv2value_list (aTHX_ values, &vl))
944 ret = plugin_dispatch_values (&vl);
948 } /* static int pplugin_dispatch_values (char *, HV *) */
951 * Submit the values to a single write function.
953 static int pplugin_write (pTHX_ const char *plugin, AV *data_set, HV *values)
956 value_list_t vl = VALUE_LIST_INIT;
963 if (0 != hv2value_list (aTHX_ values, &vl))
966 if ((NULL != data_set)
967 && (0 != av2data_set (aTHX_ data_set, vl.type, &ds)))
970 ret = plugin_write (plugin, NULL == data_set ? NULL : &ds, &vl);
972 log_warn ("Dispatching value to plugin \"%s\" failed with status %i.",
973 NULL == plugin ? "<any>" : plugin, ret);
975 if (NULL != data_set)
979 } /* static int pplugin_write (const char *plugin, HV *, HV *) */
982 * Dispatch a notification.
984 static int pplugin_dispatch_notification (pTHX_ HV *notif)
986 notification_t n = { 0 };
993 if (0 != hv2notification (aTHX_ notif, &n))
996 ret = plugin_dispatch_notification (&n);
997 plugin_notification_meta_free (n.meta);
999 } /* static int pplugin_dispatch_notification (HV *) */
1002 * Call perl sub with thread locking flags handled.
1004 static int call_pv_locked (pTHX_ const char* sub_name)
1009 c_ithread_t *t = (c_ithread_t *)pthread_getspecific(perl_thr_key);
1010 if (t == NULL) /* thread destroyed */
1013 old_running = t->running;
1017 t->running = old_running;
1021 ret = call_pv (sub_name, G_SCALAR);
1023 t->running = old_running;
1025 } /* static int call_pv_locked (pTHX, *sub_name) */
1028 * Call all working functions of the given type.
1030 static int pplugin_call_all (pTHX_ int type, ...)
1039 if ((type < 0) || (type >= PLUGIN_TYPES))
1042 va_start (ap, type);
1049 XPUSHs (sv_2mortal (newSViv ((IV)type)));
1051 if (PLUGIN_WRITE == type) {
1053 * $_[0] = $plugin_type;
1068 * values => [ $v1, ... ],
1070 * host => $hostname,
1071 * plugin => $plugin,
1073 * plugin_instance => $instance,
1074 * type_instance => $type_instance
1083 ds = va_arg (ap, data_set_t *);
1084 vl = va_arg (ap, value_list_t *);
1086 if (-1 == data_set2av (aTHX_ ds, pds)) {
1089 pds = (AV *)&PL_sv_undef;
1093 if (-1 == value_list2hv (aTHX_ vl, ds, pvl)) {
1096 pvl = (HV *)&PL_sv_undef;
1100 XPUSHs (sv_2mortal (newSVpv (ds->type, 0)));
1101 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1102 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1104 else if (PLUGIN_LOG == type) {
1110 XPUSHs (sv_2mortal (newSViv (va_arg (ap, int))));
1111 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1113 else if (PLUGIN_NOTIF == type) {
1117 * severity => $severity,
1121 * plugin => $plugin,
1123 * plugin_instance => $instance,
1124 * type_instance => $type_instance
1128 HV *notif = newHV ();
1130 n = va_arg (ap, notification_t *);
1132 if (-1 == notification2hv (aTHX_ n, notif)) {
1135 notif = (HV *)&PL_sv_undef;
1139 XPUSHs (sv_2mortal (newRV_noinc ((SV *)notif)));
1141 else if (PLUGIN_FLUSH == type) {
1146 * $_[1] = $identifier;
1148 timeout = va_arg (ap, cdtime_t);
1150 XPUSHs (sv_2mortal (newSVnv (CDTIME_T_TO_DOUBLE (timeout))));
1151 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1156 retvals = call_pv_locked (aTHX_ "Collectd::plugin_call_all");
1171 } /* static int pplugin_call_all (int, ...) */
1174 * collectd's Perl interpreter based thread implementation.
1176 * This has been inspired by Perl's ithreads introduced in version 5.6.0.
1179 /* must be called with perl_threads->mutex locked */
1180 static void c_ithread_destroy (c_ithread_t *ithread)
1182 dTHXa (ithread->interp);
1184 assert (NULL != perl_threads);
1186 PERL_SET_CONTEXT (aTHX);
1187 log_debug ("Shutting down Perl interpreter %p...", aTHX);
1192 --perl_threads->number_of_threads;
1193 #endif /* COLLECT_DEBUG */
1195 perl_destruct (aTHX);
1198 if (NULL == ithread->prev)
1199 perl_threads->head = ithread->next;
1201 ithread->prev->next = ithread->next;
1203 if (NULL == ithread->next)
1204 perl_threads->tail = ithread->prev;
1206 ithread->next->prev = ithread->prev;
1210 } /* static void c_ithread_destroy (c_ithread_t *) */
1212 static void c_ithread_destructor (void *arg)
1214 c_ithread_t *ithread = (c_ithread_t *)arg;
1215 c_ithread_t *t = NULL;
1217 if (NULL == perl_threads)
1220 pthread_mutex_lock (&perl_threads->mutex);
1222 for (t = perl_threads->head; NULL != t; t = t->next)
1226 /* the ithread no longer exists */
1229 pthread_mutex_unlock (&perl_threads->mutex);
1233 c_ithread_destroy (ithread);
1235 pthread_mutex_unlock (&perl_threads->mutex);
1237 } /* static void c_ithread_destructor (void *) */
1239 /* must be called with perl_threads->mutex locked */
1240 static c_ithread_t *c_ithread_create (PerlInterpreter *base)
1242 c_ithread_t *t = NULL;
1245 assert (NULL != perl_threads);
1247 t = smalloc (sizeof (*t));
1248 memset (t, 0, sizeof (c_ithread_t));
1250 t->interp = (NULL == base)
1252 : perl_clone (base, CLONEf_KEEP_PTR_TABLE);
1256 if ((NULL != base) && (NULL != PL_endav)) {
1257 av_clear (PL_endav);
1258 av_undef (PL_endav);
1263 ++perl_threads->number_of_threads;
1264 #endif /* COLLECT_DEBUG */
1268 if (NULL == perl_threads->tail) {
1269 perl_threads->head = t;
1273 perl_threads->tail->next = t;
1274 t->prev = perl_threads->tail;
1277 t->pthread = pthread_self();
1280 perl_threads->tail = t;
1282 pthread_setspecific (perl_thr_key, (const void *)t);
1284 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
1287 * Filter chains implementation.
1290 static int fc_call (pTHX_ int type, int cb_type, pfc_user_data_t *data, ...)
1297 notification_meta_t **meta = NULL;
1302 if ((type < 0) || (type >= FC_TYPES))
1305 if ((cb_type < 0) || (cb_type >= FC_CB_TYPES))
1308 va_start (ap, data);
1315 XPUSHs (sv_2mortal (newSViv ((IV)type)));
1316 XPUSHs (sv_2mortal (newSVpv (data->name, 0)));
1317 XPUSHs (sv_2mortal (newSViv ((IV)cb_type)));
1319 if (FC_CB_CREATE == cb_type) {
1322 * $_[1] = $user_data;
1325 HV *config = newHV ();
1327 ci = va_arg (ap, oconfig_item_t *);
1329 if (0 != oconfig_item2hv (aTHX_ ci, config)) {
1332 config = (HV *)&PL_sv_undef;
1336 XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
1338 else if (FC_CB_DESTROY == cb_type) {
1340 * $_[1] = $user_data;
1343 /* nothing to be done - the user data pointer
1344 * is pushed onto the stack later */
1346 else if (FC_CB_EXEC == cb_type) {
1351 * $_[3] = $user_data;
1359 ds = va_arg (ap, data_set_t *);
1360 vl = va_arg (ap, value_list_t *);
1361 meta = va_arg (ap, notification_meta_t **);
1363 if (0 != data_set2av (aTHX_ ds, pds)) {
1366 pds = (AV *)&PL_sv_undef;
1370 if (0 != value_list2hv (aTHX_ vl, ds, pvl)) {
1373 pvl = (HV *)&PL_sv_undef;
1380 if (0 != notification_meta2av (aTHX_ *meta, pmeta)) {
1383 pmeta = (AV *)&PL_sv_undef;
1388 pmeta = (AV *)&PL_sv_undef;
1391 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1392 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1393 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pmeta)));
1396 XPUSHs (sv_2mortal (newRV_inc (data->user_data)));
1400 retvals = call_pv_locked (aTHX_ "Collectd::fc_call");
1402 if ((FC_CB_EXEC == cb_type) && (meta != NULL)) {
1403 assert (pmeta != NULL);
1405 plugin_notification_meta_free (*meta);
1406 av2notification_meta (aTHX_ pmeta, meta);
1413 /* the exec callbacks return a status, while
1414 * the others return a boolean value */
1415 if (FC_CB_EXEC == cb_type)
1417 else if (! SvTRUE (tmp))
1427 } /* static int fc_call (int, int, pfc_user_data_t *, ...) */
1429 static int fc_create (int type, const oconfig_item_t *ci, void **user_data)
1431 pfc_user_data_t *data;
1437 if (NULL == perl_threads)
1441 c_ithread_t *t = NULL;
1443 pthread_mutex_lock (&perl_threads->mutex);
1444 t = c_ithread_create (perl_threads->head->interp);
1445 pthread_mutex_unlock (&perl_threads->mutex);
1450 log_debug ("fc_create: c_ithread: interp = %p (active threads: %i)",
1451 aTHX, perl_threads->number_of_threads);
1453 if ((1 != ci->values_num)
1454 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1455 log_warn ("A \"%s\" block expects a single string argument.",
1456 (FC_MATCH == type) ? "Match" : "Target");
1460 data = smalloc (sizeof (*data));
1461 data->name = sstrdup (ci->values[0].value.string);
1462 data->user_data = newSV (0);
1464 ret = fc_call (aTHX_ type, FC_CB_CREATE, data, ci);
1467 PFC_USER_DATA_FREE (data);
1471 } /* static int fc_create (int, const oconfig_item_t *, void **) */
1473 static int fc_destroy (int type, void **user_data)
1475 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1481 if ((NULL == perl_threads) || (NULL == data))
1485 c_ithread_t *t = NULL;
1487 pthread_mutex_lock (&perl_threads->mutex);
1488 t = c_ithread_create (perl_threads->head->interp);
1489 pthread_mutex_unlock (&perl_threads->mutex);
1494 log_debug ("fc_destroy: c_ithread: interp = %p (active threads: %i)",
1495 aTHX, perl_threads->number_of_threads);
1497 ret = fc_call (aTHX_ type, FC_CB_DESTROY, data);
1499 PFC_USER_DATA_FREE (data);
1502 } /* static int fc_destroy (int, void **) */
1504 static int fc_exec (int type, const data_set_t *ds, const value_list_t *vl,
1505 notification_meta_t **meta, void **user_data)
1507 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1511 if (NULL == perl_threads)
1514 assert (NULL != data);
1517 c_ithread_t *t = NULL;
1519 pthread_mutex_lock (&perl_threads->mutex);
1520 t = c_ithread_create (perl_threads->head->interp);
1521 pthread_mutex_unlock (&perl_threads->mutex);
1526 log_debug ("fc_exec: c_ithread: interp = %p (active threads: %i)",
1527 aTHX, perl_threads->number_of_threads);
1529 return fc_call (aTHX_ type, FC_CB_EXEC, data, ds, vl, meta);
1530 } /* static int fc_exec (int, const data_set_t *, const value_list_t *,
1531 notification_meta_t **, void **) */
1533 static int pmatch_create (const oconfig_item_t *ci, void **user_data)
1535 return fc_create (FC_MATCH, ci, user_data);
1536 } /* static int pmatch_create (const oconfig_item_t *, void **) */
1538 static int pmatch_destroy (void **user_data)
1540 return fc_destroy (FC_MATCH, user_data);
1541 } /* static int pmatch_destroy (void **) */
1543 static int pmatch_match (const data_set_t *ds, const value_list_t *vl,
1544 notification_meta_t **meta, void **user_data)
1546 return fc_exec (FC_MATCH, ds, vl, meta, user_data);
1547 } /* static int pmatch_match (const data_set_t *, const value_list_t *,
1548 notification_meta_t **, void **) */
1550 static match_proc_t pmatch = {
1551 pmatch_create, pmatch_destroy, pmatch_match
1554 static int ptarget_create (const oconfig_item_t *ci, void **user_data)
1556 return fc_create (FC_TARGET, ci, user_data);
1557 } /* static int ptarget_create (const oconfig_item_t *, void **) */
1559 static int ptarget_destroy (void **user_data)
1561 return fc_destroy (FC_TARGET, user_data);
1562 } /* static int ptarget_destroy (void **) */
1564 static int ptarget_invoke (const data_set_t *ds, value_list_t *vl,
1565 notification_meta_t **meta, void **user_data)
1567 return fc_exec (FC_TARGET, ds, vl, meta, user_data);
1568 } /* static int ptarget_invoke (const data_set_t *, value_list_t *,
1569 notification_meta_t **, void **) */
1571 static target_proc_t ptarget = {
1572 ptarget_create, ptarget_destroy, ptarget_invoke
1576 * Exported Perl API.
1580 * Collectd::plugin_register_data_set (type, dataset).
1583 * type of the dataset
1586 * dataset to be registered
1588 static XS (Collectd_plugin_register_ds)
1595 log_warn ("Using plugin_register() to register new data-sets is "
1596 "deprecated - add new entries to a custom types.db instead.");
1599 log_err ("Usage: Collectd::plugin_register_data_set(type, dataset)");
1603 log_debug ("Collectd::plugin_register_data_set: "
1604 "type = \"%s\", dataset = \"%s\"",
1605 SvPV_nolen (ST (0)), SvPV_nolen (ST (1)));
1609 if (SvROK (data) && (SVt_PVAV == SvTYPE (SvRV (data)))) {
1610 ret = pplugin_register_data_set (aTHX_ SvPV_nolen (ST (0)),
1614 log_err ("Collectd::plugin_register_data_set: Invalid data.");
1622 } /* static XS (Collectd_plugin_register_ds) */
1625 * Collectd::plugin_unregister_data_set (type).
1628 * type of the dataset
1630 static XS (Collectd_plugin_unregister_ds)
1635 log_err ("Usage: Collectd::plugin_unregister_data_set(type)");
1639 log_debug ("Collectd::plugin_unregister_data_set: type = \"%s\"",
1640 SvPV_nolen (ST (0)));
1642 if (0 == pplugin_unregister_data_set (SvPV_nolen (ST (0))))
1646 } /* static XS (Collectd_plugin_register_ds) */
1649 * Collectd::plugin_dispatch_values (name, values).
1652 * name of the plugin
1655 * value list to submit
1657 static XS (Collectd_plugin_dispatch_values)
1666 log_err ("Usage: Collectd::plugin_dispatch_values(values)");
1670 log_debug ("Collectd::plugin_dispatch_values: values=\"%s\"",
1671 SvPV_nolen (ST (/* stack index = */ 0)));
1673 values = ST (/* stack index = */ 0);
1678 /* Make sure the argument is a hash reference. */
1679 if (! (SvROK (values) && (SVt_PVHV == SvTYPE (SvRV (values))))) {
1680 log_err ("Collectd::plugin_dispatch_values: Invalid values.");
1684 ret = pplugin_dispatch_values (aTHX_ (HV *)SvRV (values));
1690 } /* static XS (Collectd_plugin_dispatch_values) */
1693 * Collectd::plugin_get_interval ().
1695 static XS (Collectd_plugin_get_interval)
1699 /* make sure we don't get any unused variable warnings for 'items';
1700 * don't abort, though */
1702 log_err ("Usage: Collectd::plugin_get_interval()");
1704 XSRETURN_NV ((NV) CDTIME_T_TO_DOUBLE (plugin_get_interval ()));
1705 } /* static XS (Collectd_plugin_get_interval) */
1707 /* Collectd::plugin_write (plugin, ds, vl).
1710 * name of the plugin to call, may be 'undef'
1713 * data-set that describes the submitted values, may be 'undef'
1716 * value-list to be written
1718 static XS (Collectd__plugin_write)
1729 log_err ("Usage: Collectd::plugin_write(plugin, ds, vl)");
1733 log_debug ("Collectd::plugin_write: plugin=\"%s\", ds=\"%s\", vl=\"%s\"",
1734 SvPV_nolen (ST (0)), SvOK (ST (1)) ? SvPV_nolen (ST (1)) : "",
1735 SvPV_nolen (ST (2)));
1737 if (! SvOK (ST (0)))
1740 plugin = SvPV_nolen (ST (0));
1743 if (SvROK (ds) && (SVt_PVAV == SvTYPE (SvRV (ds))))
1744 ds_array = (AV *)SvRV (ds);
1745 else if (! SvOK (ds))
1748 log_err ("Collectd::plugin_write: Invalid data-set.");
1753 if (! (SvROK (vl) && (SVt_PVHV == SvTYPE (SvRV (vl))))) {
1754 log_err ("Collectd::plugin_write: Invalid value-list.");
1758 ret = pplugin_write (aTHX_ plugin, ds_array, (HV *)SvRV (vl));
1764 } /* static XS (Collectd__plugin_write) */
1767 * Collectd::_plugin_flush (plugin, timeout, identifier).
1770 * name of the plugin to flush
1773 * timeout to use when flushing the data
1776 * data-set identifier to flush
1778 static XS (Collectd__plugin_flush)
1780 char *plugin = NULL;
1787 log_err ("Usage: Collectd::_plugin_flush(plugin, timeout, id)");
1792 plugin = SvPV_nolen (ST (0));
1795 timeout = (int)SvIV (ST (1));
1798 id = SvPV_nolen (ST (2));
1800 log_debug ("Collectd::_plugin_flush: plugin = \"%s\", timeout = %i, "
1801 "id = \"%s\"", plugin, timeout, id);
1803 if (0 == plugin_flush (plugin, timeout, id))
1807 } /* static XS (Collectd__plugin_flush) */
1810 * Collectd::plugin_dispatch_notification (notif).
1813 * notification to dispatch
1815 static XS (Collectd_plugin_dispatch_notification)
1824 log_err ("Usage: Collectd::plugin_dispatch_notification(notif)");
1828 log_debug ("Collectd::plugin_dispatch_notification: notif = \"%s\"",
1829 SvPV_nolen (ST (0)));
1833 if (! (SvROK (notif) && (SVt_PVHV == SvTYPE (SvRV (notif))))) {
1834 log_err ("Collectd::plugin_dispatch_notification: Invalid notif.");
1838 ret = pplugin_dispatch_notification (aTHX_ (HV *)SvRV (notif));
1844 } /* static XS (Collectd_plugin_dispatch_notification) */
1847 * Collectd::plugin_log (level, message).
1850 * log level (LOG_DEBUG, ... LOG_ERR)
1855 static XS (Collectd_plugin_log)
1860 log_err ("Usage: Collectd::plugin_log(level, message)");
1864 plugin_log (SvIV (ST (0)), "%s", SvPV_nolen (ST (1)));
1866 } /* static XS (Collectd_plugin_log) */
1869 * Collectd::_fc_register (type, name)
1877 static XS (Collectd__fc_register)
1887 log_err ("Usage: Collectd::_fc_register(type, name)");
1891 type = SvIV (ST (0));
1892 name = SvPV_nolen (ST (1));
1894 if (FC_MATCH == type)
1895 ret = fc_register_match (name, pmatch);
1896 else if (FC_TARGET == type)
1897 ret = fc_register_target (name, ptarget);
1903 } /* static XS (Collectd_fc_register) */
1906 * Collectd::call_by_name (...).
1908 * Call a Perl sub identified by its name passed through $Collectd::cb_name.
1910 static XS (Collectd_call_by_name)
1915 if (NULL == (tmp = get_sv ("Collectd::cb_name", 0))) {
1916 sv_setpv (get_sv ("@", 1), "cb_name has not been set");
1921 name = SvPV_nolen (tmp);
1923 if (NULL == get_cv (name, 0)) {
1924 sv_setpvf (get_sv ("@", 1), "unknown callback \"%s\"", name);
1929 /* simply pass on the subroutine call without touching the stack,
1930 * thus leaving any arguments and return values in place */
1932 } /* static XS (Collectd_call_by_name) */
1935 * Interface to collectd.
1938 static int perl_init (void)
1943 if (NULL == perl_threads)
1947 c_ithread_t *t = NULL;
1949 pthread_mutex_lock (&perl_threads->mutex);
1950 t = c_ithread_create (perl_threads->head->interp);
1951 pthread_mutex_unlock (&perl_threads->mutex);
1956 log_debug ("perl_init: c_ithread: interp = %p (active threads: %i)",
1957 aTHX, perl_threads->number_of_threads);
1959 /* Lock the base thread to avoid race conditions with c_ithread_create().
1960 * See https://github.com/collectd/collectd/issues/9 and
1961 * https://github.com/collectd/collectd/issues/1706 for details.
1963 assert (aTHX == perl_threads->head->interp);
1964 pthread_mutex_lock (&perl_threads->mutex);
1966 status = pplugin_call_all (aTHX_ PLUGIN_INIT);
1968 pthread_mutex_unlock (&perl_threads->mutex);
1971 } /* static int perl_init (void) */
1973 static int perl_read (void)
1977 if (NULL == perl_threads)
1981 c_ithread_t *t = NULL;
1983 pthread_mutex_lock (&perl_threads->mutex);
1984 t = c_ithread_create (perl_threads->head->interp);
1985 pthread_mutex_unlock (&perl_threads->mutex);
1990 /* Assert that we're not running as the base thread. Otherwise, we might
1991 * run into concurrency issues with c_ithread_create(). See
1992 * https://github.com/collectd/collectd/issues/9 for details. */
1993 assert (aTHX != perl_threads->head->interp);
1995 log_debug ("perl_read: c_ithread: interp = %p (active threads: %i)",
1996 aTHX, perl_threads->number_of_threads);
1997 return pplugin_call_all (aTHX_ PLUGIN_READ);
1998 } /* static int perl_read (void) */
2000 static int perl_write (const data_set_t *ds, const value_list_t *vl,
2001 user_data_t __attribute__((unused)) *user_data)
2006 if (NULL == perl_threads)
2010 c_ithread_t *t = NULL;
2012 pthread_mutex_lock (&perl_threads->mutex);
2013 t = c_ithread_create (perl_threads->head->interp);
2014 pthread_mutex_unlock (&perl_threads->mutex);
2019 /* Lock the base thread if this is not called from one of the read threads
2020 * to avoid race conditions with c_ithread_create(). See
2021 * https://github.com/collectd/collectd/issues/9 for details. */
2022 if (aTHX == perl_threads->head->interp)
2023 pthread_mutex_lock (&perl_threads->mutex);
2025 log_debug ("perl_write: c_ithread: interp = %p (active threads: %i)",
2026 aTHX, perl_threads->number_of_threads);
2027 status = pplugin_call_all (aTHX_ PLUGIN_WRITE, ds, vl);
2029 if (aTHX == perl_threads->head->interp)
2030 pthread_mutex_unlock (&perl_threads->mutex);
2033 } /* static int perl_write (const data_set_t *, const value_list_t *) */
2035 static void perl_log (int level, const char *msg,
2036 user_data_t __attribute__((unused)) *user_data)
2040 if (NULL == perl_threads)
2044 c_ithread_t *t = NULL;
2046 pthread_mutex_lock (&perl_threads->mutex);
2047 t = c_ithread_create (perl_threads->head->interp);
2048 pthread_mutex_unlock (&perl_threads->mutex);
2053 /* Lock the base thread if this is not called from one of the read threads
2054 * to avoid race conditions with c_ithread_create(). See
2055 * https://github.com/collectd/collectd/issues/9 for details.
2058 if (aTHX == perl_threads->head->interp)
2059 pthread_mutex_lock (&perl_threads->mutex);
2061 pplugin_call_all (aTHX_ PLUGIN_LOG, level, msg);
2063 if (aTHX == perl_threads->head->interp)
2064 pthread_mutex_unlock (&perl_threads->mutex);
2067 } /* static void perl_log (int, const char *) */
2069 static int perl_notify (const notification_t *notif,
2070 user_data_t __attribute__((unused)) *user_data)
2074 if (NULL == perl_threads)
2078 c_ithread_t *t = NULL;
2080 pthread_mutex_lock (&perl_threads->mutex);
2081 t = c_ithread_create (perl_threads->head->interp);
2082 pthread_mutex_unlock (&perl_threads->mutex);
2086 return pplugin_call_all (aTHX_ PLUGIN_NOTIF, notif);
2087 } /* static int perl_notify (const notification_t *) */
2089 static int perl_flush (cdtime_t timeout, const char *identifier,
2090 user_data_t __attribute__((unused)) *user_data)
2094 if (NULL == perl_threads)
2098 c_ithread_t *t = NULL;
2100 pthread_mutex_lock (&perl_threads->mutex);
2101 t = c_ithread_create (perl_threads->head->interp);
2102 pthread_mutex_unlock (&perl_threads->mutex);
2106 return pplugin_call_all (aTHX_ PLUGIN_FLUSH, timeout, identifier);
2107 } /* static int perl_flush (const int) */
2109 static int perl_shutdown (void)
2116 plugin_unregister_complex_config ("perl");
2118 if (NULL == perl_threads)
2122 pthread_mutex_lock (&perl_threads->mutex);
2123 t = c_ithread_create (perl_threads->head->interp);
2124 pthread_mutex_unlock (&perl_threads->mutex);
2129 log_debug ("perl_shutdown: c_ithread: interp = %p (active threads: %i)",
2130 aTHX, perl_threads->number_of_threads);
2132 plugin_unregister_log ("perl");
2133 plugin_unregister_notification ("perl");
2134 plugin_unregister_init ("perl");
2135 plugin_unregister_read ("perl");
2136 plugin_unregister_write ("perl");
2137 plugin_unregister_flush ("perl");
2139 ret = pplugin_call_all (aTHX_ PLUGIN_SHUTDOWN);
2141 pthread_mutex_lock (&perl_threads->mutex);
2142 t = perl_threads->tail;
2145 struct timespec ts_wait;
2146 c_ithread_t *thr = t;
2148 /* the pointer has to be advanced before destroying
2149 * the thread as this will free the memory */
2154 /* Give some time to thread to exit from Perl interpreter */
2155 WARNING ("perl shutdown: Thread is running inside Perl. Waiting.");
2157 ts_wait.tv_nsec = 500000;
2158 nanosleep (&ts_wait, NULL);
2161 pthread_kill (thr->pthread, SIGTERM);
2162 ERROR ("perl shutdown: Thread hangs inside Perl. Thread killed.");
2164 c_ithread_destroy (thr);
2167 pthread_mutex_unlock (&perl_threads->mutex);
2168 pthread_mutex_destroy (&perl_threads->mutex);
2169 pthread_mutexattr_destroy (&perl_threads->mutexattr);
2171 sfree (perl_threads);
2173 pthread_key_delete (perl_thr_key);
2177 plugin_unregister_shutdown ("perl");
2179 } /* static void perl_shutdown (void) */
2182 * Access functions for global variables.
2184 * These functions implement the "magic" used to access
2185 * the global variables from Perl.
2188 static int g_pv_get (pTHX_ SV *var, MAGIC *mg)
2190 char *pv = mg->mg_ptr;
2193 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
2195 static int g_pv_set (pTHX_ SV *var, MAGIC *mg)
2197 char *pv = mg->mg_ptr;
2198 sstrncpy (pv, SvPV_nolen (var), DATA_MAX_NAME_LEN);
2200 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
2202 static int g_interval_get (pTHX_ SV *var, MAGIC *mg)
2204 log_warn ("Accessing $interval_g is deprecated (and might not "
2205 "give the desired results) - plugin_get_interval() should "
2206 "be used instead.");
2207 sv_setnv (var, CDTIME_T_TO_DOUBLE (interval_g));
2209 } /* static int g_interval_get (pTHX_ SV *, MAGIC *) */
2211 static int g_interval_set (pTHX_ SV *var, MAGIC *mg)
2213 double nv = (double)SvNV (var);
2214 log_warn ("Accessing $interval_g is deprecated (and might not "
2215 "give the desired results) - plugin_get_interval() should "
2216 "be used instead.");
2217 interval_g = DOUBLE_TO_CDTIME_T (nv);
2219 } /* static int g_interval_set (pTHX_ SV *, MAGIC *) */
2221 static MGVTBL g_pv_vtbl = {
2222 g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL
2223 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2227 static MGVTBL g_interval_vtbl = {
2228 g_interval_get, g_interval_set, NULL, NULL, NULL, NULL, NULL
2229 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2234 /* bootstrap the Collectd module */
2235 static void xs_init (pTHX)
2239 char *file = __FILE__;
2245 /* enable usage of Perl modules using shared libraries */
2246 newXS ("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2249 for (i = 0; NULL != api[i].f; ++i)
2250 newXS (api[i].name, api[i].f, file);
2252 stash = gv_stashpv ("Collectd", 1);
2254 /* export "constants" */
2255 for (i = 0; '\0' != constants[i].name[0]; ++i)
2256 newCONSTSUB (stash, constants[i].name, newSViv (constants[i].value));
2258 /* export global variables
2259 * by adding "magic" to the SV's representing the globale variables
2260 * perl is able to automagically call the get/set function when
2261 * accessing any such variable (this is basically the same as using
2263 /* global strings */
2264 for (i = 0; '\0' != g_strings[i].name[0]; ++i) {
2265 tmp = get_sv (g_strings[i].name, 1);
2266 sv_magicext (tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl,
2267 g_strings[i].var, 0);
2270 tmp = get_sv ("Collectd::interval_g", /* create = */ 1);
2271 sv_magicext (tmp, NULL, /* how = */ PERL_MAGIC_ext,
2272 /* vtbl = */ &g_interval_vtbl,
2273 /* name = */ NULL, /* namelen = */ 0);
2276 } /* static void xs_init (pTHX) */
2278 /* Initialize the global Perl interpreter. */
2279 static int init_pi (int argc, char **argv)
2283 if (NULL != perl_threads)
2286 log_info ("Initializing Perl interpreter...");
2291 for (i = 0; i < argc; ++i)
2292 log_debug ("argv[%i] = \"%s\"", i, argv[i]);
2294 #endif /* COLLECT_DEBUG */
2296 if (0 != pthread_key_create (&perl_thr_key, c_ithread_destructor)) {
2297 log_err ("init_pi: pthread_key_create failed");
2299 /* this must not happen - cowardly giving up if it does */
2304 /* On FreeBSD, PERL_SYS_INIT3 expands to some expression which
2305 * triggers a "value computed is not used" warning by gcc. */
2308 PERL_SYS_INIT3 (&argc, &argv, &environ);
2310 perl_threads = smalloc (sizeof (*perl_threads));
2311 memset (perl_threads, 0, sizeof (c_ithread_list_t));
2313 pthread_mutexattr_init(&perl_threads->mutexattr);
2314 pthread_mutexattr_settype(&perl_threads->mutexattr, PTHREAD_MUTEX_RECURSIVE);
2315 pthread_mutex_init (&perl_threads->mutex, &perl_threads->mutexattr);
2316 /* locking the mutex should not be necessary at this point
2317 * but let's just do it for the sake of completeness */
2318 pthread_mutex_lock (&perl_threads->mutex);
2320 perl_threads->head = c_ithread_create (NULL);
2321 perl_threads->tail = perl_threads->head;
2323 if (NULL == (perl_threads->head->interp = perl_alloc ())) {
2324 log_err ("init_pi: Not enough memory.");
2328 aTHX = perl_threads->head->interp;
2329 pthread_mutex_unlock (&perl_threads->mutex);
2331 perl_construct (aTHX);
2333 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
2335 if (0 != perl_parse (aTHX_ xs_init, argc, argv, NULL)) {
2336 SV *err = get_sv ("@", 1);
2337 log_err ("init_pi: Unable to bootstrap Collectd: %s",
2340 perl_destruct (perl_threads->head->interp);
2341 perl_free (perl_threads->head->interp);
2342 sfree (perl_threads);
2344 pthread_key_delete (perl_thr_key);
2348 /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
2349 sv_setpv (get_sv ("0", 0), "collectd");
2353 plugin_register_log ("perl", perl_log, /* user_data = */ NULL);
2354 plugin_register_notification ("perl", perl_notify,
2355 /* user_data = */ NULL);
2356 plugin_register_init ("perl", perl_init);
2358 plugin_register_read ("perl", perl_read);
2360 plugin_register_write ("perl", perl_write, /* user_data = */ NULL);
2361 plugin_register_flush ("perl", perl_flush, /* user_data = */ NULL);
2362 plugin_register_shutdown ("perl", perl_shutdown);
2364 } /* static int init_pi (const char **, const int) */
2367 * LoadPlugin "<Plugin>"
2369 static int perl_config_loadplugin (pTHX_ oconfig_item_t *ci)
2371 char module_name[DATA_MAX_NAME_LEN];
2375 if ((0 != ci->children_num) || (1 != ci->values_num)
2376 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2377 log_err ("LoadPlugin expects a single string argument.");
2381 value = ci->values[0].value.string;
2383 if (NULL == get_module_name (module_name, sizeof (module_name), value)) {
2384 log_err ("Invalid module name %s", value);
2388 if (0 != init_pi (perl_argc, perl_argv))
2391 assert (NULL != perl_threads);
2392 assert (NULL != perl_threads->head);
2394 aTHX = perl_threads->head->interp;
2396 log_debug ("perl_config: Loading Perl plugin \"%s\"", value);
2397 load_module (PERL_LOADMOD_NOIMPORT,
2398 newSVpv (module_name, strlen (module_name)), Nullsv);
2400 } /* static int perl_config_loadplugin (oconfig_item_it *) */
2405 static int perl_config_basename (pTHX_ oconfig_item_t *ci)
2409 if ((0 != ci->children_num) || (1 != ci->values_num)
2410 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2411 log_err ("BaseName expects a single string argument.");
2415 value = ci->values[0].value.string;
2417 log_debug ("perl_config: Setting plugin basename to \"%s\"", value);
2418 sstrncpy (base_name, value, sizeof (base_name));
2420 } /* static int perl_config_basename (oconfig_item_it *) */
2423 * EnableDebugger "<Package>"|""
2425 static int perl_config_enabledebugger (pTHX_ oconfig_item_t *ci)
2429 if ((0 != ci->children_num) || (1 != ci->values_num)
2430 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2431 log_err ("EnableDebugger expects a single string argument.");
2435 if (NULL != perl_threads) {
2436 log_warn ("EnableDebugger has no effects if used after LoadPlugin.");
2440 value = ci->values[0].value.string;
2442 perl_argv = realloc (perl_argv,
2443 (++perl_argc + 1) * sizeof (char *));
2445 if (NULL == perl_argv) {
2446 log_err ("perl_config: Not enough memory.");
2450 if ('\0' == value[0]) {
2451 perl_argv[perl_argc - 1] = "-d";
2454 perl_argv[perl_argc - 1] = smalloc (strlen (value) + 4);
2455 sstrncpy (perl_argv[perl_argc - 1], "-d:", 4);
2456 sstrncpy (perl_argv[perl_argc - 1] + 3, value, strlen (value) + 1);
2459 perl_argv[perl_argc] = NULL;
2461 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
2464 * IncludeDir "<Dir>"
2466 static int perl_config_includedir (pTHX_ oconfig_item_t *ci)
2470 if ((0 != ci->children_num) || (1 != ci->values_num)
2471 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2472 log_err ("IncludeDir expects a single string argument.");
2476 value = ci->values[0].value.string;
2479 perl_argv = realloc (perl_argv,
2480 (++perl_argc + 1) * sizeof (char *));
2482 if (NULL == perl_argv) {
2483 log_err ("perl_config: Not enough memory.");
2487 perl_argv[perl_argc - 1] = smalloc (strlen (value) + 3);
2488 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
2489 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen (value) + 1);
2491 perl_argv[perl_argc] = NULL;
2494 /* prepend the directory to @INC */
2495 av_unshift (GvAVn (PL_incgv), 1);
2496 av_store (GvAVn (PL_incgv), 0, newSVpv (value, strlen (value)));
2499 } /* static int perl_config_includedir (oconfig_item_it *) */
2504 static int perl_config_plugin (pTHX_ oconfig_item_t *ci)
2514 if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2515 log_err ("LoadPlugin expects a single string argument.");
2519 plugin = ci->values[0].value.string;
2522 if (0 != oconfig_item2hv (aTHX_ ci, config)) {
2526 log_err ("Unable to convert configuration to a Perl hash value.");
2527 config = (HV *)&PL_sv_undef;
2535 XPUSHs (sv_2mortal (newSVpv (plugin, 0)));
2536 XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
2540 retvals = call_pv ("Collectd::_plugin_dispatch_config", G_SCALAR);
2555 } /* static int perl_config_plugin (oconfig_item_it *) */
2557 static int perl_config (oconfig_item_t *ci)
2564 for (i = 0; i < ci->children_num; ++i) {
2565 oconfig_item_t *c = ci->children + i;
2566 int current_status = 0;
2568 if (NULL != perl_threads)
2570 if ((aTHX = PERL_GET_CONTEXT) == NULL)
2574 if (0 == strcasecmp (c->key, "LoadPlugin"))
2575 current_status = perl_config_loadplugin (aTHX_ c);
2576 else if (0 == strcasecmp (c->key, "BaseName"))
2577 current_status = perl_config_basename (aTHX_ c);
2578 else if (0 == strcasecmp (c->key, "EnableDebugger"))
2579 current_status = perl_config_enabledebugger (aTHX_ c);
2580 else if (0 == strcasecmp (c->key, "IncludeDir"))
2581 current_status = perl_config_includedir (aTHX_ c);
2582 else if (0 == strcasecmp (c->key, "Plugin"))
2583 current_status = perl_config_plugin (aTHX_ c);
2586 log_warn ("Ignoring unknown config key \"%s\".", c->key);
2590 /* fatal error - it's up to perl_config_* to clean up */
2591 if (0 > current_status) {
2592 log_err ("Configuration failed with a fatal error - "
2593 "plugin disabled!");
2594 return current_status;
2597 status += current_status;
2600 } /* static int perl_config (oconfig_item_t *) */
2602 void module_register (void)
2605 perl_argv = smalloc ((perl_argc + 1) * sizeof (*perl_argv));
2607 /* default options for the Perl interpreter */
2609 perl_argv[1] = "-MCollectd";
2610 perl_argv[2] = "-e";
2612 perl_argv[4] = NULL;
2614 plugin_register_complex_config ("perl", perl_config);
2616 } /* void module_register (void) */
2618 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */