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
38 #undef DONT_POISON_SPRINTF_YET
47 #if defined(COLLECT_DEBUG) && COLLECT_DEBUG && defined(__GNUC__) && __GNUC__
49 # pragma GCC poison sprintf
54 /* Some versions of Perl define their own version of DEBUG... :-/ */
59 /* ... while we want the definition found in plugin.h. */
63 #include "filter_chain.h"
65 #if !defined(USE_ITHREADS)
66 # error "Perl does not support ithreads!"
67 #endif /* !defined(USE_ITHREADS) */
69 /* clear the Perl sub's stack frame
70 * (this should only be used inside an XSUB) */
71 #define CLEAR_STACK_FRAME PL_stack_sp = PL_stack_base + *PL_markstack_ptr
75 #define PLUGIN_WRITE 2
76 #define PLUGIN_SHUTDOWN 3
78 #define PLUGIN_NOTIF 5
79 #define PLUGIN_FLUSH 6
81 #define PLUGIN_TYPES 7
83 #define PLUGIN_CONFIG 254
84 #define PLUGIN_DATASET 255
91 #define FC_CB_CREATE 0
92 #define FC_CB_DESTROY 1
97 #define log_debug(...) DEBUG ("perl: " __VA_ARGS__)
98 #define log_info(...) INFO ("perl: " __VA_ARGS__)
99 #define log_warn(...) WARNING ("perl: " __VA_ARGS__)
100 #define log_err(...) ERROR ("perl: " __VA_ARGS__)
102 /* this is defined in DynaLoader.a */
103 void boot_DynaLoader (PerlInterpreter *, CV *);
105 static XS (Collectd_plugin_register_ds);
106 static XS (Collectd_plugin_unregister_ds);
107 static XS (Collectd_plugin_dispatch_values);
108 static XS (Collectd_plugin_get_interval);
109 static XS (Collectd__plugin_write);
110 static XS (Collectd__plugin_flush);
111 static XS (Collectd_plugin_dispatch_notification);
112 static XS (Collectd_plugin_log);
113 static XS (Collectd__fc_register);
114 static XS (Collectd_call_by_name);
120 typedef struct c_ithread_s {
121 /* the thread's Perl interpreter */
122 PerlInterpreter *interp;
123 _Bool running; /* thread is inside Perl interpreter */
127 /* double linked list of threads */
128 struct c_ithread_s *prev;
129 struct c_ithread_s *next;
137 /* some usage stats */
138 int number_of_threads;
139 #endif /* COLLECT_DEBUG */
141 pthread_mutex_t mutex;
142 pthread_mutexattr_t mutexattr;
145 /* name / user_data for Perl matches / targets */
151 #define PFC_USER_DATA_FREE(data) \
153 sfree ((data)->name); \
154 if (NULL != (data)->user_data) \
155 sv_free ((data)->user_data); \
162 extern char **environ;
168 /* if perl_threads != NULL perl_threads->head must
169 * point to the "base" thread */
170 static c_ithread_list_t *perl_threads = NULL;
172 /* the key used to store each pthread's ithread */
173 static pthread_key_t perl_thr_key;
175 static int perl_argc = 0;
176 static char **perl_argv = NULL;
178 static char base_name[DATA_MAX_NAME_LEN] = "";
185 { "Collectd::plugin_register_data_set", Collectd_plugin_register_ds },
186 { "Collectd::plugin_unregister_data_set", Collectd_plugin_unregister_ds },
187 { "Collectd::plugin_dispatch_values", Collectd_plugin_dispatch_values },
188 { "Collectd::plugin_get_interval", Collectd_plugin_get_interval },
189 { "Collectd::_plugin_write", Collectd__plugin_write },
190 { "Collectd::_plugin_flush", Collectd__plugin_flush },
191 { "Collectd::plugin_dispatch_notification",
192 Collectd_plugin_dispatch_notification },
193 { "Collectd::plugin_log", Collectd_plugin_log },
194 { "Collectd::_fc_register", Collectd__fc_register },
195 { "Collectd::call_by_name", Collectd_call_by_name },
204 { "Collectd::TYPE_INIT", PLUGIN_INIT },
205 { "Collectd::TYPE_READ", PLUGIN_READ },
206 { "Collectd::TYPE_WRITE", PLUGIN_WRITE },
207 { "Collectd::TYPE_SHUTDOWN", PLUGIN_SHUTDOWN },
208 { "Collectd::TYPE_LOG", PLUGIN_LOG },
209 { "Collectd::TYPE_NOTIF", PLUGIN_NOTIF },
210 { "Collectd::TYPE_FLUSH", PLUGIN_FLUSH },
211 { "Collectd::TYPE_CONFIG", PLUGIN_CONFIG },
212 { "Collectd::TYPE_DATASET", PLUGIN_DATASET },
213 { "Collectd::DS_TYPE_COUNTER", DS_TYPE_COUNTER },
214 { "Collectd::DS_TYPE_GAUGE", DS_TYPE_GAUGE },
215 { "Collectd::DS_TYPE_DERIVE", DS_TYPE_DERIVE },
216 { "Collectd::DS_TYPE_ABSOLUTE", DS_TYPE_ABSOLUTE },
217 { "Collectd::LOG_ERR", LOG_ERR },
218 { "Collectd::LOG_WARNING", LOG_WARNING },
219 { "Collectd::LOG_NOTICE", LOG_NOTICE },
220 { "Collectd::LOG_INFO", LOG_INFO },
221 { "Collectd::LOG_DEBUG", LOG_DEBUG },
222 { "Collectd::FC_MATCH", FC_MATCH },
223 { "Collectd::FC_TARGET", FC_TARGET },
224 { "Collectd::FC_CB_CREATE", FC_CB_CREATE },
225 { "Collectd::FC_CB_DESTROY", FC_CB_DESTROY },
226 { "Collectd::FC_CB_EXEC", FC_CB_EXEC },
227 { "Collectd::FC_MATCH_NO_MATCH", FC_MATCH_NO_MATCH },
228 { "Collectd::FC_MATCH_MATCHES", FC_MATCH_MATCHES },
229 { "Collectd::FC_TARGET_CONTINUE", FC_TARGET_CONTINUE },
230 { "Collectd::FC_TARGET_STOP", FC_TARGET_STOP },
231 { "Collectd::FC_TARGET_RETURN", FC_TARGET_RETURN },
232 { "Collectd::NOTIF_FAILURE", NOTIF_FAILURE },
233 { "Collectd::NOTIF_WARNING", NOTIF_WARNING },
234 { "Collectd::NOTIF_OKAY", NOTIF_OKAY },
243 { "Collectd::hostname_g", hostname_g },
248 * Helper functions for data type conversion.
263 static int hv2data_source (pTHX_ HV *hash, data_source_t *ds)
267 if ((NULL == hash) || (NULL == ds))
270 if (NULL != (tmp = hv_fetch (hash, "name", 4, 0))) {
271 sstrncpy (ds->name, SvPV_nolen (*tmp), sizeof (ds->name));
274 log_err ("hv2data_source: No DS name given.");
278 if (NULL != (tmp = hv_fetch (hash, "type", 4, 0))) {
279 ds->type = SvIV (*tmp);
281 if ((DS_TYPE_COUNTER != ds->type)
282 && (DS_TYPE_GAUGE != ds->type)
283 && (DS_TYPE_DERIVE != ds->type)
284 && (DS_TYPE_ABSOLUTE != ds->type)) {
285 log_err ("hv2data_source: Invalid DS type.");
290 ds->type = DS_TYPE_COUNTER;
293 if (NULL != (tmp = hv_fetch (hash, "min", 3, 0)))
294 ds->min = SvNV (*tmp);
298 if (NULL != (tmp = hv_fetch (hash, "max", 3, 0)))
299 ds->max = SvNV (*tmp);
303 } /* static int hv2data_source (HV *, data_source_t *) */
305 /* av2value converts at most "len" elements from "array" to "value". Returns the
306 * number of elements converted or zero on error. */
307 static size_t av2value (pTHX_ char *name, AV *array, value_t *value, size_t array_len)
309 const data_set_t *ds;
311 if ((NULL == name) || (NULL == array) || (NULL == value) || (array_len == 0))
314 ds = plugin_get_ds (name);
316 log_err ("av2value: Unknown dataset \"%s\"", name);
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);
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);
329 for (size_t i = 0; i < ds->ds_num; ++i) {
330 SV **tmp = av_fetch (array, i, 0);
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);
348 } /* static size_t av2value (char *, AV *, value_t *, size_t) */
353 * values => [ @values ],
357 * plugin_instance => $pinstance,
358 * type_instance => $tinstance,
361 static int hv2value_list (pTHX_ HV *hash, value_list_t *vl)
365 if ((NULL == hash) || (NULL == vl))
368 if (NULL == (tmp = hv_fetch (hash, "type", 4, 0))) {
369 log_err ("hv2value_list: No type given.");
373 sstrncpy (vl->type, SvPV_nolen (*tmp), sizeof (vl->type));
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.");
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);
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) {
396 if (NULL != (tmp = hv_fetch (hash, "time", 4, 0)))
398 double t = SvNV (*tmp);
399 vl->time = DOUBLE_TO_CDTIME_T (t);
402 if (NULL != (tmp = hv_fetch (hash, "interval", 8, 0)))
404 double t = SvNV (*tmp);
405 vl->interval = DOUBLE_TO_CDTIME_T (t);
408 if (NULL != (tmp = hv_fetch (hash, "host", 4, 0)))
409 sstrncpy (vl->host, SvPV_nolen (*tmp), sizeof (vl->host));
411 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
413 if (NULL != (tmp = hv_fetch (hash, "plugin", 6, 0)))
414 sstrncpy (vl->plugin, SvPV_nolen (*tmp), sizeof (vl->plugin));
416 if (NULL != (tmp = hv_fetch (hash, "plugin_instance", 15, 0)))
417 sstrncpy (vl->plugin_instance, SvPV_nolen (*tmp),
418 sizeof (vl->plugin_instance));
420 if (NULL != (tmp = hv_fetch (hash, "type_instance", 13, 0)))
421 sstrncpy (vl->type_instance, SvPV_nolen (*tmp),
422 sizeof (vl->type_instance));
424 } /* static int hv2value_list (pTHX_ HV *, value_list_t *) */
426 static int av2data_set (pTHX_ AV *array, char *name, data_set_t *ds)
430 if ((NULL == array) || (NULL == name) || (NULL == ds))
433 len = av_len (array);
436 log_err ("av2data_set: Invalid data set.");
440 ds->ds = smalloc ((len + 1) * sizeof (*ds->ds));
441 ds->ds_num = len + 1;
443 for (int i = 0; i <= len; ++i) {
444 SV **elem = av_fetch (array, i, 0);
447 log_err ("av2data_set: Failed to fetch data source %i.", i);
451 if (! (SvROK (*elem) && (SVt_PVHV == SvTYPE (SvRV (*elem))))) {
452 log_err ("av2data_set: Invalid data source.");
456 if (-1 == hv2data_source (aTHX_ (HV *)SvRV (*elem), &ds->ds[i]))
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);
464 sstrncpy (ds->type, name, sizeof (ds->type));
466 } /* static int av2data_set (pTHX_ AV *, data_set_t *) */
471 * severity => $severity,
477 * plugin_instance => $instance,
478 * type_instance => $type_instance,
479 * meta => [ { name => <name>, value => <value> }, ... ]
482 static int av2notification_meta (pTHX_ AV *array, notification_meta_t **meta)
484 notification_meta_t **m = meta;
486 int len = av_len (array);
488 for (int i = 0; i <= len; ++i) {
489 SV **tmp = av_fetch (array, i, 0);
495 if (! (SvROK (*tmp) && (SVt_PVHV == SvTYPE (SvRV (*tmp))))) {
496 log_warn ("av2notification_meta: Skipping invalid "
497 "meta information.");
501 hash = (HV *)SvRV (*tmp);
503 *m = smalloc (sizeof (**m));
505 if (NULL == (tmp = hv_fetch (hash, "name", 4, 0))) {
506 log_warn ("av2notification_meta: Skipping invalid "
507 "meta information.");
511 sstrncpy ((*m)->name, SvPV_nolen (*tmp), sizeof ((*m)->name));
513 if (NULL == (tmp = hv_fetch (hash, "value", 5, 0))) {
514 log_warn ("av2notification_meta: Skipping invalid "
515 "meta information.");
521 (*m)->nm_value.nm_double = SvNVX (*tmp);
522 (*m)->type = NM_TYPE_DOUBLE;
524 else if (SvUOK (*tmp)) {
525 (*m)->nm_value.nm_unsigned_int = SvUVX (*tmp);
526 (*m)->type = NM_TYPE_UNSIGNED_INT;
528 else if (SvIOK (*tmp)) {
529 (*m)->nm_value.nm_signed_int = SvIVX (*tmp);
530 (*m)->type = NM_TYPE_SIGNED_INT;
533 (*m)->nm_value.nm_string = sstrdup (SvPV_nolen (*tmp));
534 (*m)->type = NM_TYPE_STRING;
541 } /* static int av2notification_meta (AV *, notification_meta_t *) */
543 static int hv2notification (pTHX_ HV *hash, notification_t *n)
547 if ((NULL == hash) || (NULL == n))
550 if (NULL != (tmp = hv_fetch (hash, "severity", 8, 0)))
551 n->severity = SvIV (*tmp);
553 n->severity = NOTIF_FAILURE;
555 if (NULL != (tmp = hv_fetch (hash, "time", 4, 0)))
557 double t = SvNV (*tmp);
558 n->time = DOUBLE_TO_CDTIME_T (t);
563 if (NULL != (tmp = hv_fetch (hash, "message", 7, 0)))
564 sstrncpy (n->message, SvPV_nolen (*tmp), sizeof (n->message));
566 if (NULL != (tmp = hv_fetch (hash, "host", 4, 0)))
567 sstrncpy (n->host, SvPV_nolen (*tmp), sizeof (n->host));
569 sstrncpy (n->host, hostname_g, sizeof (n->host));
571 if (NULL != (tmp = hv_fetch (hash, "plugin", 6, 0)))
572 sstrncpy (n->plugin, SvPV_nolen (*tmp), sizeof (n->plugin));
574 if (NULL != (tmp = hv_fetch (hash, "plugin_instance", 15, 0)))
575 sstrncpy (n->plugin_instance, SvPV_nolen (*tmp),
576 sizeof (n->plugin_instance));
578 if (NULL != (tmp = hv_fetch (hash, "type", 4, 0)))
579 sstrncpy (n->type, SvPV_nolen (*tmp), sizeof (n->type));
581 if (NULL != (tmp = hv_fetch (hash, "type_instance", 13, 0)))
582 sstrncpy (n->type_instance, SvPV_nolen (*tmp),
583 sizeof (n->type_instance));
586 while (NULL != (tmp = hv_fetch (hash, "meta", 4, 0))) {
587 if (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp))))) {
588 log_warn ("hv2notification: Ignoring invalid meta information.");
592 if (0 != av2notification_meta (aTHX_ (AV *)SvRV (*tmp), &n->meta)) {
593 plugin_notification_meta_free (n->meta);
600 } /* static int hv2notification (pTHX_ HV *, notification_t *) */
602 static int data_set2av (pTHX_ data_set_t *ds, AV *array)
604 if ((NULL == ds) || (NULL == array))
607 av_extend (array, ds->ds_num);
609 for (size_t i = 0; i < ds->ds_num; ++i) {
610 HV *source = newHV ();
612 if (NULL == hv_store (source, "name", 4,
613 newSVpv (ds->ds[i].name, 0), 0))
616 if (NULL == hv_store (source, "type", 4, newSViv (ds->ds[i].type), 0))
619 if (! isnan (ds->ds[i].min))
620 if (NULL == hv_store (source, "min", 3,
621 newSVnv (ds->ds[i].min), 0))
624 if (! isnan (ds->ds[i].max))
625 if (NULL == hv_store (source, "max", 3,
626 newSVnv (ds->ds[i].max), 0))
629 if (NULL == av_store (array, i, newRV_noinc ((SV *)source)))
633 } /* static int data_set2av (data_set_t *, AV *) */
635 static int value_list2hv (pTHX_ value_list_t *vl, data_set_t *ds, HV *hash)
640 if ((NULL == vl) || (NULL == ds) || (NULL == hash))
644 /* av_extend takes the last *index* to which the array should be extended. */
645 av_extend (values, vl->values_len - 1);
647 assert (ds->ds_num == vl->values_len);
648 for (i = 0; i < vl->values_len; ++i) {
651 if (DS_TYPE_COUNTER == ds->ds[i].type)
652 val = newSViv (vl->values[i].counter);
653 else if (DS_TYPE_GAUGE == ds->ds[i].type)
654 val = newSVnv (vl->values[i].gauge);
655 else if (DS_TYPE_DERIVE == ds->ds[i].type)
656 val = newSViv (vl->values[i].derive);
657 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
658 val = newSViv (vl->values[i].absolute);
660 if (NULL == av_store (values, i, val)) {
666 if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0))
671 double t = CDTIME_T_TO_DOUBLE (vl->time);
672 if (NULL == hv_store (hash, "time", 4, newSVnv (t), 0))
677 double t = CDTIME_T_TO_DOUBLE (vl->interval);
678 if (NULL == hv_store (hash, "interval", 8, newSVnv (t), 0))
682 if ('\0' != vl->host[0])
683 if (NULL == hv_store (hash, "host", 4, newSVpv (vl->host, 0), 0))
686 if ('\0' != vl->plugin[0])
687 if (NULL == hv_store (hash, "plugin", 6, newSVpv (vl->plugin, 0), 0))
690 if ('\0' != vl->plugin_instance[0])
691 if (NULL == hv_store (hash, "plugin_instance", 15,
692 newSVpv (vl->plugin_instance, 0), 0))
695 if ('\0' != vl->type[0])
696 if (NULL == hv_store (hash, "type", 4, newSVpv (vl->type, 0), 0))
699 if ('\0' != vl->type_instance[0])
700 if (NULL == hv_store (hash, "type_instance", 13,
701 newSVpv (vl->type_instance, 0), 0))
704 } /* static int value2av (value_list_t *, data_set_t *, HV *) */
706 static int notification_meta2av (pTHX_ notification_meta_t *meta, AV *array)
715 av_extend (array, meta_num);
717 for (int i = 0; NULL != meta; meta = meta->next, ++i) {
721 if (NULL == hv_store (m, "name", 4, newSVpv (meta->name, 0), 0))
724 if (NM_TYPE_STRING == meta->type)
725 value = newSVpv (meta->nm_value.nm_string, 0);
726 else if (NM_TYPE_SIGNED_INT == meta->type)
727 value = newSViv (meta->nm_value.nm_signed_int);
728 else if (NM_TYPE_UNSIGNED_INT == meta->type)
729 value = newSVuv (meta->nm_value.nm_unsigned_int);
730 else if (NM_TYPE_DOUBLE == meta->type)
731 value = newSVnv (meta->nm_value.nm_double);
732 else if (NM_TYPE_BOOLEAN == meta->type)
733 value = meta->nm_value.nm_boolean ? &PL_sv_yes : &PL_sv_no;
737 if (NULL == hv_store (m, "value", 5, value, 0)) {
742 if (NULL == av_store (array, i, newRV_noinc ((SV *)m))) {
749 } /* static int notification_meta2av (notification_meta_t *, AV *) */
751 static int notification2hv (pTHX_ notification_t *n, HV *hash)
753 if (NULL == hv_store (hash, "severity", 8, newSViv (n->severity), 0))
758 double t = CDTIME_T_TO_DOUBLE (n->time);
759 if (NULL == hv_store (hash, "time", 4, newSVnv (t), 0))
763 if ('\0' != *n->message)
764 if (NULL == hv_store (hash, "message", 7, newSVpv (n->message, 0), 0))
767 if ('\0' != *n->host)
768 if (NULL == hv_store (hash, "host", 4, newSVpv (n->host, 0), 0))
771 if ('\0' != *n->plugin)
772 if (NULL == hv_store (hash, "plugin", 6, newSVpv (n->plugin, 0), 0))
775 if ('\0' != *n->plugin_instance)
776 if (NULL == hv_store (hash, "plugin_instance", 15,
777 newSVpv (n->plugin_instance, 0), 0))
780 if ('\0' != *n->type)
781 if (NULL == hv_store (hash, "type", 4, newSVpv (n->type, 0), 0))
784 if ('\0' != *n->type_instance)
785 if (NULL == hv_store (hash, "type_instance", 13,
786 newSVpv (n->type_instance, 0), 0))
789 if (NULL != n->meta) {
791 if ((0 != notification_meta2av (aTHX_ n->meta, meta))
792 || (NULL == hv_store (hash, "meta", 4,
793 newRV_noinc ((SV *)meta), 0))) {
800 } /* static int notification2hv (notification_t *, HV *) */
802 static int oconfig_item2hv (pTHX_ oconfig_item_t *ci, HV *hash)
807 if (NULL == hv_store (hash, "key", 3, newSVpv (ci->key, 0), 0))
811 if (0 < ci->values_num)
812 av_extend (values, ci->values_num);
814 if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0)) {
820 for (int i = 0; i < ci->values_num; ++i) {
823 switch (ci->values[i].type) {
824 case OCONFIG_TYPE_STRING:
825 value = newSVpv (ci->values[i].value.string, 0);
827 case OCONFIG_TYPE_NUMBER:
828 value = newSVnv ((NV)ci->values[i].value.number);
830 case OCONFIG_TYPE_BOOLEAN:
831 value = ci->values[i].value.boolean ? &PL_sv_yes : &PL_sv_no;
834 log_err ("oconfig_item2hv: Invalid value type %i.",
836 value = &PL_sv_undef;
839 if (NULL == av_store (values, i, value)) {
845 /* ignoring 'parent' member which is uninteresting in this case */
848 if (0 < ci->children_num)
849 av_extend (children, ci->children_num);
851 if (NULL == hv_store (hash, "children", 8, newRV_noinc ((SV *)children), 0)) {
857 for (int i = 0; i < ci->children_num; ++i) {
858 HV *child = newHV ();
860 if (0 != oconfig_item2hv (aTHX_ ci->children + i, child)) {
866 if (NULL == av_store (children, i, newRV_noinc ((SV *)child))) {
873 } /* static int oconfig_item2hv (pTHX_ oconfig_item_t *, HV *) */
876 * Internal functions.
879 static char *get_module_name (char *buf, size_t buf_len, const char *module) {
881 if (base_name[0] == '\0')
882 status = ssnprintf (buf, buf_len, "%s", module);
884 status = ssnprintf (buf, buf_len, "%s::%s", base_name, module);
885 if ((status < 0) || ((unsigned int)status >= buf_len))
888 } /* char *get_module_name */
891 * Add a plugin's data set definition.
893 static int pplugin_register_data_set (pTHX_ char *name, AV *dataset)
899 if ((NULL == name) || (NULL == dataset))
902 if (0 != av2data_set (aTHX_ dataset, name, &ds))
905 ret = plugin_register_data_set (&ds);
909 } /* static int pplugin_register_data_set (char *, SV *) */
912 * Remove a plugin's data set definition.
914 static int pplugin_unregister_data_set (char *name)
918 return plugin_unregister_data_set (name);
919 } /* static int pplugin_unregister_data_set (char *) */
922 * Submit the values to the write functions.
924 static int pplugin_dispatch_values (pTHX_ HV *values)
926 value_list_t vl = VALUE_LIST_INIT;
933 if (0 != hv2value_list (aTHX_ values, &vl))
936 ret = plugin_dispatch_values (&vl);
940 } /* static int pplugin_dispatch_values (char *, HV *) */
943 * Submit the values to a single write function.
945 static int pplugin_write (pTHX_ const char *plugin, AV *data_set, HV *values)
948 value_list_t vl = VALUE_LIST_INIT;
955 if (0 != hv2value_list (aTHX_ values, &vl))
958 if ((NULL != data_set)
959 && (0 != av2data_set (aTHX_ data_set, vl.type, &ds)))
962 ret = plugin_write (plugin, NULL == data_set ? NULL : &ds, &vl);
964 log_warn ("Dispatching value to plugin \"%s\" failed with status %i.",
965 NULL == plugin ? "<any>" : plugin, ret);
967 if (NULL != data_set)
971 } /* static int pplugin_write (const char *plugin, HV *, HV *) */
974 * Dispatch a notification.
976 static int pplugin_dispatch_notification (pTHX_ HV *notif)
978 notification_t n = { 0 };
985 if (0 != hv2notification (aTHX_ notif, &n))
988 ret = plugin_dispatch_notification (&n);
989 plugin_notification_meta_free (n.meta);
991 } /* static int pplugin_dispatch_notification (HV *) */
994 * Call perl sub with thread locking flags handled.
996 static int call_pv_locked (pTHX_ const char* sub_name)
1001 c_ithread_t *t = (c_ithread_t *)pthread_getspecific(perl_thr_key);
1002 if (t == NULL) /* thread destroyed */
1005 old_running = t->running;
1009 t->running = old_running;
1013 ret = call_pv (sub_name, G_SCALAR);
1015 t->running = old_running;
1017 } /* static int call_pv_locked (pTHX, *sub_name) */
1020 * Call all working functions of the given type.
1022 static int pplugin_call_all (pTHX_ int type, ...)
1031 if ((type < 0) || (type >= PLUGIN_TYPES))
1034 va_start (ap, type);
1041 XPUSHs (sv_2mortal (newSViv ((IV)type)));
1043 if (PLUGIN_WRITE == type) {
1045 * $_[0] = $plugin_type;
1060 * values => [ $v1, ... ],
1062 * host => $hostname,
1063 * plugin => $plugin,
1065 * plugin_instance => $instance,
1066 * type_instance => $type_instance
1075 ds = va_arg (ap, data_set_t *);
1076 vl = va_arg (ap, value_list_t *);
1078 if (-1 == data_set2av (aTHX_ ds, pds)) {
1081 pds = (AV *)&PL_sv_undef;
1085 if (-1 == value_list2hv (aTHX_ vl, ds, pvl)) {
1088 pvl = (HV *)&PL_sv_undef;
1092 XPUSHs (sv_2mortal (newSVpv (ds->type, 0)));
1093 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1094 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1096 else if (PLUGIN_LOG == type) {
1102 XPUSHs (sv_2mortal (newSViv (va_arg (ap, int))));
1103 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1105 else if (PLUGIN_NOTIF == type) {
1109 * severity => $severity,
1113 * plugin => $plugin,
1115 * plugin_instance => $instance,
1116 * type_instance => $type_instance
1120 HV *notif = newHV ();
1122 n = va_arg (ap, notification_t *);
1124 if (-1 == notification2hv (aTHX_ n, notif)) {
1127 notif = (HV *)&PL_sv_undef;
1131 XPUSHs (sv_2mortal (newRV_noinc ((SV *)notif)));
1133 else if (PLUGIN_FLUSH == type) {
1138 * $_[1] = $identifier;
1140 timeout = va_arg (ap, cdtime_t);
1142 XPUSHs (sv_2mortal (newSVnv (CDTIME_T_TO_DOUBLE (timeout))));
1143 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1148 retvals = call_pv_locked (aTHX_ "Collectd::plugin_call_all");
1163 } /* static int pplugin_call_all (int, ...) */
1166 * collectd's Perl interpreter based thread implementation.
1168 * This has been inspired by Perl's ithreads introduced in version 5.6.0.
1171 /* must be called with perl_threads->mutex locked */
1172 static void c_ithread_destroy (c_ithread_t *ithread)
1174 dTHXa (ithread->interp);
1176 assert (NULL != perl_threads);
1178 PERL_SET_CONTEXT (aTHX);
1179 log_debug ("Shutting down Perl interpreter %p...", aTHX);
1184 --perl_threads->number_of_threads;
1185 #endif /* COLLECT_DEBUG */
1187 perl_destruct (aTHX);
1190 if (NULL == ithread->prev)
1191 perl_threads->head = ithread->next;
1193 ithread->prev->next = ithread->next;
1195 if (NULL == ithread->next)
1196 perl_threads->tail = ithread->prev;
1198 ithread->next->prev = ithread->prev;
1202 } /* static void c_ithread_destroy (c_ithread_t *) */
1204 static void c_ithread_destructor (void *arg)
1206 c_ithread_t *ithread = (c_ithread_t *)arg;
1207 c_ithread_t *t = NULL;
1209 if (NULL == perl_threads)
1212 pthread_mutex_lock (&perl_threads->mutex);
1214 for (t = perl_threads->head; NULL != t; t = t->next)
1218 /* the ithread no longer exists */
1221 pthread_mutex_unlock (&perl_threads->mutex);
1225 c_ithread_destroy (ithread);
1227 pthread_mutex_unlock (&perl_threads->mutex);
1229 } /* static void c_ithread_destructor (void *) */
1231 /* must be called with perl_threads->mutex locked */
1232 static c_ithread_t *c_ithread_create (PerlInterpreter *base)
1234 c_ithread_t *t = NULL;
1237 assert (NULL != perl_threads);
1239 t = smalloc (sizeof (*t));
1240 memset (t, 0, sizeof (c_ithread_t));
1242 t->interp = (NULL == base)
1244 : perl_clone (base, CLONEf_KEEP_PTR_TABLE);
1248 if ((NULL != base) && (NULL != PL_endav)) {
1249 av_clear (PL_endav);
1250 av_undef (PL_endav);
1255 ++perl_threads->number_of_threads;
1256 #endif /* COLLECT_DEBUG */
1260 if (NULL == perl_threads->tail) {
1261 perl_threads->head = t;
1265 perl_threads->tail->next = t;
1266 t->prev = perl_threads->tail;
1269 t->pthread = pthread_self();
1272 perl_threads->tail = t;
1274 pthread_setspecific (perl_thr_key, (const void *)t);
1276 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
1279 * Filter chains implementation.
1282 static int fc_call (pTHX_ int type, int cb_type, pfc_user_data_t *data, ...)
1289 notification_meta_t **meta = NULL;
1294 if ((type < 0) || (type >= FC_TYPES))
1297 if ((cb_type < 0) || (cb_type >= FC_CB_TYPES))
1300 va_start (ap, data);
1307 XPUSHs (sv_2mortal (newSViv ((IV)type)));
1308 XPUSHs (sv_2mortal (newSVpv (data->name, 0)));
1309 XPUSHs (sv_2mortal (newSViv ((IV)cb_type)));
1311 if (FC_CB_CREATE == cb_type) {
1314 * $_[1] = $user_data;
1317 HV *config = newHV ();
1319 ci = va_arg (ap, oconfig_item_t *);
1321 if (0 != oconfig_item2hv (aTHX_ ci, config)) {
1324 config = (HV *)&PL_sv_undef;
1328 XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
1330 else if (FC_CB_DESTROY == cb_type) {
1332 * $_[1] = $user_data;
1335 /* nothing to be done - the user data pointer
1336 * is pushed onto the stack later */
1338 else if (FC_CB_EXEC == cb_type) {
1343 * $_[3] = $user_data;
1351 ds = va_arg (ap, data_set_t *);
1352 vl = va_arg (ap, value_list_t *);
1353 meta = va_arg (ap, notification_meta_t **);
1355 if (0 != data_set2av (aTHX_ ds, pds)) {
1358 pds = (AV *)&PL_sv_undef;
1362 if (0 != value_list2hv (aTHX_ vl, ds, pvl)) {
1365 pvl = (HV *)&PL_sv_undef;
1372 if (0 != notification_meta2av (aTHX_ *meta, pmeta)) {
1375 pmeta = (AV *)&PL_sv_undef;
1380 pmeta = (AV *)&PL_sv_undef;
1383 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1384 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1385 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pmeta)));
1388 XPUSHs (sv_2mortal (newRV_inc (data->user_data)));
1392 retvals = call_pv_locked (aTHX_ "Collectd::fc_call");
1394 if ((FC_CB_EXEC == cb_type) && (meta != NULL)) {
1395 assert (pmeta != NULL);
1397 plugin_notification_meta_free (*meta);
1398 av2notification_meta (aTHX_ pmeta, meta);
1405 /* the exec callbacks return a status, while
1406 * the others return a boolean value */
1407 if (FC_CB_EXEC == cb_type)
1409 else if (! SvTRUE (tmp))
1419 } /* static int fc_call (int, int, pfc_user_data_t *, ...) */
1421 static int fc_create (int type, const oconfig_item_t *ci, void **user_data)
1423 pfc_user_data_t *data;
1429 if (NULL == perl_threads)
1433 c_ithread_t *t = NULL;
1435 pthread_mutex_lock (&perl_threads->mutex);
1436 t = c_ithread_create (perl_threads->head->interp);
1437 pthread_mutex_unlock (&perl_threads->mutex);
1442 log_debug ("fc_create: c_ithread: interp = %p (active threads: %i)",
1443 aTHX, perl_threads->number_of_threads);
1445 if ((1 != ci->values_num)
1446 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1447 log_warn ("A \"%s\" block expects a single string argument.",
1448 (FC_MATCH == type) ? "Match" : "Target");
1452 data = smalloc (sizeof (*data));
1453 data->name = sstrdup (ci->values[0].value.string);
1454 data->user_data = newSV (0);
1456 ret = fc_call (aTHX_ type, FC_CB_CREATE, data, ci);
1459 PFC_USER_DATA_FREE (data);
1463 } /* static int fc_create (int, const oconfig_item_t *, void **) */
1465 static int fc_destroy (int type, void **user_data)
1467 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1473 if ((NULL == perl_threads) || (NULL == data))
1477 c_ithread_t *t = NULL;
1479 pthread_mutex_lock (&perl_threads->mutex);
1480 t = c_ithread_create (perl_threads->head->interp);
1481 pthread_mutex_unlock (&perl_threads->mutex);
1486 log_debug ("fc_destroy: c_ithread: interp = %p (active threads: %i)",
1487 aTHX, perl_threads->number_of_threads);
1489 ret = fc_call (aTHX_ type, FC_CB_DESTROY, data);
1491 PFC_USER_DATA_FREE (data);
1494 } /* static int fc_destroy (int, void **) */
1496 static int fc_exec (int type, const data_set_t *ds, const value_list_t *vl,
1497 notification_meta_t **meta, void **user_data)
1499 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1503 if (NULL == perl_threads)
1506 assert (NULL != data);
1509 c_ithread_t *t = NULL;
1511 pthread_mutex_lock (&perl_threads->mutex);
1512 t = c_ithread_create (perl_threads->head->interp);
1513 pthread_mutex_unlock (&perl_threads->mutex);
1518 log_debug ("fc_exec: c_ithread: interp = %p (active threads: %i)",
1519 aTHX, perl_threads->number_of_threads);
1521 return fc_call (aTHX_ type, FC_CB_EXEC, data, ds, vl, meta);
1522 } /* static int fc_exec (int, const data_set_t *, const value_list_t *,
1523 notification_meta_t **, void **) */
1525 static int pmatch_create (const oconfig_item_t *ci, void **user_data)
1527 return fc_create (FC_MATCH, ci, user_data);
1528 } /* static int pmatch_create (const oconfig_item_t *, void **) */
1530 static int pmatch_destroy (void **user_data)
1532 return fc_destroy (FC_MATCH, user_data);
1533 } /* static int pmatch_destroy (void **) */
1535 static int pmatch_match (const data_set_t *ds, const value_list_t *vl,
1536 notification_meta_t **meta, void **user_data)
1538 return fc_exec (FC_MATCH, ds, vl, meta, user_data);
1539 } /* static int pmatch_match (const data_set_t *, const value_list_t *,
1540 notification_meta_t **, void **) */
1542 static match_proc_t pmatch = {
1543 pmatch_create, pmatch_destroy, pmatch_match
1546 static int ptarget_create (const oconfig_item_t *ci, void **user_data)
1548 return fc_create (FC_TARGET, ci, user_data);
1549 } /* static int ptarget_create (const oconfig_item_t *, void **) */
1551 static int ptarget_destroy (void **user_data)
1553 return fc_destroy (FC_TARGET, user_data);
1554 } /* static int ptarget_destroy (void **) */
1556 static int ptarget_invoke (const data_set_t *ds, value_list_t *vl,
1557 notification_meta_t **meta, void **user_data)
1559 return fc_exec (FC_TARGET, ds, vl, meta, user_data);
1560 } /* static int ptarget_invoke (const data_set_t *, value_list_t *,
1561 notification_meta_t **, void **) */
1563 static target_proc_t ptarget = {
1564 ptarget_create, ptarget_destroy, ptarget_invoke
1568 * Exported Perl API.
1572 * Collectd::plugin_register_data_set (type, dataset).
1575 * type of the dataset
1578 * dataset to be registered
1580 static XS (Collectd_plugin_register_ds)
1587 log_warn ("Using plugin_register() to register new data-sets is "
1588 "deprecated - add new entries to a custom types.db instead.");
1591 log_err ("Usage: Collectd::plugin_register_data_set(type, dataset)");
1595 log_debug ("Collectd::plugin_register_data_set: "
1596 "type = \"%s\", dataset = \"%s\"",
1597 SvPV_nolen (ST (0)), SvPV_nolen (ST (1)));
1601 if (SvROK (data) && (SVt_PVAV == SvTYPE (SvRV (data)))) {
1602 ret = pplugin_register_data_set (aTHX_ SvPV_nolen (ST (0)),
1606 log_err ("Collectd::plugin_register_data_set: Invalid data.");
1614 } /* static XS (Collectd_plugin_register_ds) */
1617 * Collectd::plugin_unregister_data_set (type).
1620 * type of the dataset
1622 static XS (Collectd_plugin_unregister_ds)
1627 log_err ("Usage: Collectd::plugin_unregister_data_set(type)");
1631 log_debug ("Collectd::plugin_unregister_data_set: type = \"%s\"",
1632 SvPV_nolen (ST (0)));
1634 if (0 == pplugin_unregister_data_set (SvPV_nolen (ST (0))))
1638 } /* static XS (Collectd_plugin_register_ds) */
1641 * Collectd::plugin_dispatch_values (name, values).
1644 * name of the plugin
1647 * value list to submit
1649 static XS (Collectd_plugin_dispatch_values)
1658 log_err ("Usage: Collectd::plugin_dispatch_values(values)");
1662 log_debug ("Collectd::plugin_dispatch_values: values=\"%s\"",
1663 SvPV_nolen (ST (/* stack index = */ 0)));
1665 values = ST (/* stack index = */ 0);
1670 /* Make sure the argument is a hash reference. */
1671 if (! (SvROK (values) && (SVt_PVHV == SvTYPE (SvRV (values))))) {
1672 log_err ("Collectd::plugin_dispatch_values: Invalid values.");
1676 ret = pplugin_dispatch_values (aTHX_ (HV *)SvRV (values));
1682 } /* static XS (Collectd_plugin_dispatch_values) */
1685 * Collectd::plugin_get_interval ().
1687 static XS (Collectd_plugin_get_interval)
1691 /* make sure we don't get any unused variable warnings for 'items';
1692 * don't abort, though */
1694 log_err ("Usage: Collectd::plugin_get_interval()");
1696 XSRETURN_NV ((NV) CDTIME_T_TO_DOUBLE (plugin_get_interval ()));
1697 } /* static XS (Collectd_plugin_get_interval) */
1699 /* Collectd::plugin_write (plugin, ds, vl).
1702 * name of the plugin to call, may be 'undef'
1705 * data-set that describes the submitted values, may be 'undef'
1708 * value-list to be written
1710 static XS (Collectd__plugin_write)
1721 log_err ("Usage: Collectd::plugin_write(plugin, ds, vl)");
1725 log_debug ("Collectd::plugin_write: plugin=\"%s\", ds=\"%s\", vl=\"%s\"",
1726 SvPV_nolen (ST (0)), SvOK (ST (1)) ? SvPV_nolen (ST (1)) : "",
1727 SvPV_nolen (ST (2)));
1729 if (! SvOK (ST (0)))
1732 plugin = SvPV_nolen (ST (0));
1735 if (SvROK (ds) && (SVt_PVAV == SvTYPE (SvRV (ds))))
1736 ds_array = (AV *)SvRV (ds);
1737 else if (! SvOK (ds))
1740 log_err ("Collectd::plugin_write: Invalid data-set.");
1745 if (! (SvROK (vl) && (SVt_PVHV == SvTYPE (SvRV (vl))))) {
1746 log_err ("Collectd::plugin_write: Invalid value-list.");
1750 ret = pplugin_write (aTHX_ plugin, ds_array, (HV *)SvRV (vl));
1756 } /* static XS (Collectd__plugin_write) */
1759 * Collectd::_plugin_flush (plugin, timeout, identifier).
1762 * name of the plugin to flush
1765 * timeout to use when flushing the data
1768 * data-set identifier to flush
1770 static XS (Collectd__plugin_flush)
1772 char *plugin = NULL;
1779 log_err ("Usage: Collectd::_plugin_flush(plugin, timeout, id)");
1784 plugin = SvPV_nolen (ST (0));
1787 timeout = (int)SvIV (ST (1));
1790 id = SvPV_nolen (ST (2));
1792 log_debug ("Collectd::_plugin_flush: plugin = \"%s\", timeout = %i, "
1793 "id = \"%s\"", plugin, timeout, id);
1795 if (0 == plugin_flush (plugin, timeout, id))
1799 } /* static XS (Collectd__plugin_flush) */
1802 * Collectd::plugin_dispatch_notification (notif).
1805 * notification to dispatch
1807 static XS (Collectd_plugin_dispatch_notification)
1816 log_err ("Usage: Collectd::plugin_dispatch_notification(notif)");
1820 log_debug ("Collectd::plugin_dispatch_notification: notif = \"%s\"",
1821 SvPV_nolen (ST (0)));
1825 if (! (SvROK (notif) && (SVt_PVHV == SvTYPE (SvRV (notif))))) {
1826 log_err ("Collectd::plugin_dispatch_notification: Invalid notif.");
1830 ret = pplugin_dispatch_notification (aTHX_ (HV *)SvRV (notif));
1836 } /* static XS (Collectd_plugin_dispatch_notification) */
1839 * Collectd::plugin_log (level, message).
1842 * log level (LOG_DEBUG, ... LOG_ERR)
1847 static XS (Collectd_plugin_log)
1852 log_err ("Usage: Collectd::plugin_log(level, message)");
1856 plugin_log (SvIV (ST (0)), "%s", SvPV_nolen (ST (1)));
1858 } /* static XS (Collectd_plugin_log) */
1861 * Collectd::_fc_register (type, name)
1869 static XS (Collectd__fc_register)
1879 log_err ("Usage: Collectd::_fc_register(type, name)");
1883 type = SvIV (ST (0));
1884 name = SvPV_nolen (ST (1));
1886 if (FC_MATCH == type)
1887 ret = fc_register_match (name, pmatch);
1888 else if (FC_TARGET == type)
1889 ret = fc_register_target (name, ptarget);
1895 } /* static XS (Collectd_fc_register) */
1898 * Collectd::call_by_name (...).
1900 * Call a Perl sub identified by its name passed through $Collectd::cb_name.
1902 static XS (Collectd_call_by_name)
1907 if (NULL == (tmp = get_sv ("Collectd::cb_name", 0))) {
1908 sv_setpv (get_sv ("@", 1), "cb_name has not been set");
1913 name = SvPV_nolen (tmp);
1915 if (NULL == get_cv (name, 0)) {
1916 sv_setpvf (get_sv ("@", 1), "unknown callback \"%s\"", name);
1921 /* simply pass on the subroutine call without touching the stack,
1922 * thus leaving any arguments and return values in place */
1924 } /* static XS (Collectd_call_by_name) */
1927 * Interface to collectd.
1930 static int perl_init (void)
1935 if (NULL == perl_threads)
1939 c_ithread_t *t = NULL;
1941 pthread_mutex_lock (&perl_threads->mutex);
1942 t = c_ithread_create (perl_threads->head->interp);
1943 pthread_mutex_unlock (&perl_threads->mutex);
1948 log_debug ("perl_init: c_ithread: interp = %p (active threads: %i)",
1949 aTHX, perl_threads->number_of_threads);
1951 /* Lock the base thread to avoid race conditions with c_ithread_create().
1952 * See https://github.com/collectd/collectd/issues/9 and
1953 * https://github.com/collectd/collectd/issues/1706 for details.
1955 assert (aTHX == perl_threads->head->interp);
1956 pthread_mutex_lock (&perl_threads->mutex);
1958 status = pplugin_call_all (aTHX_ PLUGIN_INIT);
1960 pthread_mutex_unlock (&perl_threads->mutex);
1963 } /* static int perl_init (void) */
1965 static int perl_read (void)
1969 if (NULL == perl_threads)
1973 c_ithread_t *t = NULL;
1975 pthread_mutex_lock (&perl_threads->mutex);
1976 t = c_ithread_create (perl_threads->head->interp);
1977 pthread_mutex_unlock (&perl_threads->mutex);
1982 /* Assert that we're not running as the base thread. Otherwise, we might
1983 * run into concurrency issues with c_ithread_create(). See
1984 * https://github.com/collectd/collectd/issues/9 for details. */
1985 assert (aTHX != perl_threads->head->interp);
1987 log_debug ("perl_read: c_ithread: interp = %p (active threads: %i)",
1988 aTHX, perl_threads->number_of_threads);
1989 return pplugin_call_all (aTHX_ PLUGIN_READ);
1990 } /* static int perl_read (void) */
1992 static int perl_write (const data_set_t *ds, const value_list_t *vl,
1993 user_data_t __attribute__((unused)) *user_data)
1998 if (NULL == perl_threads)
2002 c_ithread_t *t = NULL;
2004 pthread_mutex_lock (&perl_threads->mutex);
2005 t = c_ithread_create (perl_threads->head->interp);
2006 pthread_mutex_unlock (&perl_threads->mutex);
2011 /* Lock the base thread if this is not called from one of the read threads
2012 * to avoid race conditions with c_ithread_create(). See
2013 * https://github.com/collectd/collectd/issues/9 for details. */
2014 if (aTHX == perl_threads->head->interp)
2015 pthread_mutex_lock (&perl_threads->mutex);
2017 log_debug ("perl_write: c_ithread: interp = %p (active threads: %i)",
2018 aTHX, perl_threads->number_of_threads);
2019 status = pplugin_call_all (aTHX_ PLUGIN_WRITE, ds, vl);
2021 if (aTHX == perl_threads->head->interp)
2022 pthread_mutex_unlock (&perl_threads->mutex);
2025 } /* static int perl_write (const data_set_t *, const value_list_t *) */
2027 static void perl_log (int level, const char *msg,
2028 user_data_t __attribute__((unused)) *user_data)
2032 if (NULL == perl_threads)
2036 c_ithread_t *t = NULL;
2038 pthread_mutex_lock (&perl_threads->mutex);
2039 t = c_ithread_create (perl_threads->head->interp);
2040 pthread_mutex_unlock (&perl_threads->mutex);
2045 /* Lock the base thread if this is not called from one of the read threads
2046 * to avoid race conditions with c_ithread_create(). See
2047 * https://github.com/collectd/collectd/issues/9 for details.
2050 if (aTHX == perl_threads->head->interp)
2051 pthread_mutex_lock (&perl_threads->mutex);
2053 pplugin_call_all (aTHX_ PLUGIN_LOG, level, msg);
2055 if (aTHX == perl_threads->head->interp)
2056 pthread_mutex_unlock (&perl_threads->mutex);
2059 } /* static void perl_log (int, const char *) */
2061 static int perl_notify (const notification_t *notif,
2062 user_data_t __attribute__((unused)) *user_data)
2066 if (NULL == perl_threads)
2070 c_ithread_t *t = NULL;
2072 pthread_mutex_lock (&perl_threads->mutex);
2073 t = c_ithread_create (perl_threads->head->interp);
2074 pthread_mutex_unlock (&perl_threads->mutex);
2078 return pplugin_call_all (aTHX_ PLUGIN_NOTIF, notif);
2079 } /* static int perl_notify (const notification_t *) */
2081 static int perl_flush (cdtime_t timeout, const char *identifier,
2082 user_data_t __attribute__((unused)) *user_data)
2086 if (NULL == perl_threads)
2090 c_ithread_t *t = NULL;
2092 pthread_mutex_lock (&perl_threads->mutex);
2093 t = c_ithread_create (perl_threads->head->interp);
2094 pthread_mutex_unlock (&perl_threads->mutex);
2098 return pplugin_call_all (aTHX_ PLUGIN_FLUSH, timeout, identifier);
2099 } /* static int perl_flush (const int) */
2101 static int perl_shutdown (void)
2108 plugin_unregister_complex_config ("perl");
2110 if (NULL == perl_threads)
2114 pthread_mutex_lock (&perl_threads->mutex);
2115 t = c_ithread_create (perl_threads->head->interp);
2116 pthread_mutex_unlock (&perl_threads->mutex);
2121 log_debug ("perl_shutdown: c_ithread: interp = %p (active threads: %i)",
2122 aTHX, perl_threads->number_of_threads);
2124 plugin_unregister_log ("perl");
2125 plugin_unregister_notification ("perl");
2126 plugin_unregister_init ("perl");
2127 plugin_unregister_read ("perl");
2128 plugin_unregister_write ("perl");
2129 plugin_unregister_flush ("perl");
2131 ret = pplugin_call_all (aTHX_ PLUGIN_SHUTDOWN);
2133 pthread_mutex_lock (&perl_threads->mutex);
2134 t = perl_threads->tail;
2137 struct timespec ts_wait;
2138 c_ithread_t *thr = t;
2140 /* the pointer has to be advanced before destroying
2141 * the thread as this will free the memory */
2146 /* Give some time to thread to exit from Perl interpreter */
2147 WARNING ("perl shutdown: Thread is running inside Perl. Waiting.");
2149 ts_wait.tv_nsec = 500000;
2150 nanosleep (&ts_wait, NULL);
2153 pthread_kill (thr->pthread, SIGTERM);
2154 ERROR ("perl shutdown: Thread hangs inside Perl. Thread killed.");
2156 c_ithread_destroy (thr);
2159 pthread_mutex_unlock (&perl_threads->mutex);
2160 pthread_mutex_destroy (&perl_threads->mutex);
2161 pthread_mutexattr_destroy (&perl_threads->mutexattr);
2163 sfree (perl_threads);
2165 pthread_key_delete (perl_thr_key);
2169 plugin_unregister_shutdown ("perl");
2171 } /* static void perl_shutdown (void) */
2174 * Access functions for global variables.
2176 * These functions implement the "magic" used to access
2177 * the global variables from Perl.
2180 static int g_pv_get (pTHX_ SV *var, MAGIC *mg)
2182 char *pv = mg->mg_ptr;
2185 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
2187 static int g_pv_set (pTHX_ SV *var, MAGIC *mg)
2189 char *pv = mg->mg_ptr;
2190 sstrncpy (pv, SvPV_nolen (var), DATA_MAX_NAME_LEN);
2192 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
2194 static int g_interval_get (pTHX_ SV *var, MAGIC *mg)
2196 log_warn ("Accessing $interval_g is deprecated (and might not "
2197 "give the desired results) - plugin_get_interval() should "
2198 "be used instead.");
2199 sv_setnv (var, CDTIME_T_TO_DOUBLE (interval_g));
2201 } /* static int g_interval_get (pTHX_ SV *, MAGIC *) */
2203 static int g_interval_set (pTHX_ SV *var, MAGIC *mg)
2205 double nv = (double)SvNV (var);
2206 log_warn ("Accessing $interval_g is deprecated (and might not "
2207 "give the desired results) - plugin_get_interval() should "
2208 "be used instead.");
2209 interval_g = DOUBLE_TO_CDTIME_T (nv);
2211 } /* static int g_interval_set (pTHX_ SV *, MAGIC *) */
2213 static MGVTBL g_pv_vtbl = {
2214 g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL
2215 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2219 static MGVTBL g_interval_vtbl = {
2220 g_interval_get, g_interval_set, NULL, NULL, NULL, NULL, NULL
2221 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2226 /* bootstrap the Collectd module */
2227 static void xs_init (pTHX)
2231 char *file = __FILE__;
2235 /* enable usage of Perl modules using shared libraries */
2236 newXS ("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2239 for (int i = 0; NULL != api[i].f; ++i)
2240 newXS (api[i].name, api[i].f, file);
2242 stash = gv_stashpv ("Collectd", 1);
2244 /* export "constants" */
2245 for (int i = 0; '\0' != constants[i].name[0]; ++i)
2246 newCONSTSUB (stash, constants[i].name, newSViv (constants[i].value));
2248 /* export global variables
2249 * by adding "magic" to the SV's representing the globale variables
2250 * perl is able to automagically call the get/set function when
2251 * accessing any such variable (this is basically the same as using
2253 /* global strings */
2254 for (int i = 0; '\0' != g_strings[i].name[0]; ++i) {
2255 tmp = get_sv (g_strings[i].name, 1);
2256 sv_magicext (tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl,
2257 g_strings[i].var, 0);
2260 tmp = get_sv ("Collectd::interval_g", /* create = */ 1);
2261 sv_magicext (tmp, NULL, /* how = */ PERL_MAGIC_ext,
2262 /* vtbl = */ &g_interval_vtbl,
2263 /* name = */ NULL, /* namelen = */ 0);
2266 } /* static void xs_init (pTHX) */
2268 /* Initialize the global Perl interpreter. */
2269 static int init_pi (int argc, char **argv)
2273 if (NULL != perl_threads)
2276 log_info ("Initializing Perl interpreter...");
2279 for (int i = 0; i < argc; ++i)
2280 log_debug ("argv[%i] = \"%s\"", i, argv[i]);
2282 #endif /* COLLECT_DEBUG */
2284 if (0 != pthread_key_create (&perl_thr_key, c_ithread_destructor)) {
2285 log_err ("init_pi: pthread_key_create failed");
2287 /* this must not happen - cowardly giving up if it does */
2292 /* On FreeBSD, PERL_SYS_INIT3 expands to some expression which
2293 * triggers a "value computed is not used" warning by gcc. */
2296 PERL_SYS_INIT3 (&argc, &argv, &environ);
2298 perl_threads = smalloc (sizeof (*perl_threads));
2299 memset (perl_threads, 0, sizeof (c_ithread_list_t));
2301 pthread_mutexattr_init(&perl_threads->mutexattr);
2302 pthread_mutexattr_settype(&perl_threads->mutexattr, PTHREAD_MUTEX_RECURSIVE);
2303 pthread_mutex_init (&perl_threads->mutex, &perl_threads->mutexattr);
2304 /* locking the mutex should not be necessary at this point
2305 * but let's just do it for the sake of completeness */
2306 pthread_mutex_lock (&perl_threads->mutex);
2308 perl_threads->head = c_ithread_create (NULL);
2309 perl_threads->tail = perl_threads->head;
2311 if (NULL == (perl_threads->head->interp = perl_alloc ())) {
2312 log_err ("init_pi: Not enough memory.");
2316 aTHX = perl_threads->head->interp;
2317 pthread_mutex_unlock (&perl_threads->mutex);
2319 perl_construct (aTHX);
2321 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
2323 if (0 != perl_parse (aTHX_ xs_init, argc, argv, NULL)) {
2324 SV *err = get_sv ("@", 1);
2325 log_err ("init_pi: Unable to bootstrap Collectd: %s",
2328 perl_destruct (perl_threads->head->interp);
2329 perl_free (perl_threads->head->interp);
2330 sfree (perl_threads);
2332 pthread_key_delete (perl_thr_key);
2336 /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
2337 sv_setpv (get_sv ("0", 0), "collectd");
2341 plugin_register_log ("perl", perl_log, /* user_data = */ NULL);
2342 plugin_register_notification ("perl", perl_notify,
2343 /* user_data = */ NULL);
2344 plugin_register_init ("perl", perl_init);
2346 plugin_register_read ("perl", perl_read);
2348 plugin_register_write ("perl", perl_write, /* user_data = */ NULL);
2349 plugin_register_flush ("perl", perl_flush, /* user_data = */ NULL);
2350 plugin_register_shutdown ("perl", perl_shutdown);
2352 } /* static int init_pi (const char **, const int) */
2355 * LoadPlugin "<Plugin>"
2357 static int perl_config_loadplugin (pTHX_ oconfig_item_t *ci)
2359 char module_name[DATA_MAX_NAME_LEN];
2363 if ((0 != ci->children_num) || (1 != ci->values_num)
2364 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2365 log_err ("LoadPlugin expects a single string argument.");
2369 value = ci->values[0].value.string;
2371 if (NULL == get_module_name (module_name, sizeof (module_name), value)) {
2372 log_err ("Invalid module name %s", value);
2376 if (0 != init_pi (perl_argc, perl_argv))
2379 assert (NULL != perl_threads);
2380 assert (NULL != perl_threads->head);
2382 aTHX = perl_threads->head->interp;
2384 log_debug ("perl_config: Loading Perl plugin \"%s\"", value);
2385 load_module (PERL_LOADMOD_NOIMPORT,
2386 newSVpv (module_name, strlen (module_name)), Nullsv);
2388 } /* static int perl_config_loadplugin (oconfig_item_it *) */
2393 static int perl_config_basename (pTHX_ oconfig_item_t *ci)
2397 if ((0 != ci->children_num) || (1 != ci->values_num)
2398 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2399 log_err ("BaseName expects a single string argument.");
2403 value = ci->values[0].value.string;
2405 log_debug ("perl_config: Setting plugin basename to \"%s\"", value);
2406 sstrncpy (base_name, value, sizeof (base_name));
2408 } /* static int perl_config_basename (oconfig_item_it *) */
2411 * EnableDebugger "<Package>"|""
2413 static int perl_config_enabledebugger (pTHX_ oconfig_item_t *ci)
2417 if ((0 != ci->children_num) || (1 != ci->values_num)
2418 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2419 log_err ("EnableDebugger expects a single string argument.");
2423 if (NULL != perl_threads) {
2424 log_warn ("EnableDebugger has no effects if used after LoadPlugin.");
2428 value = ci->values[0].value.string;
2430 perl_argv = realloc (perl_argv,
2431 (++perl_argc + 1) * sizeof (char *));
2433 if (NULL == perl_argv) {
2434 log_err ("perl_config: Not enough memory.");
2438 if ('\0' == value[0]) {
2439 perl_argv[perl_argc - 1] = "-d";
2442 perl_argv[perl_argc - 1] = smalloc (strlen (value) + 4);
2443 sstrncpy (perl_argv[perl_argc - 1], "-d:", 4);
2444 sstrncpy (perl_argv[perl_argc - 1] + 3, value, strlen (value) + 1);
2447 perl_argv[perl_argc] = NULL;
2449 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
2452 * IncludeDir "<Dir>"
2454 static int perl_config_includedir (pTHX_ oconfig_item_t *ci)
2458 if ((0 != ci->children_num) || (1 != ci->values_num)
2459 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2460 log_err ("IncludeDir expects a single string argument.");
2464 value = ci->values[0].value.string;
2467 perl_argv = realloc (perl_argv,
2468 (++perl_argc + 1) * sizeof (char *));
2470 if (NULL == perl_argv) {
2471 log_err ("perl_config: Not enough memory.");
2475 perl_argv[perl_argc - 1] = smalloc (strlen (value) + 3);
2476 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
2477 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen (value) + 1);
2479 perl_argv[perl_argc] = NULL;
2482 /* prepend the directory to @INC */
2483 av_unshift (GvAVn (PL_incgv), 1);
2484 av_store (GvAVn (PL_incgv), 0, newSVpv (value, strlen (value)));
2487 } /* static int perl_config_includedir (oconfig_item_it *) */
2492 static int perl_config_plugin (pTHX_ oconfig_item_t *ci)
2502 if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2503 log_err ("LoadPlugin expects a single string argument.");
2507 plugin = ci->values[0].value.string;
2510 if (0 != oconfig_item2hv (aTHX_ ci, config)) {
2514 log_err ("Unable to convert configuration to a Perl hash value.");
2515 config = (HV *)&PL_sv_undef;
2523 XPUSHs (sv_2mortal (newSVpv (plugin, 0)));
2524 XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
2528 retvals = call_pv ("Collectd::_plugin_dispatch_config", G_SCALAR);
2543 } /* static int perl_config_plugin (oconfig_item_it *) */
2545 static int perl_config (oconfig_item_t *ci)
2551 for (int i = 0; i < ci->children_num; ++i) {
2552 oconfig_item_t *c = ci->children + i;
2553 int current_status = 0;
2555 if (NULL != perl_threads)
2557 if ((aTHX = PERL_GET_CONTEXT) == NULL)
2561 if (0 == strcasecmp (c->key, "LoadPlugin"))
2562 current_status = perl_config_loadplugin (aTHX_ c);
2563 else if (0 == strcasecmp (c->key, "BaseName"))
2564 current_status = perl_config_basename (aTHX_ c);
2565 else if (0 == strcasecmp (c->key, "EnableDebugger"))
2566 current_status = perl_config_enabledebugger (aTHX_ c);
2567 else if (0 == strcasecmp (c->key, "IncludeDir"))
2568 current_status = perl_config_includedir (aTHX_ c);
2569 else if (0 == strcasecmp (c->key, "Plugin"))
2570 current_status = perl_config_plugin (aTHX_ c);
2573 log_warn ("Ignoring unknown config key \"%s\".", c->key);
2577 /* fatal error - it's up to perl_config_* to clean up */
2578 if (0 > current_status) {
2579 log_err ("Configuration failed with a fatal error - "
2580 "plugin disabled!");
2581 return current_status;
2584 status += current_status;
2587 } /* static int perl_config (oconfig_item_t *) */
2589 void module_register (void)
2592 perl_argv = smalloc ((perl_argc + 1) * sizeof (*perl_argv));
2594 /* default options for the Perl interpreter */
2596 perl_argv[1] = "-MCollectd";
2597 perl_argv[2] = "-e";
2599 perl_argv[4] = NULL;
2601 plugin_register_complex_config ("perl", perl_config);
2603 } /* void module_register (void) */
2605 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */