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] = "";
184 {"Collectd::plugin_register_data_set", Collectd_plugin_register_ds},
185 {"Collectd::plugin_unregister_data_set", Collectd_plugin_unregister_ds},
186 {"Collectd::plugin_dispatch_values", Collectd_plugin_dispatch_values},
187 {"Collectd::plugin_get_interval", Collectd_plugin_get_interval},
188 {"Collectd::_plugin_write", Collectd__plugin_write},
189 {"Collectd::_plugin_flush", Collectd__plugin_flush},
190 {"Collectd::plugin_dispatch_notification",
191 Collectd_plugin_dispatch_notification},
192 {"Collectd::plugin_log", Collectd_plugin_log},
193 {"Collectd::_fc_register", Collectd__fc_register},
194 {"Collectd::call_by_name", Collectd_call_by_name},
200 } constants[] = {{"Collectd::TYPE_INIT", PLUGIN_INIT},
201 {"Collectd::TYPE_READ", PLUGIN_READ},
202 {"Collectd::TYPE_WRITE", PLUGIN_WRITE},
203 {"Collectd::TYPE_SHUTDOWN", PLUGIN_SHUTDOWN},
204 {"Collectd::TYPE_LOG", PLUGIN_LOG},
205 {"Collectd::TYPE_NOTIF", PLUGIN_NOTIF},
206 {"Collectd::TYPE_FLUSH", PLUGIN_FLUSH},
207 {"Collectd::TYPE_CONFIG", PLUGIN_CONFIG},
208 {"Collectd::TYPE_DATASET", PLUGIN_DATASET},
209 {"Collectd::DS_TYPE_COUNTER", DS_TYPE_COUNTER},
210 {"Collectd::DS_TYPE_GAUGE", DS_TYPE_GAUGE},
211 {"Collectd::DS_TYPE_DERIVE", DS_TYPE_DERIVE},
212 {"Collectd::DS_TYPE_ABSOLUTE", DS_TYPE_ABSOLUTE},
213 {"Collectd::LOG_ERR", LOG_ERR},
214 {"Collectd::LOG_WARNING", LOG_WARNING},
215 {"Collectd::LOG_NOTICE", LOG_NOTICE},
216 {"Collectd::LOG_INFO", LOG_INFO},
217 {"Collectd::LOG_DEBUG", LOG_DEBUG},
218 {"Collectd::FC_MATCH", FC_MATCH},
219 {"Collectd::FC_TARGET", FC_TARGET},
220 {"Collectd::FC_CB_CREATE", FC_CB_CREATE},
221 {"Collectd::FC_CB_DESTROY", FC_CB_DESTROY},
222 {"Collectd::FC_CB_EXEC", FC_CB_EXEC},
223 {"Collectd::FC_MATCH_NO_MATCH", FC_MATCH_NO_MATCH},
224 {"Collectd::FC_MATCH_MATCHES", FC_MATCH_MATCHES},
225 {"Collectd::FC_TARGET_CONTINUE", FC_TARGET_CONTINUE},
226 {"Collectd::FC_TARGET_STOP", FC_TARGET_STOP},
227 {"Collectd::FC_TARGET_RETURN", FC_TARGET_RETURN},
228 {"Collectd::NOTIF_FAILURE", NOTIF_FAILURE},
229 {"Collectd::NOTIF_WARNING", NOTIF_WARNING},
230 {"Collectd::NOTIF_OKAY", NOTIF_OKAY},
236 } g_strings[] = {{"Collectd::hostname_g", hostname_g}, {"", NULL}};
239 * Helper functions for data type conversion.
254 static int hv2data_source(pTHX_ HV *hash, data_source_t *ds) {
257 if ((NULL == hash) || (NULL == ds))
260 if (NULL != (tmp = hv_fetch(hash, "name", 4, 0))) {
261 sstrncpy(ds->name, SvPV_nolen(*tmp), sizeof(ds->name));
263 log_err("hv2data_source: No DS name given.");
267 if (NULL != (tmp = hv_fetch(hash, "type", 4, 0))) {
268 ds->type = SvIV(*tmp);
270 if ((DS_TYPE_COUNTER != ds->type) && (DS_TYPE_GAUGE != ds->type) &&
271 (DS_TYPE_DERIVE != ds->type) && (DS_TYPE_ABSOLUTE != ds->type)) {
272 log_err("hv2data_source: Invalid DS type.");
276 ds->type = DS_TYPE_COUNTER;
279 if (NULL != (tmp = hv_fetch(hash, "min", 3, 0)))
280 ds->min = SvNV(*tmp);
284 if (NULL != (tmp = hv_fetch(hash, "max", 3, 0)))
285 ds->max = SvNV(*tmp);
289 } /* static int hv2data_source (HV *, data_source_t *) */
291 /* av2value converts at most "len" elements from "array" to "value". Returns the
292 * number of elements converted or zero on error. */
293 static size_t av2value(pTHX_ char *name, AV *array, value_t *value,
295 const data_set_t *ds;
297 if ((NULL == name) || (NULL == array) || (NULL == value) || (array_len == 0))
300 ds = plugin_get_ds(name);
302 log_err("av2value: Unknown dataset \"%s\"", name);
306 if (array_len < ds->ds_num) {
307 log_warn("av2value: array does not contain enough elements for type "
308 "\"%s\": got %zu, want %zu",
309 name, array_len, ds->ds_num);
311 } else if (array_len > ds->ds_num) {
312 log_warn("av2value: array contains excess elements for type \"%s\": got "
314 name, array_len, ds->ds_num);
317 for (size_t i = 0; i < ds->ds_num; ++i) {
318 SV **tmp = av_fetch(array, i, 0);
321 if (DS_TYPE_COUNTER == ds->ds[i].type)
322 value[i].counter = SvIV(*tmp);
323 else if (DS_TYPE_GAUGE == ds->ds[i].type)
324 value[i].gauge = SvNV(*tmp);
325 else if (DS_TYPE_DERIVE == ds->ds[i].type)
326 value[i].derive = SvIV(*tmp);
327 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
328 value[i].absolute = SvIV(*tmp);
335 } /* static size_t av2value (char *, AV *, value_t *, size_t) */
340 * values => [ @values ],
344 * plugin_instance => $pinstance,
345 * type_instance => $tinstance,
348 static int hv2value_list(pTHX_ HV *hash, value_list_t *vl) {
351 if ((NULL == hash) || (NULL == vl))
354 if (NULL == (tmp = hv_fetch(hash, "type", 4, 0))) {
355 log_err("hv2value_list: No type given.");
359 sstrncpy(vl->type, SvPV_nolen(*tmp), sizeof(vl->type));
361 if ((NULL == (tmp = hv_fetch(hash, "values", 6, 0))) ||
362 (!(SvROK(*tmp) && (SVt_PVAV == SvTYPE(SvRV(*tmp)))))) {
363 log_err("hv2value_list: No valid values given.");
368 AV *array = (AV *)SvRV(*tmp);
369 /* av_len returns the highest index, not the actual length. */
370 size_t array_len = (size_t)(av_len(array) + 1);
374 vl->values = calloc(array_len, sizeof(*vl->values));
376 av2value(aTHX_ vl->type, (AV *)SvRV(*tmp), vl->values, array_len);
377 if (vl->values_len == 0) {
383 if (NULL != (tmp = hv_fetch(hash, "time", 4, 0))) {
384 double t = SvNV(*tmp);
385 vl->time = DOUBLE_TO_CDTIME_T(t);
388 if (NULL != (tmp = hv_fetch(hash, "interval", 8, 0))) {
389 double t = SvNV(*tmp);
390 vl->interval = DOUBLE_TO_CDTIME_T(t);
393 if (NULL != (tmp = hv_fetch(hash, "host", 4, 0)))
394 sstrncpy(vl->host, SvPV_nolen(*tmp), sizeof(vl->host));
396 sstrncpy(vl->host, hostname_g, sizeof(vl->host));
398 if (NULL != (tmp = hv_fetch(hash, "plugin", 6, 0)))
399 sstrncpy(vl->plugin, SvPV_nolen(*tmp), sizeof(vl->plugin));
401 if (NULL != (tmp = hv_fetch(hash, "plugin_instance", 15, 0)))
402 sstrncpy(vl->plugin_instance, SvPV_nolen(*tmp),
403 sizeof(vl->plugin_instance));
405 if (NULL != (tmp = hv_fetch(hash, "type_instance", 13, 0)))
406 sstrncpy(vl->type_instance, SvPV_nolen(*tmp), sizeof(vl->type_instance));
408 } /* static int hv2value_list (pTHX_ HV *, value_list_t *) */
410 static int av2data_set(pTHX_ AV *array, char *name, data_set_t *ds) {
413 if ((NULL == array) || (NULL == name) || (NULL == ds))
419 log_err("av2data_set: Invalid data set.");
423 ds->ds = smalloc((len + 1) * sizeof(*ds->ds));
424 ds->ds_num = len + 1;
426 for (int i = 0; i <= len; ++i) {
427 SV **elem = av_fetch(array, i, 0);
430 log_err("av2data_set: Failed to fetch data source %i.", i);
434 if (!(SvROK(*elem) && (SVt_PVHV == SvTYPE(SvRV(*elem))))) {
435 log_err("av2data_set: Invalid data source.");
439 if (-1 == hv2data_source(aTHX_(HV *) SvRV(*elem), &ds->ds[i]))
442 log_debug("av2data_set: "
443 "DS.name = \"%s\", DS.type = %i, DS.min = %f, DS.max = %f",
444 ds->ds[i].name, ds->ds[i].type, ds->ds[i].min, ds->ds[i].max);
447 sstrncpy(ds->type, name, sizeof(ds->type));
449 } /* static int av2data_set (pTHX_ AV *, data_set_t *) */
454 * severity => $severity,
460 * plugin_instance => $instance,
461 * type_instance => $type_instance,
462 * meta => [ { name => <name>, value => <value> }, ... ]
465 static int av2notification_meta(pTHX_ AV *array, notification_meta_t **ret_meta) {
466 notification_meta_t *tail = NULL;
468 int len = av_len(array);
470 for (int i = 0; i <= len; ++i) {
471 SV **tmp = av_fetch(array, i, 0);
476 if (!(SvROK(*tmp) && (SVt_PVHV == SvTYPE(SvRV(*tmp))))) {
477 log_warn("av2notification_meta: Skipping invalid "
478 "meta information.");
482 HV *hash = (HV *)SvRV(*tmp);
484 notification_meta_t *m = calloc(1, sizeof(*m));
488 SV **name = hv_fetch(hash, "name", strlen("name"), 0);
490 log_warn("av2notification_meta: Skipping invalid "
491 "meta information.");
495 sstrncpy(m->name, SvPV_nolen(*name), sizeof(m->name));
497 SV **value = hv_fetch(hash, "value", strlen("value"), 0);
499 log_warn("av2notification_meta: Skipping invalid "
500 "meta information.");
506 m->nm_value.nm_double = SvNVX(*value);
507 m->type = NM_TYPE_DOUBLE;
508 } else if (SvUOK(*value)) {
509 m->nm_value.nm_unsigned_int = SvUVX(*value);
510 m->type = NM_TYPE_UNSIGNED_INT;
511 } else if (SvIOK(*value)) {
512 m->nm_value.nm_signed_int = SvIVX(*value);
513 m->type = NM_TYPE_SIGNED_INT;
515 m->nm_value.nm_string = sstrdup(SvPV_nolen(*value));
516 m->type = NM_TYPE_STRING;
528 } /* static int av2notification_meta (AV *, notification_meta_t *) */
530 static int hv2notification(pTHX_ HV *hash, notification_t *n) {
533 if ((NULL == hash) || (NULL == n))
536 if (NULL != (tmp = hv_fetch(hash, "severity", 8, 0)))
537 n->severity = SvIV(*tmp);
539 n->severity = NOTIF_FAILURE;
541 if (NULL != (tmp = hv_fetch(hash, "time", 4, 0))) {
542 double t = SvNV(*tmp);
543 n->time = DOUBLE_TO_CDTIME_T(t);
547 if (NULL != (tmp = hv_fetch(hash, "message", 7, 0)))
548 sstrncpy(n->message, SvPV_nolen(*tmp), sizeof(n->message));
550 if (NULL != (tmp = hv_fetch(hash, "host", 4, 0)))
551 sstrncpy(n->host, SvPV_nolen(*tmp), sizeof(n->host));
553 sstrncpy(n->host, hostname_g, sizeof(n->host));
555 if (NULL != (tmp = hv_fetch(hash, "plugin", 6, 0)))
556 sstrncpy(n->plugin, SvPV_nolen(*tmp), sizeof(n->plugin));
558 if (NULL != (tmp = hv_fetch(hash, "plugin_instance", 15, 0)))
559 sstrncpy(n->plugin_instance, SvPV_nolen(*tmp), sizeof(n->plugin_instance));
561 if (NULL != (tmp = hv_fetch(hash, "type", 4, 0)))
562 sstrncpy(n->type, SvPV_nolen(*tmp), sizeof(n->type));
564 if (NULL != (tmp = hv_fetch(hash, "type_instance", 13, 0)))
565 sstrncpy(n->type_instance, SvPV_nolen(*tmp), sizeof(n->type_instance));
568 while (NULL != (tmp = hv_fetch(hash, "meta", 4, 0))) {
569 if (!(SvROK(*tmp) && (SVt_PVAV == SvTYPE(SvRV(*tmp))))) {
570 log_warn("hv2notification: Ignoring invalid meta information.");
574 if (0 != av2notification_meta(aTHX_(AV *) SvRV(*tmp), &n->meta)) {
575 plugin_notification_meta_free(n->meta);
582 } /* static int hv2notification (pTHX_ HV *, notification_t *) */
584 static int data_set2av(pTHX_ data_set_t *ds, AV *array) {
585 if ((NULL == ds) || (NULL == array))
588 av_extend(array, ds->ds_num);
590 for (size_t i = 0; i < ds->ds_num; ++i) {
591 HV *source = newHV();
593 if (NULL == hv_store(source, "name", 4, newSVpv(ds->ds[i].name, 0), 0))
596 if (NULL == hv_store(source, "type", 4, newSViv(ds->ds[i].type), 0))
599 if (!isnan(ds->ds[i].min))
600 if (NULL == hv_store(source, "min", 3, newSVnv(ds->ds[i].min), 0))
603 if (!isnan(ds->ds[i].max))
604 if (NULL == hv_store(source, "max", 3, newSVnv(ds->ds[i].max), 0))
607 if (NULL == av_store(array, i, newRV_noinc((SV *)source)))
611 } /* static int data_set2av (data_set_t *, AV *) */
613 static int value_list2hv(pTHX_ value_list_t *vl, data_set_t *ds, HV *hash) {
617 if ((NULL == vl) || (NULL == ds) || (NULL == hash))
621 /* av_extend takes the last *index* to which the array should be extended. */
622 av_extend(values, vl->values_len - 1);
624 assert(ds->ds_num == vl->values_len);
625 for (i = 0; i < vl->values_len; ++i) {
628 if (DS_TYPE_COUNTER == ds->ds[i].type)
629 val = newSViv(vl->values[i].counter);
630 else if (DS_TYPE_GAUGE == ds->ds[i].type)
631 val = newSVnv(vl->values[i].gauge);
632 else if (DS_TYPE_DERIVE == ds->ds[i].type)
633 val = newSViv(vl->values[i].derive);
634 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
635 val = newSViv(vl->values[i].absolute);
637 if (NULL == av_store(values, i, val)) {
643 if (NULL == hv_store(hash, "values", 6, newRV_noinc((SV *)values), 0))
647 double t = CDTIME_T_TO_DOUBLE(vl->time);
648 if (NULL == hv_store(hash, "time", 4, newSVnv(t), 0))
653 double t = CDTIME_T_TO_DOUBLE(vl->interval);
654 if (NULL == hv_store(hash, "interval", 8, newSVnv(t), 0))
658 if ('\0' != vl->host[0])
659 if (NULL == hv_store(hash, "host", 4, newSVpv(vl->host, 0), 0))
662 if ('\0' != vl->plugin[0])
663 if (NULL == hv_store(hash, "plugin", 6, newSVpv(vl->plugin, 0), 0))
666 if ('\0' != vl->plugin_instance[0])
667 if (NULL == hv_store(hash, "plugin_instance", 15,
668 newSVpv(vl->plugin_instance, 0), 0))
671 if ('\0' != vl->type[0])
672 if (NULL == hv_store(hash, "type", 4, newSVpv(vl->type, 0), 0))
675 if ('\0' != vl->type_instance[0])
677 hv_store(hash, "type_instance", 13, newSVpv(vl->type_instance, 0), 0))
680 } /* static int value2av (value_list_t *, data_set_t *, HV *) */
682 static int notification_meta2av(pTHX_ notification_meta_t *meta, AV *array) {
690 av_extend(array, meta_num);
692 for (int i = 0; NULL != meta; meta = meta->next, ++i) {
696 if (NULL == hv_store(m, "name", 4, newSVpv(meta->name, 0), 0))
699 if (NM_TYPE_STRING == meta->type)
700 value = newSVpv(meta->nm_value.nm_string, 0);
701 else if (NM_TYPE_SIGNED_INT == meta->type)
702 value = newSViv(meta->nm_value.nm_signed_int);
703 else if (NM_TYPE_UNSIGNED_INT == meta->type)
704 value = newSVuv(meta->nm_value.nm_unsigned_int);
705 else if (NM_TYPE_DOUBLE == meta->type)
706 value = newSVnv(meta->nm_value.nm_double);
707 else if (NM_TYPE_BOOLEAN == meta->type)
708 value = meta->nm_value.nm_boolean ? &PL_sv_yes : &PL_sv_no;
712 if (NULL == hv_store(m, "value", 5, value, 0)) {
717 if (NULL == av_store(array, i, newRV_noinc((SV *)m))) {
724 } /* static int notification_meta2av (notification_meta_t *, AV *) */
726 static int notification2hv(pTHX_ notification_t *n, HV *hash) {
727 if (NULL == hv_store(hash, "severity", 8, newSViv(n->severity), 0))
731 double t = CDTIME_T_TO_DOUBLE(n->time);
732 if (NULL == hv_store(hash, "time", 4, newSVnv(t), 0))
736 if ('\0' != *n->message)
737 if (NULL == hv_store(hash, "message", 7, newSVpv(n->message, 0), 0))
740 if ('\0' != *n->host)
741 if (NULL == hv_store(hash, "host", 4, newSVpv(n->host, 0), 0))
744 if ('\0' != *n->plugin)
745 if (NULL == hv_store(hash, "plugin", 6, newSVpv(n->plugin, 0), 0))
748 if ('\0' != *n->plugin_instance)
749 if (NULL == hv_store(hash, "plugin_instance", 15,
750 newSVpv(n->plugin_instance, 0), 0))
753 if ('\0' != *n->type)
754 if (NULL == hv_store(hash, "type", 4, newSVpv(n->type, 0), 0))
757 if ('\0' != *n->type_instance)
759 hv_store(hash, "type_instance", 13, newSVpv(n->type_instance, 0), 0))
762 if (NULL != n->meta) {
764 if ((0 != notification_meta2av(aTHX_ n->meta, meta)) ||
765 (NULL == hv_store(hash, "meta", 4, newRV_noinc((SV *)meta), 0))) {
772 } /* static int notification2hv (notification_t *, HV *) */
774 static int oconfig_item2hv(pTHX_ oconfig_item_t *ci, HV *hash) {
778 if (NULL == hv_store(hash, "key", 3, newSVpv(ci->key, 0), 0))
782 if (0 < ci->values_num)
783 av_extend(values, ci->values_num);
785 if (NULL == hv_store(hash, "values", 6, newRV_noinc((SV *)values), 0)) {
791 for (int i = 0; i < ci->values_num; ++i) {
794 switch (ci->values[i].type) {
795 case OCONFIG_TYPE_STRING:
796 value = newSVpv(ci->values[i].value.string, 0);
798 case OCONFIG_TYPE_NUMBER:
799 value = newSVnv((NV)ci->values[i].value.number);
801 case OCONFIG_TYPE_BOOLEAN:
802 value = ci->values[i].value.boolean ? &PL_sv_yes : &PL_sv_no;
805 log_err("oconfig_item2hv: Invalid value type %i.", ci->values[i].type);
806 value = &PL_sv_undef;
809 if (NULL == av_store(values, i, value)) {
815 /* ignoring 'parent' member which is uninteresting in this case */
818 if (0 < ci->children_num)
819 av_extend(children, ci->children_num);
821 if (NULL == hv_store(hash, "children", 8, newRV_noinc((SV *)children), 0)) {
827 for (int i = 0; i < ci->children_num; ++i) {
830 if (0 != oconfig_item2hv(aTHX_ ci->children + i, child)) {
836 if (NULL == av_store(children, i, newRV_noinc((SV *)child))) {
843 } /* static int oconfig_item2hv (pTHX_ oconfig_item_t *, HV *) */
846 * Internal functions.
849 static char *get_module_name(char *buf, size_t buf_len, const char *module) {
851 if (base_name[0] == '\0')
852 status = ssnprintf(buf, buf_len, "%s", module);
854 status = ssnprintf(buf, buf_len, "%s::%s", base_name, module);
855 if ((status < 0) || ((unsigned int)status >= buf_len))
858 } /* char *get_module_name */
861 * Add a plugin's data set definition.
863 static int pplugin_register_data_set(pTHX_ char *name, AV *dataset) {
868 if ((NULL == name) || (NULL == dataset))
871 if (0 != av2data_set(aTHX_ dataset, name, &ds))
874 ret = plugin_register_data_set(&ds);
878 } /* static int pplugin_register_data_set (char *, SV *) */
881 * Remove a plugin's data set definition.
883 static int pplugin_unregister_data_set(char *name) {
886 return plugin_unregister_data_set(name);
887 } /* static int pplugin_unregister_data_set (char *) */
890 * Submit the values to the write functions.
892 static int pplugin_dispatch_values(pTHX_ HV *values) {
893 value_list_t vl = VALUE_LIST_INIT;
900 if (0 != hv2value_list(aTHX_ values, &vl))
903 ret = plugin_dispatch_values(&vl);
907 } /* static int pplugin_dispatch_values (char *, HV *) */
910 * Submit the values to a single write function.
912 static int pplugin_write(pTHX_ const char *plugin, AV *data_set, HV *values) {
914 value_list_t vl = VALUE_LIST_INIT;
921 if (0 != hv2value_list(aTHX_ values, &vl))
924 if ((NULL != data_set) && (0 != av2data_set(aTHX_ data_set, vl.type, &ds)))
927 ret = plugin_write(plugin, NULL == data_set ? NULL : &ds, &vl);
929 log_warn("Dispatching value to plugin \"%s\" failed with status %i.",
930 NULL == plugin ? "<any>" : plugin, ret);
932 if (NULL != data_set)
936 } /* static int pplugin_write (const char *plugin, HV *, HV *) */
939 * Dispatch a notification.
941 static int pplugin_dispatch_notification(pTHX_ HV *notif) {
942 notification_t n = {0};
949 if (0 != hv2notification(aTHX_ notif, &n))
952 ret = plugin_dispatch_notification(&n);
953 plugin_notification_meta_free(n.meta);
955 } /* static int pplugin_dispatch_notification (HV *) */
958 * Call perl sub with thread locking flags handled.
960 static int call_pv_locked(pTHX_ const char *sub_name) {
964 c_ithread_t *t = (c_ithread_t *)pthread_getspecific(perl_thr_key);
965 if (t == NULL) /* thread destroyed */
968 old_running = t->running;
972 t->running = old_running;
976 ret = call_pv(sub_name, G_SCALAR);
978 t->running = old_running;
980 } /* static int call_pv_locked (pTHX, *sub_name) */
983 * Call all working functions of the given type.
985 static int pplugin_call_all(pTHX_ int type, ...) {
993 if ((type < 0) || (type >= PLUGIN_TYPES))
1003 XPUSHs(sv_2mortal(newSViv((IV)type)));
1005 if (PLUGIN_WRITE == type) {
1007 * $_[0] = $plugin_type;
1022 * values => [ $v1, ... ],
1024 * host => $hostname,
1025 * plugin => $plugin,
1027 * plugin_instance => $instance,
1028 * type_instance => $type_instance
1037 ds = va_arg(ap, data_set_t *);
1038 vl = va_arg(ap, value_list_t *);
1040 if (-1 == data_set2av(aTHX_ ds, pds)) {
1043 pds = (AV *)&PL_sv_undef;
1047 if (-1 == value_list2hv(aTHX_ vl, ds, pvl)) {
1050 pvl = (HV *)&PL_sv_undef;
1054 XPUSHs(sv_2mortal(newSVpv(ds->type, 0)));
1055 XPUSHs(sv_2mortal(newRV_noinc((SV *)pds)));
1056 XPUSHs(sv_2mortal(newRV_noinc((SV *)pvl)));
1057 } else if (PLUGIN_LOG == type) {
1063 XPUSHs(sv_2mortal(newSViv(va_arg(ap, int))));
1064 XPUSHs(sv_2mortal(newSVpv(va_arg(ap, char *), 0)));
1065 } else if (PLUGIN_NOTIF == type) {
1069 * severity => $severity,
1073 * plugin => $plugin,
1075 * plugin_instance => $instance,
1076 * type_instance => $type_instance
1080 HV *notif = newHV();
1082 n = va_arg(ap, notification_t *);
1084 if (-1 == notification2hv(aTHX_ n, notif)) {
1087 notif = (HV *)&PL_sv_undef;
1091 XPUSHs(sv_2mortal(newRV_noinc((SV *)notif)));
1092 } else if (PLUGIN_FLUSH == type) {
1097 * $_[1] = $identifier;
1099 timeout = va_arg(ap, cdtime_t);
1101 XPUSHs(sv_2mortal(newSVnv(CDTIME_T_TO_DOUBLE(timeout))));
1102 XPUSHs(sv_2mortal(newSVpv(va_arg(ap, char *), 0)));
1107 retvals = call_pv_locked(aTHX_ "Collectd::plugin_call_all");
1122 } /* static int pplugin_call_all (int, ...) */
1125 * collectd's Perl interpreter based thread implementation.
1127 * This has been inspired by Perl's ithreads introduced in version 5.6.0.
1130 /* must be called with perl_threads->mutex locked */
1131 static void c_ithread_destroy(c_ithread_t *ithread) {
1132 dTHXa(ithread->interp);
1134 assert(NULL != perl_threads);
1136 PERL_SET_CONTEXT(aTHX);
1137 log_debug("Shutting down Perl interpreter %p...", aTHX);
1142 --perl_threads->number_of_threads;
1143 #endif /* COLLECT_DEBUG */
1145 perl_destruct(aTHX);
1148 if (NULL == ithread->prev)
1149 perl_threads->head = ithread->next;
1151 ithread->prev->next = ithread->next;
1153 if (NULL == ithread->next)
1154 perl_threads->tail = ithread->prev;
1156 ithread->next->prev = ithread->prev;
1160 } /* static void c_ithread_destroy (c_ithread_t *) */
1162 static void c_ithread_destructor(void *arg) {
1163 c_ithread_t *ithread = (c_ithread_t *)arg;
1164 c_ithread_t *t = NULL;
1166 if (NULL == perl_threads)
1169 pthread_mutex_lock(&perl_threads->mutex);
1171 for (t = perl_threads->head; NULL != t; t = t->next)
1175 /* the ithread no longer exists */
1177 pthread_mutex_unlock(&perl_threads->mutex);
1181 c_ithread_destroy(ithread);
1183 pthread_mutex_unlock(&perl_threads->mutex);
1185 } /* static void c_ithread_destructor (void *) */
1187 /* must be called with perl_threads->mutex locked */
1188 static c_ithread_t *c_ithread_create(PerlInterpreter *base) {
1189 c_ithread_t *t = NULL;
1192 assert(NULL != perl_threads);
1194 t = smalloc(sizeof(*t));
1195 memset(t, 0, sizeof(c_ithread_t));
1197 t->interp = (NULL == base) ? NULL : perl_clone(base, CLONEf_KEEP_PTR_TABLE);
1201 if ((NULL != base) && (NULL != PL_endav)) {
1208 ++perl_threads->number_of_threads;
1209 #endif /* COLLECT_DEBUG */
1213 if (NULL == perl_threads->tail) {
1214 perl_threads->head = t;
1217 perl_threads->tail->next = t;
1218 t->prev = perl_threads->tail;
1221 t->pthread = pthread_self();
1224 perl_threads->tail = t;
1226 pthread_setspecific(perl_thr_key, (const void *)t);
1228 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
1231 * Filter chains implementation.
1234 static int fc_call(pTHX_ int type, int cb_type, pfc_user_data_t *data, ...) {
1240 notification_meta_t **meta = NULL;
1245 if ((type < 0) || (type >= FC_TYPES))
1248 if ((cb_type < 0) || (cb_type >= FC_CB_TYPES))
1258 XPUSHs(sv_2mortal(newSViv((IV)type)));
1259 XPUSHs(sv_2mortal(newSVpv(data->name, 0)));
1260 XPUSHs(sv_2mortal(newSViv((IV)cb_type)));
1262 if (FC_CB_CREATE == cb_type) {
1265 * $_[1] = $user_data;
1268 HV *config = newHV();
1270 ci = va_arg(ap, oconfig_item_t *);
1272 if (0 != oconfig_item2hv(aTHX_ ci, config)) {
1275 config = (HV *)&PL_sv_undef;
1279 XPUSHs(sv_2mortal(newRV_noinc((SV *)config)));
1280 } else if (FC_CB_DESTROY == cb_type) {
1282 * $_[1] = $user_data;
1285 /* nothing to be done - the user data pointer
1286 * is pushed onto the stack later */
1287 } else if (FC_CB_EXEC == cb_type) {
1292 * $_[3] = $user_data;
1300 ds = va_arg(ap, data_set_t *);
1301 vl = va_arg(ap, value_list_t *);
1302 meta = va_arg(ap, notification_meta_t **);
1304 if (0 != data_set2av(aTHX_ ds, pds)) {
1307 pds = (AV *)&PL_sv_undef;
1311 if (0 != value_list2hv(aTHX_ vl, ds, pvl)) {
1314 pvl = (HV *)&PL_sv_undef;
1321 if (0 != notification_meta2av(aTHX_ * meta, pmeta)) {
1324 pmeta = (AV *)&PL_sv_undef;
1328 pmeta = (AV *)&PL_sv_undef;
1331 XPUSHs(sv_2mortal(newRV_noinc((SV *)pds)));
1332 XPUSHs(sv_2mortal(newRV_noinc((SV *)pvl)));
1333 XPUSHs(sv_2mortal(newRV_noinc((SV *)pmeta)));
1336 XPUSHs(sv_2mortal(newRV_inc(data->user_data)));
1340 retvals = call_pv_locked(aTHX_ "Collectd::fc_call");
1342 if ((FC_CB_EXEC == cb_type) && (meta != NULL)) {
1343 assert(pmeta != NULL);
1345 plugin_notification_meta_free(*meta);
1346 av2notification_meta(aTHX_ pmeta, meta);
1353 /* the exec callbacks return a status, while
1354 * the others return a boolean value */
1355 if (FC_CB_EXEC == cb_type)
1357 else if (!SvTRUE(tmp))
1367 } /* static int fc_call (int, int, pfc_user_data_t *, ...) */
1369 static int fc_create(int type, const oconfig_item_t *ci, void **user_data) {
1370 pfc_user_data_t *data;
1376 if (NULL == perl_threads)
1380 c_ithread_t *t = NULL;
1382 pthread_mutex_lock(&perl_threads->mutex);
1383 t = c_ithread_create(perl_threads->head->interp);
1384 pthread_mutex_unlock(&perl_threads->mutex);
1389 log_debug("fc_create: c_ithread: interp = %p (active threads: %i)", aTHX,
1390 perl_threads->number_of_threads);
1392 if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1393 log_warn("A \"%s\" block expects a single string argument.",
1394 (FC_MATCH == type) ? "Match" : "Target");
1398 data = smalloc(sizeof(*data));
1399 data->name = sstrdup(ci->values[0].value.string);
1400 data->user_data = newSV(0);
1402 ret = fc_call(aTHX_ type, FC_CB_CREATE, data, ci);
1405 PFC_USER_DATA_FREE(data);
1409 } /* static int fc_create (int, const oconfig_item_t *, void **) */
1411 static int fc_destroy(int type, void **user_data) {
1412 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1418 if ((NULL == perl_threads) || (NULL == data))
1422 c_ithread_t *t = NULL;
1424 pthread_mutex_lock(&perl_threads->mutex);
1425 t = c_ithread_create(perl_threads->head->interp);
1426 pthread_mutex_unlock(&perl_threads->mutex);
1431 log_debug("fc_destroy: c_ithread: interp = %p (active threads: %i)", aTHX,
1432 perl_threads->number_of_threads);
1434 ret = fc_call(aTHX_ type, FC_CB_DESTROY, data);
1436 PFC_USER_DATA_FREE(data);
1439 } /* static int fc_destroy (int, void **) */
1441 static int fc_exec(int type, const data_set_t *ds, const value_list_t *vl,
1442 notification_meta_t **meta, void **user_data) {
1443 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1447 if (NULL == perl_threads)
1450 assert(NULL != data);
1453 c_ithread_t *t = NULL;
1455 pthread_mutex_lock(&perl_threads->mutex);
1456 t = c_ithread_create(perl_threads->head->interp);
1457 pthread_mutex_unlock(&perl_threads->mutex);
1462 log_debug("fc_exec: c_ithread: interp = %p (active threads: %i)", aTHX,
1463 perl_threads->number_of_threads);
1465 return fc_call(aTHX_ type, FC_CB_EXEC, data, ds, vl, meta);
1466 } /* static int fc_exec (int, const data_set_t *, const value_list_t *,
1467 notification_meta_t **, void **) */
1469 static int pmatch_create(const oconfig_item_t *ci, void **user_data) {
1470 return fc_create(FC_MATCH, ci, user_data);
1471 } /* static int pmatch_create (const oconfig_item_t *, void **) */
1473 static int pmatch_destroy(void **user_data) {
1474 return fc_destroy(FC_MATCH, user_data);
1475 } /* static int pmatch_destroy (void **) */
1477 static int pmatch_match(const data_set_t *ds, const value_list_t *vl,
1478 notification_meta_t **meta, void **user_data) {
1479 return fc_exec(FC_MATCH, ds, vl, meta, user_data);
1480 } /* static int pmatch_match (const data_set_t *, const value_list_t *,
1481 notification_meta_t **, void **) */
1483 static match_proc_t pmatch = {pmatch_create, pmatch_destroy, pmatch_match};
1485 static int ptarget_create(const oconfig_item_t *ci, void **user_data) {
1486 return fc_create(FC_TARGET, ci, user_data);
1487 } /* static int ptarget_create (const oconfig_item_t *, void **) */
1489 static int ptarget_destroy(void **user_data) {
1490 return fc_destroy(FC_TARGET, user_data);
1491 } /* static int ptarget_destroy (void **) */
1493 static int ptarget_invoke(const data_set_t *ds, value_list_t *vl,
1494 notification_meta_t **meta, void **user_data) {
1495 return fc_exec(FC_TARGET, ds, vl, meta, user_data);
1496 } /* static int ptarget_invoke (const data_set_t *, value_list_t *,
1497 notification_meta_t **, void **) */
1499 static target_proc_t ptarget = {ptarget_create, ptarget_destroy,
1503 * Exported Perl API.
1507 * Collectd::plugin_register_data_set (type, dataset).
1510 * type of the dataset
1513 * dataset to be registered
1515 static XS(Collectd_plugin_register_ds) {
1521 log_warn("Using plugin_register() to register new data-sets is "
1522 "deprecated - add new entries to a custom types.db instead.");
1525 log_err("Usage: Collectd::plugin_register_data_set(type, dataset)");
1529 log_debug("Collectd::plugin_register_data_set: "
1530 "type = \"%s\", dataset = \"%s\"",
1531 SvPV_nolen(ST(0)), SvPV_nolen(ST(1)));
1535 if (SvROK(data) && (SVt_PVAV == SvTYPE(SvRV(data)))) {
1536 ret = pplugin_register_data_set(aTHX_ SvPV_nolen(ST(0)), (AV *)SvRV(data));
1538 log_err("Collectd::plugin_register_data_set: Invalid data.");
1546 } /* static XS (Collectd_plugin_register_ds) */
1549 * Collectd::plugin_unregister_data_set (type).
1552 * type of the dataset
1554 static XS(Collectd_plugin_unregister_ds) {
1558 log_err("Usage: Collectd::plugin_unregister_data_set(type)");
1562 log_debug("Collectd::plugin_unregister_data_set: type = \"%s\"",
1565 if (0 == pplugin_unregister_data_set(SvPV_nolen(ST(0))))
1569 } /* static XS (Collectd_plugin_register_ds) */
1572 * Collectd::plugin_dispatch_values (name, values).
1575 * name of the plugin
1578 * value list to submit
1580 static XS(Collectd_plugin_dispatch_values) {
1588 log_err("Usage: Collectd::plugin_dispatch_values(values)");
1592 log_debug("Collectd::plugin_dispatch_values: values=\"%s\"",
1593 SvPV_nolen(ST(/* stack index = */ 0)));
1595 values = ST(/* stack index = */ 0);
1600 /* Make sure the argument is a hash reference. */
1601 if (!(SvROK(values) && (SVt_PVHV == SvTYPE(SvRV(values))))) {
1602 log_err("Collectd::plugin_dispatch_values: Invalid values.");
1606 ret = pplugin_dispatch_values(aTHX_(HV *) SvRV(values));
1612 } /* static XS (Collectd_plugin_dispatch_values) */
1615 * Collectd::plugin_get_interval ().
1617 static XS(Collectd_plugin_get_interval) {
1620 /* make sure we don't get any unused variable warnings for 'items';
1621 * don't abort, though */
1623 log_err("Usage: Collectd::plugin_get_interval()");
1625 XSRETURN_NV((NV)CDTIME_T_TO_DOUBLE(plugin_get_interval()));
1626 } /* static XS (Collectd_plugin_get_interval) */
1628 /* Collectd::plugin_write (plugin, ds, vl).
1631 * name of the plugin to call, may be 'undef'
1634 * data-set that describes the submitted values, may be 'undef'
1637 * value-list to be written
1639 static XS(Collectd__plugin_write) {
1649 log_err("Usage: Collectd::plugin_write(plugin, ds, vl)");
1653 log_debug("Collectd::plugin_write: plugin=\"%s\", ds=\"%s\", vl=\"%s\"",
1654 SvPV_nolen(ST(0)), SvOK(ST(1)) ? SvPV_nolen(ST(1)) : "",
1660 plugin = SvPV_nolen(ST(0));
1663 if (SvROK(ds) && (SVt_PVAV == SvTYPE(SvRV(ds))))
1664 ds_array = (AV *)SvRV(ds);
1668 log_err("Collectd::plugin_write: Invalid data-set.");
1673 if (!(SvROK(vl) && (SVt_PVHV == SvTYPE(SvRV(vl))))) {
1674 log_err("Collectd::plugin_write: Invalid value-list.");
1678 ret = pplugin_write(aTHX_ plugin, ds_array, (HV *)SvRV(vl));
1684 } /* static XS (Collectd__plugin_write) */
1687 * Collectd::_plugin_flush (plugin, timeout, identifier).
1690 * name of the plugin to flush
1693 * timeout to use when flushing the data
1696 * data-set identifier to flush
1698 static XS(Collectd__plugin_flush) {
1699 char *plugin = NULL;
1706 log_err("Usage: Collectd::_plugin_flush(plugin, timeout, id)");
1711 plugin = SvPV_nolen(ST(0));
1714 timeout = (int)SvIV(ST(1));
1717 id = SvPV_nolen(ST(2));
1719 log_debug("Collectd::_plugin_flush: plugin = \"%s\", timeout = %i, "
1721 plugin, timeout, id);
1723 if (0 == plugin_flush(plugin, timeout, id))
1727 } /* static XS (Collectd__plugin_flush) */
1730 * Collectd::plugin_dispatch_notification (notif).
1733 * notification to dispatch
1735 static XS(Collectd_plugin_dispatch_notification) {
1743 log_err("Usage: Collectd::plugin_dispatch_notification(notif)");
1747 log_debug("Collectd::plugin_dispatch_notification: notif = \"%s\"",
1752 if (!(SvROK(notif) && (SVt_PVHV == SvTYPE(SvRV(notif))))) {
1753 log_err("Collectd::plugin_dispatch_notification: Invalid notif.");
1757 ret = pplugin_dispatch_notification(aTHX_(HV *) SvRV(notif));
1763 } /* static XS (Collectd_plugin_dispatch_notification) */
1766 * Collectd::plugin_log (level, message).
1769 * log level (LOG_DEBUG, ... LOG_ERR)
1774 static XS(Collectd_plugin_log) {
1778 log_err("Usage: Collectd::plugin_log(level, message)");
1782 plugin_log(SvIV(ST(0)), "%s", SvPV_nolen(ST(1)));
1784 } /* static XS (Collectd_plugin_log) */
1787 * Collectd::_fc_register (type, name)
1795 static XS(Collectd__fc_register) {
1804 log_err("Usage: Collectd::_fc_register(type, name)");
1809 name = SvPV_nolen(ST(1));
1811 if (FC_MATCH == type)
1812 ret = fc_register_match(name, pmatch);
1813 else if (FC_TARGET == type)
1814 ret = fc_register_target(name, ptarget);
1820 } /* static XS (Collectd_fc_register) */
1823 * Collectd::call_by_name (...).
1825 * Call a Perl sub identified by its name passed through $Collectd::cb_name.
1827 static XS(Collectd_call_by_name) {
1831 if (NULL == (tmp = get_sv("Collectd::cb_name", 0))) {
1832 sv_setpv(get_sv("@", 1), "cb_name has not been set");
1837 name = SvPV_nolen(tmp);
1839 if (NULL == get_cv(name, 0)) {
1840 sv_setpvf(get_sv("@", 1), "unknown callback \"%s\"", name);
1845 /* simply pass on the subroutine call without touching the stack,
1846 * thus leaving any arguments and return values in place */
1848 } /* static XS (Collectd_call_by_name) */
1851 * Interface to collectd.
1854 static int perl_init(void) {
1858 if (NULL == perl_threads)
1862 c_ithread_t *t = NULL;
1864 pthread_mutex_lock(&perl_threads->mutex);
1865 t = c_ithread_create(perl_threads->head->interp);
1866 pthread_mutex_unlock(&perl_threads->mutex);
1871 log_debug("perl_init: c_ithread: interp = %p (active threads: %i)", aTHX,
1872 perl_threads->number_of_threads);
1874 /* Lock the base thread to avoid race conditions with c_ithread_create().
1875 * See https://github.com/collectd/collectd/issues/9 and
1876 * https://github.com/collectd/collectd/issues/1706 for details.
1878 assert(aTHX == perl_threads->head->interp);
1879 pthread_mutex_lock(&perl_threads->mutex);
1881 status = pplugin_call_all(aTHX_ PLUGIN_INIT);
1883 pthread_mutex_unlock(&perl_threads->mutex);
1886 } /* static int perl_init (void) */
1888 static int perl_read(void) {
1891 if (NULL == perl_threads)
1895 c_ithread_t *t = NULL;
1897 pthread_mutex_lock(&perl_threads->mutex);
1898 t = c_ithread_create(perl_threads->head->interp);
1899 pthread_mutex_unlock(&perl_threads->mutex);
1904 /* Assert that we're not running as the base thread. Otherwise, we might
1905 * run into concurrency issues with c_ithread_create(). See
1906 * https://github.com/collectd/collectd/issues/9 for details. */
1907 assert(aTHX != perl_threads->head->interp);
1909 log_debug("perl_read: c_ithread: interp = %p (active threads: %i)", aTHX,
1910 perl_threads->number_of_threads);
1911 return pplugin_call_all(aTHX_ PLUGIN_READ);
1912 } /* static int perl_read (void) */
1914 static int perl_write(const data_set_t *ds, const value_list_t *vl,
1915 user_data_t __attribute__((unused)) * user_data) {
1919 if (NULL == perl_threads)
1923 c_ithread_t *t = NULL;
1925 pthread_mutex_lock(&perl_threads->mutex);
1926 t = c_ithread_create(perl_threads->head->interp);
1927 pthread_mutex_unlock(&perl_threads->mutex);
1932 /* Lock the base thread if this is not called from one of the read threads
1933 * to avoid race conditions with c_ithread_create(). See
1934 * https://github.com/collectd/collectd/issues/9 for details. */
1935 if (aTHX == perl_threads->head->interp)
1936 pthread_mutex_lock(&perl_threads->mutex);
1938 log_debug("perl_write: c_ithread: interp = %p (active threads: %i)", aTHX,
1939 perl_threads->number_of_threads);
1940 status = pplugin_call_all(aTHX_ PLUGIN_WRITE, ds, vl);
1942 if (aTHX == perl_threads->head->interp)
1943 pthread_mutex_unlock(&perl_threads->mutex);
1946 } /* static int perl_write (const data_set_t *, const value_list_t *) */
1948 static void perl_log(int level, const char *msg,
1949 user_data_t __attribute__((unused)) * user_data) {
1952 if (NULL == perl_threads)
1956 c_ithread_t *t = NULL;
1958 pthread_mutex_lock(&perl_threads->mutex);
1959 t = c_ithread_create(perl_threads->head->interp);
1960 pthread_mutex_unlock(&perl_threads->mutex);
1965 /* Lock the base thread if this is not called from one of the read threads
1966 * to avoid race conditions with c_ithread_create(). See
1967 * https://github.com/collectd/collectd/issues/9 for details.
1970 if (aTHX == perl_threads->head->interp)
1971 pthread_mutex_lock(&perl_threads->mutex);
1973 pplugin_call_all(aTHX_ PLUGIN_LOG, level, msg);
1975 if (aTHX == perl_threads->head->interp)
1976 pthread_mutex_unlock(&perl_threads->mutex);
1979 } /* static void perl_log (int, const char *) */
1981 static int perl_notify(const notification_t *notif,
1982 user_data_t __attribute__((unused)) * user_data) {
1985 if (NULL == perl_threads)
1989 c_ithread_t *t = NULL;
1991 pthread_mutex_lock(&perl_threads->mutex);
1992 t = c_ithread_create(perl_threads->head->interp);
1993 pthread_mutex_unlock(&perl_threads->mutex);
1997 return pplugin_call_all(aTHX_ PLUGIN_NOTIF, notif);
1998 } /* static int perl_notify (const notification_t *) */
2000 static int perl_flush(cdtime_t timeout, const char *identifier,
2001 user_data_t __attribute__((unused)) * user_data) {
2004 if (NULL == perl_threads)
2008 c_ithread_t *t = NULL;
2010 pthread_mutex_lock(&perl_threads->mutex);
2011 t = c_ithread_create(perl_threads->head->interp);
2012 pthread_mutex_unlock(&perl_threads->mutex);
2016 return pplugin_call_all(aTHX_ PLUGIN_FLUSH, timeout, identifier);
2017 } /* static int perl_flush (const int) */
2019 static int perl_shutdown(void) {
2025 plugin_unregister_complex_config("perl");
2027 if (NULL == perl_threads)
2031 pthread_mutex_lock(&perl_threads->mutex);
2032 t = c_ithread_create(perl_threads->head->interp);
2033 pthread_mutex_unlock(&perl_threads->mutex);
2038 log_debug("perl_shutdown: c_ithread: interp = %p (active threads: %i)", aTHX,
2039 perl_threads->number_of_threads);
2041 plugin_unregister_log("perl");
2042 plugin_unregister_notification("perl");
2043 plugin_unregister_init("perl");
2044 plugin_unregister_read("perl");
2045 plugin_unregister_write("perl");
2046 plugin_unregister_flush("perl");
2048 ret = pplugin_call_all(aTHX_ PLUGIN_SHUTDOWN);
2050 pthread_mutex_lock(&perl_threads->mutex);
2051 t = perl_threads->tail;
2054 struct timespec ts_wait;
2055 c_ithread_t *thr = t;
2057 /* the pointer has to be advanced before destroying
2058 * the thread as this will free the memory */
2063 /* Give some time to thread to exit from Perl interpreter */
2064 WARNING("perl shutdown: Thread is running inside Perl. Waiting.");
2066 ts_wait.tv_nsec = 500000;
2067 nanosleep(&ts_wait, NULL);
2070 pthread_kill(thr->pthread, SIGTERM);
2071 ERROR("perl shutdown: Thread hangs inside Perl. Thread killed.");
2073 c_ithread_destroy(thr);
2076 pthread_mutex_unlock(&perl_threads->mutex);
2077 pthread_mutex_destroy(&perl_threads->mutex);
2078 pthread_mutexattr_destroy(&perl_threads->mutexattr);
2080 sfree(perl_threads);
2082 pthread_key_delete(perl_thr_key);
2086 plugin_unregister_shutdown("perl");
2088 } /* static void perl_shutdown (void) */
2091 * Access functions for global variables.
2093 * These functions implement the "magic" used to access
2094 * the global variables from Perl.
2097 static int g_pv_get(pTHX_ SV *var, MAGIC *mg) {
2098 char *pv = mg->mg_ptr;
2101 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
2103 static int g_pv_set(pTHX_ SV *var, MAGIC *mg) {
2104 char *pv = mg->mg_ptr;
2105 sstrncpy(pv, SvPV_nolen(var), DATA_MAX_NAME_LEN);
2107 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
2109 static int g_interval_get(pTHX_ SV *var, MAGIC *mg) {
2110 log_warn("Accessing $interval_g is deprecated (and might not "
2111 "give the desired results) - plugin_get_interval() should "
2112 "be used instead.");
2113 sv_setnv(var, CDTIME_T_TO_DOUBLE(interval_g));
2115 } /* static int g_interval_get (pTHX_ SV *, MAGIC *) */
2117 static int g_interval_set(pTHX_ SV *var, MAGIC *mg) {
2118 double nv = (double)SvNV(var);
2119 log_warn("Accessing $interval_g is deprecated (and might not "
2120 "give the desired results) - plugin_get_interval() should "
2121 "be used instead.");
2122 interval_g = DOUBLE_TO_CDTIME_T(nv);
2124 } /* static int g_interval_set (pTHX_ SV *, MAGIC *) */
2126 static MGVTBL g_pv_vtbl = {g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL
2127 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2132 static MGVTBL g_interval_vtbl = {g_interval_get, g_interval_set, NULL, NULL,
2134 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2140 /* bootstrap the Collectd module */
2141 static void xs_init(pTHX) {
2144 char *file = __FILE__;
2148 /* enable usage of Perl modules using shared libraries */
2149 newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2152 for (int i = 0; NULL != api[i].f; ++i)
2153 newXS(api[i].name, api[i].f, file);
2155 stash = gv_stashpv("Collectd", 1);
2157 /* export "constants" */
2158 for (int i = 0; '\0' != constants[i].name[0]; ++i)
2159 newCONSTSUB(stash, constants[i].name, newSViv(constants[i].value));
2161 /* export global variables
2162 * by adding "magic" to the SV's representing the globale variables
2163 * perl is able to automagically call the get/set function when
2164 * accessing any such variable (this is basically the same as using
2166 /* global strings */
2167 for (int i = 0; '\0' != g_strings[i].name[0]; ++i) {
2168 tmp = get_sv(g_strings[i].name, 1);
2169 sv_magicext(tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl, g_strings[i].var, 0);
2172 tmp = get_sv("Collectd::interval_g", /* create = */ 1);
2173 sv_magicext(tmp, NULL, /* how = */ PERL_MAGIC_ext,
2174 /* vtbl = */ &g_interval_vtbl,
2175 /* name = */ NULL, /* namelen = */ 0);
2178 } /* static void xs_init (pTHX) */
2180 /* Initialize the global Perl interpreter. */
2181 static int init_pi(int argc, char **argv) {
2184 if (NULL != perl_threads)
2187 log_info("Initializing Perl interpreter...");
2190 for (int i = 0; i < argc; ++i)
2191 log_debug("argv[%i] = \"%s\"", i, argv[i]);
2193 #endif /* COLLECT_DEBUG */
2195 if (0 != pthread_key_create(&perl_thr_key, c_ithread_destructor)) {
2196 log_err("init_pi: pthread_key_create failed");
2198 /* this must not happen - cowardly giving up if it does */
2203 /* On FreeBSD, PERL_SYS_INIT3 expands to some expression which
2204 * triggers a "value computed is not used" warning by gcc. */
2207 PERL_SYS_INIT3(&argc, &argv, &environ);
2209 perl_threads = smalloc(sizeof(*perl_threads));
2210 memset(perl_threads, 0, sizeof(c_ithread_list_t));
2212 pthread_mutexattr_init(&perl_threads->mutexattr);
2213 pthread_mutexattr_settype(&perl_threads->mutexattr, PTHREAD_MUTEX_RECURSIVE);
2214 pthread_mutex_init(&perl_threads->mutex, &perl_threads->mutexattr);
2215 /* locking the mutex should not be necessary at this point
2216 * but let's just do it for the sake of completeness */
2217 pthread_mutex_lock(&perl_threads->mutex);
2219 perl_threads->head = c_ithread_create(NULL);
2220 perl_threads->tail = perl_threads->head;
2222 if (NULL == (perl_threads->head->interp = perl_alloc())) {
2223 log_err("init_pi: Not enough memory.");
2227 aTHX = perl_threads->head->interp;
2228 pthread_mutex_unlock(&perl_threads->mutex);
2230 perl_construct(aTHX);
2232 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
2234 if (0 != perl_parse(aTHX_ xs_init, argc, argv, NULL)) {
2235 SV *err = get_sv("@", 1);
2236 log_err("init_pi: Unable to bootstrap Collectd: %s", SvPV_nolen(err));
2238 perl_destruct(perl_threads->head->interp);
2239 perl_free(perl_threads->head->interp);
2240 sfree(perl_threads);
2242 pthread_key_delete(perl_thr_key);
2246 /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
2247 sv_setpv(get_sv("0", 0), "collectd");
2251 plugin_register_log("perl", perl_log, /* user_data = */ NULL);
2252 plugin_register_notification("perl", perl_notify,
2253 /* user_data = */ NULL);
2254 plugin_register_init("perl", perl_init);
2256 plugin_register_read("perl", perl_read);
2258 plugin_register_write("perl", perl_write, /* user_data = */ NULL);
2259 plugin_register_flush("perl", perl_flush, /* user_data = */ NULL);
2260 plugin_register_shutdown("perl", perl_shutdown);
2262 } /* static int init_pi (const char **, const int) */
2265 * LoadPlugin "<Plugin>"
2267 static int perl_config_loadplugin(pTHX_ oconfig_item_t *ci) {
2268 char module_name[DATA_MAX_NAME_LEN];
2272 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2273 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2274 log_err("LoadPlugin expects a single string argument.");
2278 value = ci->values[0].value.string;
2280 if (NULL == get_module_name(module_name, sizeof(module_name), value)) {
2281 log_err("Invalid module name %s", value);
2285 if (0 != init_pi(perl_argc, perl_argv))
2288 assert(NULL != perl_threads);
2289 assert(NULL != perl_threads->head);
2291 aTHX = perl_threads->head->interp;
2293 log_debug("perl_config: Loading Perl plugin \"%s\"", value);
2294 load_module(PERL_LOADMOD_NOIMPORT, newSVpv(module_name, strlen(module_name)),
2297 } /* static int perl_config_loadplugin (oconfig_item_it *) */
2302 static int perl_config_basename(pTHX_ oconfig_item_t *ci) {
2305 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2306 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2307 log_err("BaseName expects a single string argument.");
2311 value = ci->values[0].value.string;
2313 log_debug("perl_config: Setting plugin basename to \"%s\"", value);
2314 sstrncpy(base_name, value, sizeof(base_name));
2316 } /* static int perl_config_basename (oconfig_item_it *) */
2319 * EnableDebugger "<Package>"|""
2321 static int perl_config_enabledebugger(pTHX_ oconfig_item_t *ci) {
2324 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2325 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2326 log_err("EnableDebugger expects a single string argument.");
2330 if (NULL != perl_threads) {
2331 log_warn("EnableDebugger has no effects if used after LoadPlugin.");
2335 value = ci->values[0].value.string;
2337 perl_argv = realloc(perl_argv, (++perl_argc + 1) * sizeof(char *));
2339 if (NULL == perl_argv) {
2340 log_err("perl_config: Not enough memory.");
2344 if ('\0' == value[0]) {
2345 perl_argv[perl_argc - 1] = "-d";
2347 perl_argv[perl_argc - 1] = smalloc(strlen(value) + 4);
2348 sstrncpy(perl_argv[perl_argc - 1], "-d:", 4);
2349 sstrncpy(perl_argv[perl_argc - 1] + 3, value, strlen(value) + 1);
2352 perl_argv[perl_argc] = NULL;
2354 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
2357 * IncludeDir "<Dir>"
2359 static int perl_config_includedir(pTHX_ oconfig_item_t *ci) {
2362 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2363 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2364 log_err("IncludeDir expects a single string argument.");
2368 value = ci->values[0].value.string;
2371 perl_argv = realloc(perl_argv, (++perl_argc + 1) * sizeof(char *));
2373 if (NULL == perl_argv) {
2374 log_err("perl_config: Not enough memory.");
2378 perl_argv[perl_argc - 1] = smalloc(strlen(value) + 3);
2379 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
2380 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen(value) + 1);
2382 perl_argv[perl_argc] = NULL;
2384 /* prepend the directory to @INC */
2385 av_unshift(GvAVn(PL_incgv), 1);
2386 av_store(GvAVn(PL_incgv), 0, newSVpv(value, strlen(value)));
2389 } /* static int perl_config_includedir (oconfig_item_it *) */
2394 static int perl_config_plugin(pTHX_ oconfig_item_t *ci) {
2401 if (NULL == perl_threads) {
2402 log_err("A `Plugin' block was encountered but no plugin was loaded yet. "
2403 "Put the appropriate `LoadPlugin' option in front of it.");
2409 if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2410 log_err("LoadPlugin expects a single string argument.");
2414 plugin = ci->values[0].value.string;
2417 if (0 != oconfig_item2hv(aTHX_ ci, config)) {
2421 log_err("Unable to convert configuration to a Perl hash value.");
2422 config = (HV *)&PL_sv_undef;
2430 XPUSHs(sv_2mortal(newSVpv(plugin, 0)));
2431 XPUSHs(sv_2mortal(newRV_noinc((SV *)config)));
2435 retvals = call_pv("Collectd::_plugin_dispatch_config", G_SCALAR);
2449 } /* static int perl_config_plugin (oconfig_item_it *) */
2451 static int perl_config(oconfig_item_t *ci) {
2456 for (int i = 0; i < ci->children_num; ++i) {
2457 oconfig_item_t *c = ci->children + i;
2458 int current_status = 0;
2460 if (NULL != perl_threads) {
2461 if ((aTHX = PERL_GET_CONTEXT) == NULL)
2465 if (0 == strcasecmp(c->key, "LoadPlugin"))
2466 current_status = perl_config_loadplugin(aTHX_ c);
2467 else if (0 == strcasecmp(c->key, "BaseName"))
2468 current_status = perl_config_basename(aTHX_ c);
2469 else if (0 == strcasecmp(c->key, "EnableDebugger"))
2470 current_status = perl_config_enabledebugger(aTHX_ c);
2471 else if (0 == strcasecmp(c->key, "IncludeDir"))
2472 current_status = perl_config_includedir(aTHX_ c);
2473 else if (0 == strcasecmp(c->key, "Plugin"))
2474 current_status = perl_config_plugin(aTHX_ c);
2476 log_warn("Ignoring unknown config key \"%s\".", c->key);
2480 /* fatal error - it's up to perl_config_* to clean up */
2481 if (0 > current_status) {
2482 log_err("Configuration failed with a fatal error - "
2483 "plugin disabled!");
2484 return current_status;
2487 status += current_status;
2490 } /* static int perl_config (oconfig_item_t *) */
2492 void module_register(void) {
2494 perl_argv = smalloc((perl_argc + 1) * sizeof(*perl_argv));
2496 /* default options for the Perl interpreter */
2498 perl_argv[1] = "-MCollectd";
2499 perl_argv[2] = "-e";
2501 perl_argv[4] = NULL;
2503 plugin_register_complex_config("perl", perl_config);
2505 } /* void module_register (void) */
2507 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */