1 /**
2 * collectd - src/perl.c
3 * Copyright (C) 2007-2009 Sebastian Harl
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 * and/or sell copies of the Software, and to permit persons to whom the
10 * Software is furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 * DEALINGS IN THE SOFTWARE.
22 *
23 * Authors:
24 * Sebastian Harl <sh at tokkee.org>
25 * Pavel Rochnyak <pavel2000 ngs.ru>
26 **/
28 /*
29 * This plugin embeds a Perl interpreter into collectd and provides an
30 * interface for collectd plugins written in perl.
31 */
33 /* do not automatically get the thread specific Perl interpreter */
34 #define PERL_NO_GET_CONTEXT
36 #define DONT_POISON_SPRINTF_YET 1
37 #include "collectd.h"
39 #undef DONT_POISON_SPRINTF_YET
41 #include <stdbool.h>
43 #include <EXTERN.h>
44 #include <perl.h>
46 #if defined(COLLECT_DEBUG) && COLLECT_DEBUG && defined(__GNUC__) && __GNUC__
47 #undef sprintf
48 #pragma GCC poison sprintf
49 #endif
51 #include <XSUB.h>
53 /* Some versions of Perl define their own version of DEBUG... :-/ */
54 #ifdef DEBUG
55 #undef DEBUG
56 #endif /* DEBUG */
58 /* ... while we want the definition found in plugin.h. */
59 #include "common.h"
60 #include "plugin.h"
62 #include "filter_chain.h"
64 #if !defined(USE_ITHREADS)
65 #error "Perl does not support ithreads!"
66 #endif /* !defined(USE_ITHREADS) */
68 /* clear the Perl sub's stack frame
69 * (this should only be used inside an XSUB) */
70 #define CLEAR_STACK_FRAME PL_stack_sp = PL_stack_base + *PL_markstack_ptr
72 #define PLUGIN_INIT 0
73 #define PLUGIN_READ 1
74 #define PLUGIN_WRITE 2
75 #define PLUGIN_SHUTDOWN 3
76 #define PLUGIN_LOG 4
77 #define PLUGIN_NOTIF 5
78 #define PLUGIN_FLUSH 6
79 #define PLUGIN_FLUSH_ALL 7 /* For collectd-5.6 only */
81 #define PLUGIN_TYPES 8
83 #define PLUGIN_CONFIG 254
84 #define PLUGIN_DATASET 255
86 #define FC_MATCH 0
87 #define FC_TARGET 1
89 #define FC_TYPES 2
91 #define FC_CB_CREATE 0
92 #define FC_CB_DESTROY 1
93 #define FC_CB_EXEC 2
95 #define FC_CB_TYPES 3
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_read);
106 static XS(Collectd_plugin_register_write);
107 static XS(Collectd_plugin_register_log);
108 static XS(Collectd_plugin_register_notification);
109 static XS(Collectd_plugin_register_flush);
110 static XS(Collectd_plugin_unregister_read);
111 static XS(Collectd_plugin_unregister_write);
112 static XS(Collectd_plugin_unregister_log);
113 static XS(Collectd_plugin_unregister_notification);
114 static XS(Collectd_plugin_unregister_flush);
115 static XS(Collectd_plugin_register_ds);
116 static XS(Collectd_plugin_unregister_ds);
117 static XS(Collectd_plugin_dispatch_values);
118 static XS(Collectd_plugin_get_interval);
119 static XS(Collectd__plugin_write);
120 static XS(Collectd__plugin_flush);
121 static XS(Collectd_plugin_dispatch_notification);
122 static XS(Collectd_plugin_log);
123 static XS(Collectd__fc_register);
124 static XS(Collectd_call_by_name);
126 static int perl_read(user_data_t *ud);
127 static int perl_write(const data_set_t *ds, const value_list_t *vl,
128 user_data_t *user_data);
129 static void perl_log(int level, const char *msg, user_data_t *user_data);
130 static int perl_notify(const notification_t *notif, user_data_t *user_data);
131 static int perl_flush(cdtime_t timeout, const char *identifier,
132 user_data_t *user_data);
134 /*
135 * private data types
136 */
138 typedef struct c_ithread_s {
139 /* the thread's Perl interpreter */
140 PerlInterpreter *interp;
141 _Bool running; /* thread is inside Perl interpreter */
142 _Bool shutdown;
143 pthread_t pthread;
145 /* double linked list of threads */
146 struct c_ithread_s *prev;
147 struct c_ithread_s *next;
148 } c_ithread_t;
150 typedef struct {
151 c_ithread_t *head;
152 c_ithread_t *tail;
154 #if COLLECT_DEBUG
155 /* some usage stats */
156 int number_of_threads;
157 #endif /* COLLECT_DEBUG */
159 pthread_mutex_t mutex;
160 pthread_mutexattr_t mutexattr;
161 } c_ithread_list_t;
163 /* name / user_data for Perl matches / targets */
164 typedef struct {
165 char *name;
166 SV *user_data;
167 } pfc_user_data_t;
169 #define PFC_USER_DATA_FREE(data) \
170 do { \
171 sfree((data)->name); \
172 if (NULL != (data)->user_data) \
173 sv_free((data)->user_data); \
174 sfree(data); \
175 } while (0)
177 /*
178 * Public variable
179 */
180 extern char **environ;
182 /*
183 * private variables
184 */
186 static _Bool register_legacy_flush = 1;
188 /* if perl_threads != NULL perl_threads->head must
189 * point to the "base" thread */
190 static c_ithread_list_t *perl_threads = NULL;
192 /* the key used to store each pthread's ithread */
193 static pthread_key_t perl_thr_key;
195 static int perl_argc = 0;
196 static char **perl_argv = NULL;
198 static char base_name[DATA_MAX_NAME_LEN] = "";
200 static struct {
201 char name[64];
202 XS((*f));
203 } api[] = {
204 {"Collectd::plugin_register_read", Collectd_plugin_register_read},
205 {"Collectd::plugin_register_write", Collectd_plugin_register_write},
206 {"Collectd::plugin_register_log", Collectd_plugin_register_log},
207 {"Collectd::plugin_register_notification",
208 Collectd_plugin_register_notification},
209 {"Collectd::plugin_register_flush", Collectd_plugin_register_flush},
210 {"Collectd::plugin_unregister_read", Collectd_plugin_unregister_read},
211 {"Collectd::plugin_unregister_write", Collectd_plugin_unregister_write},
212 {"Collectd::plugin_unregister_log", Collectd_plugin_unregister_log},
213 {"Collectd::plugin_unregister_notification",
214 Collectd_plugin_unregister_notification},
215 {"Collectd::plugin_unregister_flush", Collectd_plugin_unregister_flush},
216 {"Collectd::plugin_register_data_set", Collectd_plugin_register_ds},
217 {"Collectd::plugin_unregister_data_set", Collectd_plugin_unregister_ds},
218 {"Collectd::plugin_dispatch_values", Collectd_plugin_dispatch_values},
219 {"Collectd::plugin_get_interval", Collectd_plugin_get_interval},
220 {"Collectd::_plugin_write", Collectd__plugin_write},
221 {"Collectd::_plugin_flush", Collectd__plugin_flush},
222 {"Collectd::plugin_dispatch_notification",
223 Collectd_plugin_dispatch_notification},
224 {"Collectd::plugin_log", Collectd_plugin_log},
225 {"Collectd::_fc_register", Collectd__fc_register},
226 {"Collectd::call_by_name", Collectd_call_by_name},
227 {"", NULL}};
229 struct {
230 char name[64];
231 int value;
232 } constants[] = {{"Collectd::TYPE_INIT", PLUGIN_INIT},
233 {"Collectd::TYPE_READ", PLUGIN_READ},
234 {"Collectd::TYPE_WRITE", PLUGIN_WRITE},
235 {"Collectd::TYPE_SHUTDOWN", PLUGIN_SHUTDOWN},
236 {"Collectd::TYPE_LOG", PLUGIN_LOG},
237 {"Collectd::TYPE_NOTIF", PLUGIN_NOTIF},
238 {"Collectd::TYPE_FLUSH", PLUGIN_FLUSH},
239 {"Collectd::TYPE_CONFIG", PLUGIN_CONFIG},
240 {"Collectd::TYPE_DATASET", PLUGIN_DATASET},
241 {"Collectd::DS_TYPE_COUNTER", DS_TYPE_COUNTER},
242 {"Collectd::DS_TYPE_GAUGE", DS_TYPE_GAUGE},
243 {"Collectd::DS_TYPE_DERIVE", DS_TYPE_DERIVE},
244 {"Collectd::DS_TYPE_ABSOLUTE", DS_TYPE_ABSOLUTE},
245 {"Collectd::LOG_ERR", LOG_ERR},
246 {"Collectd::LOG_WARNING", LOG_WARNING},
247 {"Collectd::LOG_NOTICE", LOG_NOTICE},
248 {"Collectd::LOG_INFO", LOG_INFO},
249 {"Collectd::LOG_DEBUG", LOG_DEBUG},
250 {"Collectd::FC_MATCH", FC_MATCH},
251 {"Collectd::FC_TARGET", FC_TARGET},
252 {"Collectd::FC_CB_CREATE", FC_CB_CREATE},
253 {"Collectd::FC_CB_DESTROY", FC_CB_DESTROY},
254 {"Collectd::FC_CB_EXEC", FC_CB_EXEC},
255 {"Collectd::FC_MATCH_NO_MATCH", FC_MATCH_NO_MATCH},
256 {"Collectd::FC_MATCH_MATCHES", FC_MATCH_MATCHES},
257 {"Collectd::FC_TARGET_CONTINUE", FC_TARGET_CONTINUE},
258 {"Collectd::FC_TARGET_STOP", FC_TARGET_STOP},
259 {"Collectd::FC_TARGET_RETURN", FC_TARGET_RETURN},
260 {"Collectd::NOTIF_FAILURE", NOTIF_FAILURE},
261 {"Collectd::NOTIF_WARNING", NOTIF_WARNING},
262 {"Collectd::NOTIF_OKAY", NOTIF_OKAY},
263 {"", 0}};
265 struct {
266 char name[64];
267 char *var;
268 } g_strings[] = {{"Collectd::hostname_g", hostname_g}, {"", NULL}};
270 /*
271 * Helper functions for data type conversion.
272 */
274 /*
275 * data source:
276 * [
277 * {
278 * name => $ds_name,
279 * type => $ds_type,
280 * min => $ds_min,
281 * max => $ds_max
282 * },
283 * ...
284 * ]
285 */
286 static int hv2data_source(pTHX_ HV *hash, data_source_t *ds) {
287 SV **tmp = NULL;
289 if ((NULL == hash) || (NULL == ds))
290 return -1;
292 if (NULL != (tmp = hv_fetch(hash, "name", 4, 0))) {
293 sstrncpy(ds->name, SvPV_nolen(*tmp), sizeof(ds->name));
294 } else {
295 log_err("hv2data_source: No DS name given.");
296 return -1;
297 }
299 if (NULL != (tmp = hv_fetch(hash, "type", 4, 0))) {
300 ds->type = SvIV(*tmp);
302 if ((DS_TYPE_COUNTER != ds->type) && (DS_TYPE_GAUGE != ds->type) &&
303 (DS_TYPE_DERIVE != ds->type) && (DS_TYPE_ABSOLUTE != ds->type)) {
304 log_err("hv2data_source: Invalid DS type.");
305 return -1;
306 }
307 } else {
308 ds->type = DS_TYPE_COUNTER;
309 }
311 if (NULL != (tmp = hv_fetch(hash, "min", 3, 0)))
312 ds->min = SvNV(*tmp);
313 else
314 ds->min = NAN;
316 if (NULL != (tmp = hv_fetch(hash, "max", 3, 0)))
317 ds->max = SvNV(*tmp);
318 else
319 ds->max = NAN;
320 return 0;
321 } /* static int hv2data_source (HV *, data_source_t *) */
323 /* av2value converts at most "len" elements from "array" to "value". Returns the
324 * number of elements converted or zero on error. */
325 static size_t av2value(pTHX_ char *name, AV *array, value_t *value,
326 size_t array_len) {
327 const data_set_t *ds;
329 if ((NULL == name) || (NULL == array) || (NULL == value) || (array_len == 0))
330 return 0;
332 ds = plugin_get_ds(name);
333 if (NULL == ds) {
334 log_err("av2value: Unknown dataset \"%s\"", name);
335 return 0;
336 }
338 if (array_len < ds->ds_num) {
339 log_warn("av2value: array does not contain enough elements for type "
340 "\"%s\": got %zu, want %zu",
341 name, array_len, ds->ds_num);
342 return 0;
343 } else if (array_len > ds->ds_num) {
344 log_warn("av2value: array contains excess elements for type \"%s\": got "
345 "%zu, want %zu",
346 name, array_len, ds->ds_num);
347 }
349 for (size_t i = 0; i < ds->ds_num; ++i) {
350 SV **tmp = av_fetch(array, i, 0);
352 if (NULL != tmp) {
353 if (DS_TYPE_COUNTER == ds->ds[i].type)
354 value[i].counter = SvIV(*tmp);
355 else if (DS_TYPE_GAUGE == ds->ds[i].type)
356 value[i].gauge = SvNV(*tmp);
357 else if (DS_TYPE_DERIVE == ds->ds[i].type)
358 value[i].derive = SvIV(*tmp);
359 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
360 value[i].absolute = SvIV(*tmp);
361 } else {
362 return 0;
363 }
364 }
366 return ds->ds_num;
367 } /* static size_t av2value (char *, AV *, value_t *, size_t) */
369 /*
370 * value list:
371 * {
372 * values => [ @values ],
373 * time => $time,
374 * host => $host,
375 * plugin => $plugin,
376 * plugin_instance => $pinstance,
377 * type_instance => $tinstance,
378 * }
379 */
380 static int hv2value_list(pTHX_ HV *hash, value_list_t *vl) {
381 SV **tmp;
383 if ((NULL == hash) || (NULL == vl))
384 return -1;
386 if (NULL == (tmp = hv_fetch(hash, "type", 4, 0))) {
387 log_err("hv2value_list: No type given.");
388 return -1;
389 }
391 sstrncpy(vl->type, SvPV_nolen(*tmp), sizeof(vl->type));
393 if ((NULL == (tmp = hv_fetch(hash, "values", 6, 0))) ||
394 (!(SvROK(*tmp) && (SVt_PVAV == SvTYPE(SvRV(*tmp)))))) {
395 log_err("hv2value_list: No valid values given.");
396 return -1;
397 }
399 {
400 AV *array = (AV *)SvRV(*tmp);
401 /* av_len returns the highest index, not the actual length. */
402 size_t array_len = (size_t)(av_len(array) + 1);
403 if (array_len == 0)
404 return -1;
406 vl->values = calloc(array_len, sizeof(*vl->values));
407 vl->values_len =
408 av2value(aTHX_ vl->type, (AV *)SvRV(*tmp), vl->values, array_len);
409 if (vl->values_len == 0) {
410 sfree(vl->values);
411 return -1;
412 }
413 }
415 if (NULL != (tmp = hv_fetch(hash, "time", 4, 0))) {
416 double t = SvNV(*tmp);
417 vl->time = DOUBLE_TO_CDTIME_T(t);
418 }
420 if (NULL != (tmp = hv_fetch(hash, "interval", 8, 0))) {
421 double t = SvNV(*tmp);
422 vl->interval = DOUBLE_TO_CDTIME_T(t);
423 }
425 if (NULL != (tmp = hv_fetch(hash, "host", 4, 0)))
426 sstrncpy(vl->host, SvPV_nolen(*tmp), sizeof(vl->host));
427 else
428 sstrncpy(vl->host, hostname_g, sizeof(vl->host));
430 if (NULL != (tmp = hv_fetch(hash, "plugin", 6, 0)))
431 sstrncpy(vl->plugin, SvPV_nolen(*tmp), sizeof(vl->plugin));
433 if (NULL != (tmp = hv_fetch(hash, "plugin_instance", 15, 0)))
434 sstrncpy(vl->plugin_instance, SvPV_nolen(*tmp),
435 sizeof(vl->plugin_instance));
437 if (NULL != (tmp = hv_fetch(hash, "type_instance", 13, 0)))
438 sstrncpy(vl->type_instance, SvPV_nolen(*tmp), sizeof(vl->type_instance));
439 return 0;
440 } /* static int hv2value_list (pTHX_ HV *, value_list_t *) */
442 static int av2data_set(pTHX_ AV *array, char *name, data_set_t *ds) {
443 int len;
445 if ((NULL == array) || (NULL == name) || (NULL == ds))
446 return -1;
448 len = av_len(array);
450 if (-1 == len) {
451 log_err("av2data_set: Invalid data set.");
452 return -1;
453 }
455 ds->ds = smalloc((len + 1) * sizeof(*ds->ds));
456 ds->ds_num = len + 1;
458 for (int i = 0; i <= len; ++i) {
459 SV **elem = av_fetch(array, i, 0);
461 if (NULL == elem) {
462 log_err("av2data_set: Failed to fetch data source %i.", i);
463 return -1;
464 }
466 if (!(SvROK(*elem) && (SVt_PVHV == SvTYPE(SvRV(*elem))))) {
467 log_err("av2data_set: Invalid data source.");
468 return -1;
469 }
471 if (-1 == hv2data_source(aTHX_(HV *) SvRV(*elem), &ds->ds[i]))
472 return -1;
474 log_debug("av2data_set: "
475 "DS.name = \"%s\", DS.type = %i, DS.min = %f, DS.max = %f",
476 ds->ds[i].name, ds->ds[i].type, ds->ds[i].min, ds->ds[i].max);
477 }
479 sstrncpy(ds->type, name, sizeof(ds->type));
480 return 0;
481 } /* static int av2data_set (pTHX_ AV *, data_set_t *) */
483 /*
484 * notification:
485 * {
486 * severity => $severity,
487 * time => $time,
488 * message => $msg,
489 * host => $host,
490 * plugin => $plugin,
491 * type => $type,
492 * plugin_instance => $instance,
493 * type_instance => $type_instance,
494 * meta => [ { name => <name>, value => <value> }, ... ]
495 * }
496 */
497 static int av2notification_meta(pTHX_ AV *array, notification_meta_t **meta) {
498 notification_meta_t **m = meta;
500 int len = av_len(array);
502 for (int i = 0; i <= len; ++i) {
503 SV **tmp = av_fetch(array, i, 0);
504 HV *hash;
506 if (NULL == tmp)
507 return -1;
509 if (!(SvROK(*tmp) && (SVt_PVHV == SvTYPE(SvRV(*tmp))))) {
510 log_warn("av2notification_meta: Skipping invalid "
511 "meta information.");
512 continue;
513 }
515 hash = (HV *)SvRV(*tmp);
517 *m = smalloc(sizeof(**m));
519 if (NULL == (tmp = hv_fetch(hash, "name", 4, 0))) {
520 log_warn("av2notification_meta: Skipping invalid "
521 "meta information.");
522 free(*m);
523 continue;
524 }
525 sstrncpy((*m)->name, SvPV_nolen(*tmp), sizeof((*m)->name));
527 if (NULL == (tmp = hv_fetch(hash, "value", 5, 0))) {
528 log_warn("av2notification_meta: Skipping invalid "
529 "meta information.");
530 free(*m);
531 continue;
532 }
534 if (SvNOK(*tmp)) {
535 (*m)->nm_value.nm_double = SvNVX(*tmp);
536 (*m)->type = NM_TYPE_DOUBLE;
537 } else if (SvUOK(*tmp)) {
538 (*m)->nm_value.nm_unsigned_int = SvUVX(*tmp);
539 (*m)->type = NM_TYPE_UNSIGNED_INT;
540 } else if (SvIOK(*tmp)) {
541 (*m)->nm_value.nm_signed_int = SvIVX(*tmp);
542 (*m)->type = NM_TYPE_SIGNED_INT;
543 } else {
544 (*m)->nm_value.nm_string = sstrdup(SvPV_nolen(*tmp));
545 (*m)->type = NM_TYPE_STRING;
546 }
548 (*m)->next = NULL;
549 m = &((*m)->next);
550 }
551 return 0;
552 } /* static int av2notification_meta (AV *, notification_meta_t *) */
554 static int hv2notification(pTHX_ HV *hash, notification_t *n) {
555 SV **tmp = NULL;
557 if ((NULL == hash) || (NULL == n))
558 return -1;
560 if (NULL != (tmp = hv_fetch(hash, "severity", 8, 0)))
561 n->severity = SvIV(*tmp);
562 else
563 n->severity = NOTIF_FAILURE;
565 if (NULL != (tmp = hv_fetch(hash, "time", 4, 0))) {
566 double t = SvNV(*tmp);
567 n->time = DOUBLE_TO_CDTIME_T(t);
568 } else
569 n->time = cdtime();
571 if (NULL != (tmp = hv_fetch(hash, "message", 7, 0)))
572 sstrncpy(n->message, SvPV_nolen(*tmp), sizeof(n->message));
574 if (NULL != (tmp = hv_fetch(hash, "host", 4, 0)))
575 sstrncpy(n->host, SvPV_nolen(*tmp), sizeof(n->host));
576 else
577 sstrncpy(n->host, hostname_g, sizeof(n->host));
579 if (NULL != (tmp = hv_fetch(hash, "plugin", 6, 0)))
580 sstrncpy(n->plugin, SvPV_nolen(*tmp), sizeof(n->plugin));
582 if (NULL != (tmp = hv_fetch(hash, "plugin_instance", 15, 0)))
583 sstrncpy(n->plugin_instance, SvPV_nolen(*tmp), sizeof(n->plugin_instance));
585 if (NULL != (tmp = hv_fetch(hash, "type", 4, 0)))
586 sstrncpy(n->type, SvPV_nolen(*tmp), sizeof(n->type));
588 if (NULL != (tmp = hv_fetch(hash, "type_instance", 13, 0)))
589 sstrncpy(n->type_instance, SvPV_nolen(*tmp), sizeof(n->type_instance));
591 n->meta = NULL;
592 while (NULL != (tmp = hv_fetch(hash, "meta", 4, 0))) {
593 if (!(SvROK(*tmp) && (SVt_PVAV == SvTYPE(SvRV(*tmp))))) {
594 log_warn("hv2notification: Ignoring invalid meta information.");
595 break;
596 }
598 if (0 != av2notification_meta(aTHX_(AV *) SvRV(*tmp), &n->meta)) {
599 plugin_notification_meta_free(n->meta);
600 n->meta = NULL;
601 return -1;
602 }
603 break;
604 }
605 return 0;
606 } /* static int hv2notification (pTHX_ HV *, notification_t *) */
608 static int data_set2av(pTHX_ data_set_t *ds, AV *array) {
609 if ((NULL == ds) || (NULL == array))
610 return -1;
612 av_extend(array, ds->ds_num);
614 for (size_t i = 0; i < ds->ds_num; ++i) {
615 HV *source = newHV();
617 if (NULL == hv_store(source, "name", 4, newSVpv(ds->ds[i].name, 0), 0))
618 return -1;
620 if (NULL == hv_store(source, "type", 4, newSViv(ds->ds[i].type), 0))
621 return -1;
623 if (!isnan(ds->ds[i].min))
624 if (NULL == hv_store(source, "min", 3, newSVnv(ds->ds[i].min), 0))
625 return -1;
627 if (!isnan(ds->ds[i].max))
628 if (NULL == hv_store(source, "max", 3, newSVnv(ds->ds[i].max), 0))
629 return -1;
631 if (NULL == av_store(array, i, newRV_noinc((SV *)source)))
632 return -1;
633 }
634 return 0;
635 } /* static int data_set2av (data_set_t *, AV *) */
637 static int value_list2hv(pTHX_ value_list_t *vl, data_set_t *ds, HV *hash) {
638 AV *values = NULL;
639 size_t i;
641 if ((NULL == vl) || (NULL == ds) || (NULL == hash))
642 return -1;
644 values = newAV();
645 /* av_extend takes the last *index* to which the array should be extended. */
646 av_extend(values, vl->values_len - 1);
648 assert(ds->ds_num == vl->values_len);
649 for (i = 0; i < vl->values_len; ++i) {
650 SV *val = NULL;
652 if (DS_TYPE_COUNTER == ds->ds[i].type)
653 val = newSViv(vl->values[i].counter);
654 else if (DS_TYPE_GAUGE == ds->ds[i].type)
655 val = newSVnv(vl->values[i].gauge);
656 else if (DS_TYPE_DERIVE == ds->ds[i].type)
657 val = newSViv(vl->values[i].derive);
658 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
659 val = newSViv(vl->values[i].absolute);
661 if (NULL == av_store(values, i, val)) {
662 av_undef(values);
663 return -1;
664 }
665 }
667 if (NULL == hv_store(hash, "values", 6, newRV_noinc((SV *)values), 0))
668 return -1;
670 if (0 != vl->time) {
671 double t = CDTIME_T_TO_DOUBLE(vl->time);
672 if (NULL == hv_store(hash, "time", 4, newSVnv(t), 0))
673 return -1;
674 }
676 {
677 double t = CDTIME_T_TO_DOUBLE(vl->interval);
678 if (NULL == hv_store(hash, "interval", 8, newSVnv(t), 0))
679 return -1;
680 }
682 if ('\0' != vl->host[0])
683 if (NULL == hv_store(hash, "host", 4, newSVpv(vl->host, 0), 0))
684 return -1;
686 if ('\0' != vl->plugin[0])
687 if (NULL == hv_store(hash, "plugin", 6, newSVpv(vl->plugin, 0), 0))
688 return -1;
690 if ('\0' != vl->plugin_instance[0])
691 if (NULL == hv_store(hash, "plugin_instance", 15,
692 newSVpv(vl->plugin_instance, 0), 0))
693 return -1;
695 if ('\0' != vl->type[0])
696 if (NULL == hv_store(hash, "type", 4, newSVpv(vl->type, 0), 0))
697 return -1;
699 if ('\0' != vl->type_instance[0])
700 if (NULL ==
701 hv_store(hash, "type_instance", 13, newSVpv(vl->type_instance, 0), 0))
702 return -1;
703 return 0;
704 } /* static int value2av (value_list_t *, data_set_t *, HV *) */
706 static int notification_meta2av(pTHX_ notification_meta_t *meta, AV *array) {
707 int meta_num = 0;
709 while (meta) {
710 ++meta_num;
711 meta = meta->next;
712 }
714 av_extend(array, meta_num);
716 for (int i = 0; NULL != meta; meta = meta->next, ++i) {
717 HV *m = newHV();
718 SV *value;
720 if (NULL == hv_store(m, "name", 4, newSVpv(meta->name, 0), 0))
721 return -1;
723 if (NM_TYPE_STRING == meta->type)
724 value = newSVpv(meta->nm_value.nm_string, 0);
725 else if (NM_TYPE_SIGNED_INT == meta->type)
726 value = newSViv(meta->nm_value.nm_signed_int);
727 else if (NM_TYPE_UNSIGNED_INT == meta->type)
728 value = newSVuv(meta->nm_value.nm_unsigned_int);
729 else if (NM_TYPE_DOUBLE == meta->type)
730 value = newSVnv(meta->nm_value.nm_double);
731 else if (NM_TYPE_BOOLEAN == meta->type)
732 value = meta->nm_value.nm_boolean ? &PL_sv_yes : &PL_sv_no;
733 else
734 return -1;
736 if (NULL == hv_store(m, "value", 5, value, 0)) {
737 sv_free(value);
738 return -1;
739 }
741 if (NULL == av_store(array, i, newRV_noinc((SV *)m))) {
742 hv_clear(m);
743 hv_undef(m);
744 return -1;
745 }
746 }
747 return 0;
748 } /* static int notification_meta2av (notification_meta_t *, AV *) */
750 static int notification2hv(pTHX_ notification_t *n, HV *hash) {
751 if (NULL == hv_store(hash, "severity", 8, newSViv(n->severity), 0))
752 return -1;
754 if (0 != n->time) {
755 double t = CDTIME_T_TO_DOUBLE(n->time);
756 if (NULL == hv_store(hash, "time", 4, newSVnv(t), 0))
757 return -1;
758 }
760 if ('\0' != *n->message)
761 if (NULL == hv_store(hash, "message", 7, newSVpv(n->message, 0), 0))
762 return -1;
764 if ('\0' != *n->host)
765 if (NULL == hv_store(hash, "host", 4, newSVpv(n->host, 0), 0))
766 return -1;
768 if ('\0' != *n->plugin)
769 if (NULL == hv_store(hash, "plugin", 6, newSVpv(n->plugin, 0), 0))
770 return -1;
772 if ('\0' != *n->plugin_instance)
773 if (NULL == hv_store(hash, "plugin_instance", 15,
774 newSVpv(n->plugin_instance, 0), 0))
775 return -1;
777 if ('\0' != *n->type)
778 if (NULL == hv_store(hash, "type", 4, newSVpv(n->type, 0), 0))
779 return -1;
781 if ('\0' != *n->type_instance)
782 if (NULL ==
783 hv_store(hash, "type_instance", 13, newSVpv(n->type_instance, 0), 0))
784 return -1;
786 if (NULL != n->meta) {
787 AV *meta = newAV();
788 if ((0 != notification_meta2av(aTHX_ n->meta, meta)) ||
789 (NULL == hv_store(hash, "meta", 4, newRV_noinc((SV *)meta), 0))) {
790 av_clear(meta);
791 av_undef(meta);
792 return -1;
793 }
794 }
795 return 0;
796 } /* static int notification2hv (notification_t *, HV *) */
798 static int oconfig_item2hv(pTHX_ oconfig_item_t *ci, HV *hash) {
799 AV *values;
800 AV *children;
802 if (NULL == hv_store(hash, "key", 3, newSVpv(ci->key, 0), 0))
803 return -1;
805 values = newAV();
806 if (0 < ci->values_num)
807 av_extend(values, ci->values_num);
809 if (NULL == hv_store(hash, "values", 6, newRV_noinc((SV *)values), 0)) {
810 av_clear(values);
811 av_undef(values);
812 return -1;
813 }
815 for (int i = 0; i < ci->values_num; ++i) {
816 SV *value;
818 switch (ci->values[i].type) {
819 case OCONFIG_TYPE_STRING:
820 value = newSVpv(ci->values[i].value.string, 0);
821 break;
822 case OCONFIG_TYPE_NUMBER:
823 value = newSVnv((NV)ci->values[i].value.number);
824 break;
825 case OCONFIG_TYPE_BOOLEAN:
826 value = ci->values[i].value.boolean ? &PL_sv_yes : &PL_sv_no;
827 break;
828 default:
829 log_err("oconfig_item2hv: Invalid value type %i.", ci->values[i].type);
830 value = &PL_sv_undef;
831 }
833 if (NULL == av_store(values, i, value)) {
834 sv_free(value);
835 return -1;
836 }
837 }
839 /* ignoring 'parent' member which is uninteresting in this case */
841 children = newAV();
842 if (0 < ci->children_num)
843 av_extend(children, ci->children_num);
845 if (NULL == hv_store(hash, "children", 8, newRV_noinc((SV *)children), 0)) {
846 av_clear(children);
847 av_undef(children);
848 return -1;
849 }
851 for (int i = 0; i < ci->children_num; ++i) {
852 HV *child = newHV();
854 if (0 != oconfig_item2hv(aTHX_ ci->children + i, child)) {
855 hv_clear(child);
856 hv_undef(child);
857 return -1;
858 }
860 if (NULL == av_store(children, i, newRV_noinc((SV *)child))) {
861 hv_clear(child);
862 hv_undef(child);
863 return -1;
864 }
865 }
866 return 0;
867 } /* static int oconfig_item2hv (pTHX_ oconfig_item_t *, HV *) */
869 /*
870 * Internal functions.
871 */
873 static char *get_module_name(char *buf, size_t buf_len, const char *module) {
874 int status = 0;
875 if (base_name[0] == '\0')
876 status = ssnprintf(buf, buf_len, "%s", module);
877 else
878 status = ssnprintf(buf, buf_len, "%s::%s", base_name, module);
879 if ((status < 0) || ((unsigned int)status >= buf_len))
880 return (NULL);
881 return (buf);
882 } /* char *get_module_name */
884 /*
885 * Add a plugin's data set definition.
886 */
887 static int pplugin_register_data_set(pTHX_ char *name, AV *dataset) {
888 int ret = 0;
890 data_set_t ds;
892 if ((NULL == name) || (NULL == dataset))
893 return -1;
895 if (0 != av2data_set(aTHX_ dataset, name, &ds))
896 return -1;
898 ret = plugin_register_data_set(&ds);
900 free(ds.ds);
901 return ret;
902 } /* static int pplugin_register_data_set (char *, SV *) */
904 /*
905 * Remove a plugin's data set definition.
906 */
907 static int pplugin_unregister_data_set(char *name) {
908 if (NULL == name)
909 return 0;
910 return plugin_unregister_data_set(name);
911 } /* static int pplugin_unregister_data_set (char *) */
913 /*
914 * Submit the values to the write functions.
915 */
916 static int pplugin_dispatch_values(pTHX_ HV *values) {
917 value_list_t vl = VALUE_LIST_INIT;
919 int ret = 0;
921 if (NULL == values)
922 return -1;
924 if (0 != hv2value_list(aTHX_ values, &vl))
925 return -1;
927 ret = plugin_dispatch_values(&vl);
929 sfree(vl.values);
930 return ret;
931 } /* static int pplugin_dispatch_values (char *, HV *) */
933 /*
934 * Submit the values to a single write function.
935 */
936 static int pplugin_write(pTHX_ const char *plugin, AV *data_set, HV *values) {
937 data_set_t ds;
938 value_list_t vl = VALUE_LIST_INIT;
940 int ret;
942 if (NULL == values)
943 return -1;
945 if (0 != hv2value_list(aTHX_ values, &vl))
946 return -1;
948 if ((NULL != data_set) && (0 != av2data_set(aTHX_ data_set, vl.type, &ds)))
949 return -1;
951 ret = plugin_write(plugin, NULL == data_set ? NULL : &ds, &vl);
952 if (0 != ret)
953 log_warn("Dispatching value to plugin \"%s\" failed with status %i.",
954 NULL == plugin ? "<any>" : plugin, ret);
956 if (NULL != data_set)
957 sfree(ds.ds);
958 sfree(vl.values);
959 return ret;
960 } /* static int pplugin_write (const char *plugin, HV *, HV *) */
962 /*
963 * Dispatch a notification.
964 */
965 static int pplugin_dispatch_notification(pTHX_ HV *notif) {
966 notification_t n = {0};
968 int ret;
970 if (NULL == notif)
971 return -1;
973 if (0 != hv2notification(aTHX_ notif, &n))
974 return -1;
976 ret = plugin_dispatch_notification(&n);
977 plugin_notification_meta_free(n.meta);
978 return ret;
979 } /* static int pplugin_dispatch_notification (HV *) */
981 /*
982 * Call perl sub with thread locking flags handled.
983 */
984 static int call_pv_locked(pTHX_ const char *sub_name) {
985 _Bool old_running;
986 int ret;
988 c_ithread_t *t = (c_ithread_t *)pthread_getspecific(perl_thr_key);
989 if (t == NULL) /* thread destroyed */
990 return 0;
992 old_running = t->running;
993 t->running = 1;
995 if (t->shutdown) {
996 t->running = old_running;
997 return 0;
998 }
1000 ret = call_pv(sub_name, G_SCALAR | G_EVAL);
1002 t->running = old_running;
1003 return ret;
1004 } /* static int call_pv_locked (pTHX, *sub_name) */
1006 /*
1007 * Call all working functions of the given type.
1008 */
1009 static int pplugin_call(pTHX_ int type, ...) {
1010 int retvals = 0;
1012 va_list ap;
1013 int ret = 0;
1014 char *subname;
1016 dSP;
1018 if ((type < 0) || (type >= PLUGIN_TYPES))
1019 return -1;
1021 va_start(ap, type);
1023 ENTER;
1024 SAVETMPS;
1026 PUSHMARK(SP);
1028 if (PLUGIN_READ == type) {
1029 subname = va_arg(ap, char *);
1030 } else if (PLUGIN_WRITE == type) {
1031 data_set_t *ds;
1032 value_list_t *vl;
1034 AV *pds = newAV();
1035 HV *pvl = newHV();
1037 subname = va_arg(ap, char *);
1038 /*
1039 * $_[0] = $plugin_type;
1040 *
1041 * $_[1] =
1042 * [
1043 * {
1044 * name => $ds_name,
1045 * type => $ds_type,
1046 * min => $ds_min,
1047 * max => $ds_max
1048 * },
1049 * ...
1050 * ];
1051 *
1052 * $_[2] =
1053 * {
1054 * values => [ $v1, ... ],
1055 * time => $time,
1056 * host => $hostname,
1057 * plugin => $plugin,
1058 * type => $type,
1059 * plugin_instance => $instance,
1060 * type_instance => $type_instance
1061 * };
1062 */
1063 ds = va_arg(ap, data_set_t *);
1064 vl = va_arg(ap, value_list_t *);
1066 if (-1 == data_set2av(aTHX_ ds, pds)) {
1067 av_clear(pds);
1068 av_undef(pds);
1069 pds = (AV *)&PL_sv_undef;
1070 ret = -1;
1071 }
1073 if (-1 == value_list2hv(aTHX_ vl, ds, pvl)) {
1074 hv_clear(pvl);
1075 hv_undef(pvl);
1076 pvl = (HV *)&PL_sv_undef;
1077 ret = -1;
1078 }
1080 XPUSHs(sv_2mortal(newSVpv(ds->type, 0)));
1081 XPUSHs(sv_2mortal(newRV_noinc((SV *)pds)));
1082 XPUSHs(sv_2mortal(newRV_noinc((SV *)pvl)));
1083 } else if (PLUGIN_LOG == type) {
1084 subname = va_arg(ap, char *);
1085 /*
1086 * $_[0] = $level;
1087 *
1088 * $_[1] = $message;
1089 */
1090 XPUSHs(sv_2mortal(newSViv(va_arg(ap, int))));
1091 XPUSHs(sv_2mortal(newSVpv(va_arg(ap, char *), 0)));
1092 } else if (PLUGIN_NOTIF == type) {
1093 notification_t *n;
1094 HV *notif = newHV();
1096 subname = va_arg(ap, char *);
1097 /*
1098 * $_[0] =
1099 * {
1100 * severity => $severity,
1101 * time => $time,
1102 * message => $msg,
1103 * host => $host,
1104 * plugin => $plugin,
1105 * type => $type,
1106 * plugin_instance => $instance,
1107 * type_instance => $type_instance
1108 * };
1109 */
1110 n = va_arg(ap, notification_t *);
1112 if (-1 == notification2hv(aTHX_ n, notif)) {
1113 hv_clear(notif);
1114 hv_undef(notif);
1115 notif = (HV *)&PL_sv_undef;
1116 ret = -1;
1117 }
1119 XPUSHs(sv_2mortal(newRV_noinc((SV *)notif)));
1120 } else if (PLUGIN_FLUSH == type) {
1121 cdtime_t timeout;
1122 subname = va_arg(ap, char *);
1123 /*
1124 * $_[0] = $timeout;
1125 * $_[1] = $identifier;
1126 */
1127 timeout = va_arg(ap, cdtime_t);
1129 XPUSHs(sv_2mortal(newSVnv(CDTIME_T_TO_DOUBLE(timeout))));
1130 XPUSHs(sv_2mortal(newSVpv(va_arg(ap, char *), 0)));
1131 } else if (PLUGIN_FLUSH_ALL == type) {
1132 cdtime_t timeout;
1133 subname = "Collectd::plugin_call_all";
1134 /*
1135 * $_[0] = $timeout;
1136 * $_[1] = $identifier;
1137 */
1138 timeout = va_arg(ap, cdtime_t);
1140 XPUSHs(sv_2mortal(newSViv((IV)PLUGIN_FLUSH)));
1141 XPUSHs(sv_2mortal(newSVnv(CDTIME_T_TO_DOUBLE(timeout))));
1142 XPUSHs(sv_2mortal(newSVpv(va_arg(ap, char *), 0)));
1143 } else if (PLUGIN_INIT == type) {
1144 subname = "Collectd::plugin_call_all";
1145 XPUSHs(sv_2mortal(newSViv((IV)type)));
1146 } else if (PLUGIN_SHUTDOWN == type) {
1147 subname = "Collectd::plugin_call_all";
1148 XPUSHs(sv_2mortal(newSViv((IV)type)));
1149 } else { /* Unknown type. Run 'plugin_call_all' and make compiler happy */
1150 subname = "Collectd::plugin_call_all";
1151 XPUSHs(sv_2mortal(newSViv((IV)type)));
1152 }
1154 PUTBACK;
1156 retvals = call_pv_locked(aTHX_ subname);
1158 SPAGAIN;
1159 if (SvTRUE(ERRSV)) {
1160 if (PLUGIN_LOG != type)
1161 ERROR("perl: %s error: %s", subname, SvPV_nolen(ERRSV));
1162 ret = -1;
1163 } else if (0 < retvals) {
1164 SV *tmp = POPs;
1165 if (!SvTRUE(tmp))
1166 ret = -1;
1167 }
1169 PUTBACK;
1170 FREETMPS;
1171 LEAVE;
1173 va_end(ap);
1174 return ret;
1175 } /* static int pplugin_call (int, ...) */
1177 /*
1178 * collectd's Perl interpreter based thread implementation.
1179 *
1180 * This has been inspired by Perl's ithreads introduced in version 5.6.0.
1181 */
1183 /* must be called with perl_threads->mutex locked */
1184 static void c_ithread_destroy(c_ithread_t *ithread) {
1185 dTHXa(ithread->interp);
1187 assert(NULL != perl_threads);
1189 PERL_SET_CONTEXT(aTHX);
1190 /* Mark as running to avoid deadlock:
1191 c_ithread_destroy -> log_debug -> perl_log()
1192 */
1193 ithread->running = 1;
1194 log_debug("Shutting down Perl interpreter %p...", aTHX);
1196 #if COLLECT_DEBUG
1197 sv_report_used();
1199 --perl_threads->number_of_threads;
1200 #endif /* COLLECT_DEBUG */
1202 perl_destruct(aTHX);
1203 perl_free(aTHX);
1205 if (NULL == ithread->prev)
1206 perl_threads->head = ithread->next;
1207 else
1208 ithread->prev->next = ithread->next;
1210 if (NULL == ithread->next)
1211 perl_threads->tail = ithread->prev;
1212 else
1213 ithread->next->prev = ithread->prev;
1215 sfree(ithread);
1216 return;
1217 } /* static void c_ithread_destroy (c_ithread_t *) */
1219 static void c_ithread_destructor(void *arg) {
1220 c_ithread_t *ithread = (c_ithread_t *)arg;
1221 c_ithread_t *t = NULL;
1223 if (NULL == perl_threads)
1224 return;
1226 pthread_mutex_lock(&perl_threads->mutex);
1228 for (t = perl_threads->head; NULL != t; t = t->next)
1229 if (t == ithread)
1230 break;
1232 /* the ithread no longer exists */
1233 if (NULL == t) {
1234 pthread_mutex_unlock(&perl_threads->mutex);
1235 return;
1236 }
1238 c_ithread_destroy(ithread);
1240 pthread_mutex_unlock(&perl_threads->mutex);
1241 return;
1242 } /* static void c_ithread_destructor (void *) */
1244 /* must be called with perl_threads->mutex locked */
1245 static c_ithread_t *c_ithread_create(PerlInterpreter *base) {
1246 c_ithread_t *t = NULL;
1247 dTHXa(NULL);
1249 assert(NULL != perl_threads);
1251 t = smalloc(sizeof(*t));
1252 memset(t, 0, sizeof(c_ithread_t));
1254 t->interp = (NULL == base) ? NULL : perl_clone(base, CLONEf_KEEP_PTR_TABLE);
1256 aTHX = t->interp;
1258 if ((NULL != base) && (NULL != PL_endav)) {
1259 av_clear(PL_endav);
1260 av_undef(PL_endav);
1261 PL_endav = Nullav;
1262 }
1264 #if COLLECT_DEBUG
1265 ++perl_threads->number_of_threads;
1266 #endif /* COLLECT_DEBUG */
1268 t->next = NULL;
1270 if (NULL == perl_threads->tail) {
1271 perl_threads->head = t;
1272 t->prev = NULL;
1273 } else {
1274 perl_threads->tail->next = t;
1275 t->prev = perl_threads->tail;
1276 }
1278 t->pthread = pthread_self();
1279 t->running = 0;
1280 t->shutdown = 0;
1281 perl_threads->tail = t;
1283 pthread_setspecific(perl_thr_key, (const void *)t);
1284 return t;
1285 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
1287 /*
1288 * Filter chains implementation.
1289 */
1291 static int fc_call(pTHX_ int type, int cb_type, pfc_user_data_t *data, ...) {
1292 int retvals = 0;
1294 va_list ap;
1295 int ret = 0;
1297 notification_meta_t **meta = NULL;
1298 AV *pmeta = NULL;
1300 dSP;
1302 if ((type < 0) || (type >= FC_TYPES))
1303 return -1;
1305 if ((cb_type < 0) || (cb_type >= FC_CB_TYPES))
1306 return -1;
1308 va_start(ap, data);
1310 ENTER;
1311 SAVETMPS;
1313 PUSHMARK(SP);
1315 XPUSHs(sv_2mortal(newSViv((IV)type)));
1316 XPUSHs(sv_2mortal(newSVpv(data->name, 0)));
1317 XPUSHs(sv_2mortal(newSViv((IV)cb_type)));
1319 if (FC_CB_CREATE == cb_type) {
1320 /*
1321 * $_[0] = $ci;
1322 * $_[1] = $user_data;
1323 */
1324 oconfig_item_t *ci;
1325 HV *config = newHV();
1327 ci = va_arg(ap, oconfig_item_t *);
1329 if (0 != oconfig_item2hv(aTHX_ ci, config)) {
1330 hv_clear(config);
1331 hv_undef(config);
1332 config = (HV *)&PL_sv_undef;
1333 ret = -1;
1334 }
1336 XPUSHs(sv_2mortal(newRV_noinc((SV *)config)));
1337 } else if (FC_CB_DESTROY == cb_type) {
1338 /*
1339 * $_[1] = $user_data;
1340 */
1342 /* nothing to be done - the user data pointer
1343 * is pushed onto the stack later */
1344 } else if (FC_CB_EXEC == cb_type) {
1345 /*
1346 * $_[0] = $ds;
1347 * $_[1] = $vl;
1348 * $_[2] = $meta;
1349 * $_[3] = $user_data;
1350 */
1351 data_set_t *ds;
1352 value_list_t *vl;
1354 AV *pds = newAV();
1355 HV *pvl = newHV();
1357 ds = va_arg(ap, data_set_t *);
1358 vl = va_arg(ap, value_list_t *);
1359 meta = va_arg(ap, notification_meta_t **);
1361 if (0 != data_set2av(aTHX_ ds, pds)) {
1362 av_clear(pds);
1363 av_undef(pds);
1364 pds = (AV *)&PL_sv_undef;
1365 ret = -1;
1366 }
1368 if (0 != value_list2hv(aTHX_ vl, ds, pvl)) {
1369 hv_clear(pvl);
1370 hv_undef(pvl);
1371 pvl = (HV *)&PL_sv_undef;
1372 ret = -1;
1373 }
1375 if (NULL != meta) {
1376 pmeta = newAV();
1378 if (0 != notification_meta2av(aTHX_ * meta, pmeta)) {
1379 av_clear(pmeta);
1380 av_undef(pmeta);
1381 pmeta = (AV *)&PL_sv_undef;
1382 ret = -1;
1383 }
1384 } else {
1385 pmeta = (AV *)&PL_sv_undef;
1386 }
1388 XPUSHs(sv_2mortal(newRV_noinc((SV *)pds)));
1389 XPUSHs(sv_2mortal(newRV_noinc((SV *)pvl)));
1390 XPUSHs(sv_2mortal(newRV_noinc((SV *)pmeta)));
1391 }
1393 XPUSHs(sv_2mortal(newRV_inc(data->user_data)));
1395 PUTBACK;
1397 retvals = call_pv_locked(aTHX_ "Collectd::fc_call");
1399 if ((FC_CB_EXEC == cb_type) && (meta != NULL)) {
1400 assert(pmeta != NULL);
1402 plugin_notification_meta_free(*meta);
1403 av2notification_meta(aTHX_ pmeta, meta);
1404 }
1406 SPAGAIN;
1407 if (SvTRUE(ERRSV)) {
1408 ERROR("perl: Collectd::fc_call error: %s", SvPV_nolen(ERRSV));
1409 ret = -1;
1410 } else if (0 < retvals) {
1411 SV *tmp = POPs;
1413 /* the exec callbacks return a status, while
1414 * the others return a boolean value */
1415 if (FC_CB_EXEC == cb_type)
1416 ret = SvIV(tmp);
1417 else if (!SvTRUE(tmp))
1418 ret = -1;
1419 }
1421 PUTBACK;
1422 FREETMPS;
1423 LEAVE;
1425 va_end(ap);
1426 return ret;
1427 } /* static int fc_call (int, int, pfc_user_data_t *, ...) */
1429 static int fc_create(int type, const oconfig_item_t *ci, void **user_data) {
1430 pfc_user_data_t *data;
1432 int ret = 0;
1434 dTHX;
1436 if (NULL == perl_threads)
1437 return 0;
1439 if (NULL == aTHX) {
1440 c_ithread_t *t = NULL;
1442 pthread_mutex_lock(&perl_threads->mutex);
1443 t = c_ithread_create(perl_threads->head->interp);
1444 pthread_mutex_unlock(&perl_threads->mutex);
1446 aTHX = t->interp;
1447 }
1449 log_debug("fc_create: c_ithread: interp = %p (active threads: %i)", aTHX,
1450 perl_threads->number_of_threads);
1452 if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1453 log_warn("A \"%s\" block expects a single string argument.",
1454 (FC_MATCH == type) ? "Match" : "Target");
1455 return -1;
1456 }
1458 data = smalloc(sizeof(*data));
1459 data->name = sstrdup(ci->values[0].value.string);
1460 data->user_data = newSV(0);
1462 ret = fc_call(aTHX_ type, FC_CB_CREATE, data, ci);
1464 if (0 != ret)
1465 PFC_USER_DATA_FREE(data);
1466 else
1467 *user_data = data;
1468 return ret;
1469 } /* static int fc_create (int, const oconfig_item_t *, void **) */
1471 static int fc_destroy(int type, void **user_data) {
1472 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1474 int ret = 0;
1476 dTHX;
1478 if ((NULL == perl_threads) || (NULL == data))
1479 return 0;
1481 if (NULL == aTHX) {
1482 c_ithread_t *t = NULL;
1484 pthread_mutex_lock(&perl_threads->mutex);
1485 t = c_ithread_create(perl_threads->head->interp);
1486 pthread_mutex_unlock(&perl_threads->mutex);
1488 aTHX = t->interp;
1489 }
1491 log_debug("fc_destroy: c_ithread: interp = %p (active threads: %i)", aTHX,
1492 perl_threads->number_of_threads);
1494 ret = fc_call(aTHX_ type, FC_CB_DESTROY, data);
1496 PFC_USER_DATA_FREE(data);
1497 *user_data = NULL;
1498 return ret;
1499 } /* static int fc_destroy (int, void **) */
1501 static int fc_exec(int type, const data_set_t *ds, const value_list_t *vl,
1502 notification_meta_t **meta, void **user_data) {
1503 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1505 dTHX;
1507 if (NULL == perl_threads)
1508 return 0;
1510 assert(NULL != data);
1512 if (NULL == aTHX) {
1513 c_ithread_t *t = NULL;
1515 pthread_mutex_lock(&perl_threads->mutex);
1516 t = c_ithread_create(perl_threads->head->interp);
1517 pthread_mutex_unlock(&perl_threads->mutex);
1519 aTHX = t->interp;
1520 }
1522 log_debug("fc_exec: c_ithread: interp = %p (active threads: %i)", aTHX,
1523 perl_threads->number_of_threads);
1525 return fc_call(aTHX_ type, FC_CB_EXEC, data, ds, vl, meta);
1526 } /* static int fc_exec (int, const data_set_t *, const value_list_t *,
1527 notification_meta_t **, void **) */
1529 static int pmatch_create(const oconfig_item_t *ci, void **user_data) {
1530 return fc_create(FC_MATCH, ci, user_data);
1531 } /* static int pmatch_create (const oconfig_item_t *, void **) */
1533 static int pmatch_destroy(void **user_data) {
1534 return fc_destroy(FC_MATCH, user_data);
1535 } /* static int pmatch_destroy (void **) */
1537 static int pmatch_match(const data_set_t *ds, const value_list_t *vl,
1538 notification_meta_t **meta, void **user_data) {
1539 return fc_exec(FC_MATCH, ds, vl, meta, user_data);
1540 } /* static int pmatch_match (const data_set_t *, const value_list_t *,
1541 notification_meta_t **, void **) */
1543 static match_proc_t pmatch = {pmatch_create, pmatch_destroy, pmatch_match};
1545 static int ptarget_create(const oconfig_item_t *ci, void **user_data) {
1546 return fc_create(FC_TARGET, ci, user_data);
1547 } /* static int ptarget_create (const oconfig_item_t *, void **) */
1549 static int ptarget_destroy(void **user_data) {
1550 return fc_destroy(FC_TARGET, user_data);
1551 } /* static int ptarget_destroy (void **) */
1553 static int ptarget_invoke(const data_set_t *ds, value_list_t *vl,
1554 notification_meta_t **meta, void **user_data) {
1555 return fc_exec(FC_TARGET, ds, vl, meta, user_data);
1556 } /* static int ptarget_invoke (const data_set_t *, value_list_t *,
1557 notification_meta_t **, void **) */
1559 static target_proc_t ptarget = {ptarget_create, ptarget_destroy,
1560 ptarget_invoke};
1562 /*
1563 * Exported Perl API.
1564 */
1566 static void _plugin_register_generic_userdata(pTHX, int type,
1567 const char *desc) {
1568 int ret = 0;
1569 user_data_t userdata;
1570 char *pluginname;
1572 dXSARGS;
1574 if (2 != items) {
1575 log_err("Usage: Collectd::plugin_register_%s(pluginname, subname)", desc);
1576 XSRETURN_EMPTY;
1577 }
1579 if (!SvOK(ST(0))) {
1580 log_err("Collectd::plugin_register_%s(pluginname, subname): "
1581 "Invalid pluginname",
1582 desc);
1583 XSRETURN_EMPTY;
1584 }
1585 if (!SvOK(ST(1))) {
1586 log_err("Collectd::plugin_register_%s(pluginname, subname): "
1587 "Invalid subname",
1588 desc);
1589 XSRETURN_EMPTY;
1590 }
1592 /* Use pluginname as-is to allow flush a single perl plugin */
1593 pluginname = SvPV_nolen(ST(0));
1595 log_debug("Collectd::plugin_register_%s: "
1596 "plugin = \"%s\", sub = \"%s\"",
1597 desc, pluginname, SvPV_nolen(ST(1)));
1599 memset(&userdata, 0, sizeof(userdata));
1600 userdata.data = strdup(SvPV_nolen(ST(1)));
1601 userdata.free_func = free;
1603 if (PLUGIN_READ == type) {
1604 ret = plugin_register_complex_read(
1605 "perl", /* group */
1606 pluginname, perl_read, plugin_get_interval(), /* Default interval */
1607 &userdata);
1608 } else if (PLUGIN_WRITE == type) {
1609 ret = plugin_register_write(pluginname, perl_write, &userdata);
1610 } else if (PLUGIN_LOG == type) {
1611 ret = plugin_register_log(pluginname, perl_log, &userdata);
1612 } else if (PLUGIN_NOTIF == type) {
1613 ret = plugin_register_notification(pluginname, perl_notify, &userdata);
1614 } else if (PLUGIN_FLUSH == type) {
1615 if (1 == register_legacy_flush) { /* For collectd-5.7 only, #1731 */
1616 register_legacy_flush = 0;
1617 ret = plugin_register_flush("perl", perl_flush, /* user_data = */ NULL);
1618 }
1620 if (0 == ret)
1621 ret = plugin_register_flush(pluginname, perl_flush, &userdata);
1622 } else {
1623 ret = -1;
1624 }
1626 if (0 == ret)
1627 XSRETURN_YES;
1628 else {
1629 free(userdata.data);
1630 XSRETURN_EMPTY;
1631 }
1632 } /* static void _plugin_register_generic_userdata ( ... ) */
1634 /*
1635 * Collectd::plugin_register_TYPE (pluginname, subname).
1636 *
1637 * pluginname:
1638 * name of the perl plugin
1639 *
1640 * subname:
1641 * name of the plugin's subroutine that does the work
1642 */
1644 static XS(Collectd_plugin_register_read) {
1645 return _plugin_register_generic_userdata(aTHX, PLUGIN_READ, "read");
1646 }
1648 static XS(Collectd_plugin_register_write) {
1649 return _plugin_register_generic_userdata(aTHX, PLUGIN_WRITE, "write");
1650 }
1652 static XS(Collectd_plugin_register_log) {
1653 return _plugin_register_generic_userdata(aTHX, PLUGIN_LOG, "log");
1654 }
1656 static XS(Collectd_plugin_register_notification) {
1657 return _plugin_register_generic_userdata(aTHX, PLUGIN_NOTIF, "notification");
1658 }
1660 static XS(Collectd_plugin_register_flush) {
1661 return _plugin_register_generic_userdata(aTHX, PLUGIN_FLUSH, "flush");
1662 }
1664 typedef int perl_unregister_function_t(const char *name);
1666 static void _plugin_unregister_generic(pTHX, perl_unregister_function_t *unreg,
1667 const char *desc) {
1668 dXSARGS;
1670 if (1 != items) {
1671 log_err("Usage: Collectd::plugin_unregister_%s(pluginname)", desc);
1672 XSRETURN_EMPTY;
1673 }
1675 if (!SvOK(ST(0))) {
1676 log_err("Collectd::plugin_unregister_%s(pluginname): "
1677 "Invalid pluginname",
1678 desc);
1679 XSRETURN_EMPTY;
1680 }
1682 log_debug("Collectd::plugin_unregister_%s: plugin = \"%s\"", desc,
1683 SvPV_nolen(ST(0)));
1685 unreg(SvPV_nolen(ST(0)));
1687 XSRETURN_EMPTY;
1689 return;
1690 } /* static void _plugin_unregister_generic ( ... ) */
1692 /*
1693 * Collectd::plugin_unregister_TYPE (pluginname).
1694 *
1695 * TYPE:
1696 * type of callback to be unregistered: read, write, log, notification, flush
1697 *
1698 * pluginname:
1699 * name of the perl plugin
1700 */
1702 static XS(Collectd_plugin_unregister_read) {
1703 return _plugin_unregister_generic(aTHX, plugin_unregister_read, "read");
1704 }
1706 static XS(Collectd_plugin_unregister_write) {
1707 return _plugin_unregister_generic(aTHX, plugin_unregister_write, "write");
1708 }
1710 static XS(Collectd_plugin_unregister_log) {
1711 return _plugin_unregister_generic(aTHX, plugin_unregister_log, "log");
1712 }
1714 static XS(Collectd_plugin_unregister_notification) {
1715 return _plugin_unregister_generic(aTHX, plugin_unregister_notification,
1716 "notification");
1717 }
1719 static XS(Collectd_plugin_unregister_flush) {
1720 return _plugin_unregister_generic(aTHX, plugin_unregister_flush, "flush");
1721 }
1723 /*
1724 * Collectd::plugin_register_data_set (type, dataset).
1725 *
1726 * type:
1727 * type of the dataset
1728 *
1729 * dataset:
1730 * dataset to be registered
1731 */
1732 static XS(Collectd_plugin_register_ds) {
1733 SV *data = NULL;
1734 int ret = 0;
1736 dXSARGS;
1738 log_warn("Using plugin_register() to register new data-sets is "
1739 "deprecated - add new entries to a custom types.db instead.");
1741 if (2 != items) {
1742 log_err("Usage: Collectd::plugin_register_data_set(type, dataset)");
1743 XSRETURN_EMPTY;
1744 }
1746 log_debug("Collectd::plugin_register_data_set: "
1747 "type = \"%s\", dataset = \"%s\"",
1748 SvPV_nolen(ST(0)), SvPV_nolen(ST(1)));
1750 data = ST(1);
1752 if (SvROK(data) && (SVt_PVAV == SvTYPE(SvRV(data)))) {
1753 ret = pplugin_register_data_set(aTHX_ SvPV_nolen(ST(0)), (AV *)SvRV(data));
1754 } else {
1755 log_err("Collectd::plugin_register_data_set: Invalid data.");
1756 XSRETURN_EMPTY;
1757 }
1759 if (0 == ret)
1760 XSRETURN_YES;
1761 else
1762 XSRETURN_EMPTY;
1763 } /* static XS (Collectd_plugin_register_ds) */
1765 /*
1766 * Collectd::plugin_unregister_data_set (type).
1767 *
1768 * type:
1769 * type of the dataset
1770 */
1771 static XS(Collectd_plugin_unregister_ds) {
1772 dXSARGS;
1774 if (1 != items) {
1775 log_err("Usage: Collectd::plugin_unregister_data_set(type)");
1776 XSRETURN_EMPTY;
1777 }
1779 log_debug("Collectd::plugin_unregister_data_set: type = \"%s\"",
1780 SvPV_nolen(ST(0)));
1782 if (0 == pplugin_unregister_data_set(SvPV_nolen(ST(0))))
1783 XSRETURN_YES;
1784 else
1785 XSRETURN_EMPTY;
1786 } /* static XS (Collectd_plugin_register_ds) */
1788 /*
1789 * Collectd::plugin_dispatch_values (name, values).
1790 *
1791 * name:
1792 * name of the plugin
1793 *
1794 * values:
1795 * value list to submit
1796 */
1797 static XS(Collectd_plugin_dispatch_values) {
1798 SV *values = NULL;
1800 int ret = 0;
1802 dXSARGS;
1804 if (1 != items) {
1805 log_err("Usage: Collectd::plugin_dispatch_values(values)");
1806 XSRETURN_EMPTY;
1807 }
1809 log_debug("Collectd::plugin_dispatch_values: values=\"%s\"",
1810 SvPV_nolen(ST(/* stack index = */ 0)));
1812 values = ST(/* stack index = */ 0);
1814 if (NULL == values)
1815 XSRETURN_EMPTY;
1817 /* Make sure the argument is a hash reference. */
1818 if (!(SvROK(values) && (SVt_PVHV == SvTYPE(SvRV(values))))) {
1819 log_err("Collectd::plugin_dispatch_values: Invalid values.");
1820 XSRETURN_EMPTY;
1821 }
1823 ret = pplugin_dispatch_values(aTHX_(HV *) SvRV(values));
1825 if (0 == ret)
1826 XSRETURN_YES;
1827 else
1828 XSRETURN_EMPTY;
1829 } /* static XS (Collectd_plugin_dispatch_values) */
1831 /*
1832 * Collectd::plugin_get_interval ().
1833 */
1834 static XS(Collectd_plugin_get_interval) {
1835 dXSARGS;
1837 /* make sure we don't get any unused variable warnings for 'items';
1838 * don't abort, though */
1839 if (items)
1840 log_err("Usage: Collectd::plugin_get_interval()");
1842 XSRETURN_NV((NV)CDTIME_T_TO_DOUBLE(plugin_get_interval()));
1843 } /* static XS (Collectd_plugin_get_interval) */
1845 /* Collectd::plugin_write (plugin, ds, vl).
1846 *
1847 * plugin:
1848 * name of the plugin to call, may be 'undef'
1849 *
1850 * ds:
1851 * data-set that describes the submitted values, may be 'undef'
1852 *
1853 * vl:
1854 * value-list to be written
1855 */
1856 static XS(Collectd__plugin_write) {
1857 char *plugin;
1858 SV *ds, *vl;
1859 AV *ds_array;
1861 int ret;
1863 dXSARGS;
1865 if (3 != items) {
1866 log_err("Usage: Collectd::plugin_write(plugin, ds, vl)");
1867 XSRETURN_EMPTY;
1868 }
1870 log_debug("Collectd::plugin_write: plugin=\"%s\", ds=\"%s\", vl=\"%s\"",
1871 SvPV_nolen(ST(0)), SvOK(ST(1)) ? SvPV_nolen(ST(1)) : "",
1872 SvPV_nolen(ST(2)));
1874 if (!SvOK(ST(0)))
1875 plugin = NULL;
1876 else
1877 plugin = SvPV_nolen(ST(0));
1879 ds = ST(1);
1880 if (SvROK(ds) && (SVt_PVAV == SvTYPE(SvRV(ds))))
1881 ds_array = (AV *)SvRV(ds);
1882 else if (!SvOK(ds))
1883 ds_array = NULL;
1884 else {
1885 log_err("Collectd::plugin_write: Invalid data-set.");
1886 XSRETURN_EMPTY;
1887 }
1889 vl = ST(2);
1890 if (!(SvROK(vl) && (SVt_PVHV == SvTYPE(SvRV(vl))))) {
1891 log_err("Collectd::plugin_write: Invalid value-list.");
1892 XSRETURN_EMPTY;
1893 }
1895 ret = pplugin_write(aTHX_ plugin, ds_array, (HV *)SvRV(vl));
1897 if (0 == ret)
1898 XSRETURN_YES;
1899 else
1900 XSRETURN_EMPTY;
1901 } /* static XS (Collectd__plugin_write) */
1903 /*
1904 * Collectd::_plugin_flush (plugin, timeout, identifier).
1905 *
1906 * plugin:
1907 * name of the plugin to flush
1908 *
1909 * timeout:
1910 * timeout to use when flushing the data
1911 *
1912 * identifier:
1913 * data-set identifier to flush
1914 */
1915 static XS(Collectd__plugin_flush) {
1916 char *plugin = NULL;
1917 int timeout = -1;
1918 char *id = NULL;
1920 dXSARGS;
1922 if (3 != items) {
1923 log_err("Usage: Collectd::_plugin_flush(plugin, timeout, id)");
1924 XSRETURN_EMPTY;
1925 }
1927 if (SvOK(ST(0)))
1928 plugin = SvPV_nolen(ST(0));
1930 if (SvOK(ST(1)))
1931 timeout = (int)SvIV(ST(1));
1933 if (SvOK(ST(2)))
1934 id = SvPV_nolen(ST(2));
1936 log_debug("Collectd::_plugin_flush: plugin = \"%s\", timeout = %i, "
1937 "id = \"%s\"",
1938 plugin, timeout, id);
1940 if (0 == plugin_flush(plugin, timeout, id))
1941 XSRETURN_YES;
1942 else
1943 XSRETURN_EMPTY;
1944 } /* static XS (Collectd__plugin_flush) */
1946 /*
1947 * Collectd::plugin_dispatch_notification (notif).
1948 *
1949 * notif:
1950 * notification to dispatch
1951 */
1952 static XS(Collectd_plugin_dispatch_notification) {
1953 SV *notif = NULL;
1955 int ret = 0;
1957 dXSARGS;
1959 if (1 != items) {
1960 log_err("Usage: Collectd::plugin_dispatch_notification(notif)");
1961 XSRETURN_EMPTY;
1962 }
1964 log_debug("Collectd::plugin_dispatch_notification: notif = \"%s\"",
1965 SvPV_nolen(ST(0)));
1967 notif = ST(0);
1969 if (!(SvROK(notif) && (SVt_PVHV == SvTYPE(SvRV(notif))))) {
1970 log_err("Collectd::plugin_dispatch_notification: Invalid notif.");
1971 XSRETURN_EMPTY;
1972 }
1974 ret = pplugin_dispatch_notification(aTHX_(HV *) SvRV(notif));
1976 if (0 == ret)
1977 XSRETURN_YES;
1978 else
1979 XSRETURN_EMPTY;
1980 } /* static XS (Collectd_plugin_dispatch_notification) */
1982 /*
1983 * Collectd::plugin_log (level, message).
1984 *
1985 * level:
1986 * log level (LOG_DEBUG, ... LOG_ERR)
1987 *
1988 * message:
1989 * log message
1990 */
1991 static XS(Collectd_plugin_log) {
1992 dXSARGS;
1994 if (2 != items) {
1995 log_err("Usage: Collectd::plugin_log(level, message)");
1996 XSRETURN_EMPTY;
1997 }
1999 plugin_log(SvIV(ST(0)), "%s", SvPV_nolen(ST(1)));
2000 XSRETURN_YES;
2001 } /* static XS (Collectd_plugin_log) */
2003 /*
2004 * Collectd::_fc_register (type, name)
2005 *
2006 * type:
2007 * match | target
2008 *
2009 * name:
2010 * name of the match
2011 */
2012 static XS(Collectd__fc_register) {
2013 int type;
2014 char *name;
2016 int ret = 0;
2018 dXSARGS;
2020 if (2 != items) {
2021 log_err("Usage: Collectd::_fc_register(type, name)");
2022 XSRETURN_EMPTY;
2023 }
2025 type = SvIV(ST(0));
2026 name = SvPV_nolen(ST(1));
2028 if (FC_MATCH == type)
2029 ret = fc_register_match(name, pmatch);
2030 else if (FC_TARGET == type)
2031 ret = fc_register_target(name, ptarget);
2033 if (0 == ret)
2034 XSRETURN_YES;
2035 else
2036 XSRETURN_EMPTY;
2037 } /* static XS (Collectd_fc_register) */
2039 /*
2040 * Collectd::call_by_name (...).
2041 *
2042 * Call a Perl sub identified by its name passed through $Collectd::cb_name.
2043 */
2044 static XS(Collectd_call_by_name) {
2045 SV *tmp = NULL;
2046 char *name = NULL;
2048 if (NULL == (tmp = get_sv("Collectd::cb_name", 0))) {
2049 sv_setpv(get_sv("@", 1), "cb_name has not been set");
2050 CLEAR_STACK_FRAME;
2051 return;
2052 }
2054 name = SvPV_nolen(tmp);
2056 if (NULL == get_cv(name, 0)) {
2057 sv_setpvf(get_sv("@", 1), "unknown callback \"%s\"", name);
2058 CLEAR_STACK_FRAME;
2059 return;
2060 }
2062 /* simply pass on the subroutine call without touching the stack,
2063 * thus leaving any arguments and return values in place */
2064 call_pv(name, 0);
2065 } /* static XS (Collectd_call_by_name) */
2067 /*
2068 * Interface to collectd.
2069 */
2071 static int perl_init(void) {
2072 int status;
2073 dTHX;
2075 if (NULL == perl_threads)
2076 return 0;
2078 if (NULL == aTHX) {
2079 c_ithread_t *t = NULL;
2081 pthread_mutex_lock(&perl_threads->mutex);
2082 t = c_ithread_create(perl_threads->head->interp);
2083 pthread_mutex_unlock(&perl_threads->mutex);
2085 aTHX = t->interp;
2086 }
2088 log_debug("perl_init: c_ithread: interp = %p (active threads: %i)", aTHX,
2089 perl_threads->number_of_threads);
2091 /* Lock the base thread to avoid race conditions with c_ithread_create().
2092 * See https://github.com/collectd/collectd/issues/9 and
2093 * https://github.com/collectd/collectd/issues/1706 for details.
2094 */
2095 assert(aTHX == perl_threads->head->interp);
2096 pthread_mutex_lock(&perl_threads->mutex);
2098 status = pplugin_call(aTHX_ PLUGIN_INIT);
2100 pthread_mutex_unlock(&perl_threads->mutex);
2102 return status;
2103 } /* static int perl_init (void) */
2105 static int perl_read(user_data_t *user_data) {
2106 dTHX;
2108 if (NULL == perl_threads)
2109 return 0;
2111 if (NULL == aTHX) {
2112 c_ithread_t *t = NULL;
2114 pthread_mutex_lock(&perl_threads->mutex);
2115 t = c_ithread_create(perl_threads->head->interp);
2116 pthread_mutex_unlock(&perl_threads->mutex);
2118 aTHX = t->interp;
2119 }
2121 /* Assert that we're not running as the base thread. Otherwise, we might
2122 * run into concurrency issues with c_ithread_create(). See
2123 * https://github.com/collectd/collectd/issues/9 for details. */
2124 assert(aTHX != perl_threads->head->interp);
2126 log_debug("perl_read: c_ithread: interp = %p (active threads: %i)", aTHX,
2127 perl_threads->number_of_threads);
2129 return pplugin_call(aTHX_ PLUGIN_READ, user_data->data);
2130 } /* static int perl_read (user_data_t *user_data) */
2132 static int perl_write(const data_set_t *ds, const value_list_t *vl,
2133 user_data_t *user_data) {
2134 int status;
2135 dTHX;
2137 if (NULL == perl_threads)
2138 return 0;
2140 if (NULL == aTHX) {
2141 c_ithread_t *t = NULL;
2143 pthread_mutex_lock(&perl_threads->mutex);
2144 t = c_ithread_create(perl_threads->head->interp);
2145 pthread_mutex_unlock(&perl_threads->mutex);
2147 aTHX = t->interp;
2148 }
2150 /* Lock the base thread if this is not called from one of the read threads
2151 * to avoid race conditions with c_ithread_create(). See
2152 * https://github.com/collectd/collectd/issues/9 for details. */
2153 if (aTHX == perl_threads->head->interp)
2154 pthread_mutex_lock(&perl_threads->mutex);
2156 log_debug("perl_write: c_ithread: interp = %p (active threads: %i)", aTHX,
2157 perl_threads->number_of_threads);
2158 status = pplugin_call(aTHX_ PLUGIN_WRITE, user_data->data, ds, vl);
2160 if (aTHX == perl_threads->head->interp)
2161 pthread_mutex_unlock(&perl_threads->mutex);
2163 return status;
2164 } /* static int perl_write (const data_set_t *, const value_list_t *) */
2166 static void perl_log(int level, const char *msg, user_data_t *user_data) {
2167 dTHX;
2169 if (NULL == perl_threads)
2170 return;
2172 if (NULL == aTHX) {
2173 c_ithread_t *t = NULL;
2175 pthread_mutex_lock(&perl_threads->mutex);
2176 t = c_ithread_create(perl_threads->head->interp);
2177 pthread_mutex_unlock(&perl_threads->mutex);
2179 aTHX = t->interp;
2180 }
2182 /* Lock the base thread if this is not called from one of the read threads
2183 * to avoid race conditions with c_ithread_create(). See
2184 * https://github.com/collectd/collectd/issues/9 for details.
2185 */
2187 if (aTHX == perl_threads->head->interp)
2188 pthread_mutex_lock(&perl_threads->mutex);
2190 pplugin_call(aTHX_ PLUGIN_LOG, user_data->data, level, msg);
2192 if (aTHX == perl_threads->head->interp)
2193 pthread_mutex_unlock(&perl_threads->mutex);
2195 return;
2196 } /* static void perl_log (int, const char *) */
2198 static int perl_notify(const notification_t *notif, user_data_t *user_data) {
2199 dTHX;
2201 if (NULL == perl_threads)
2202 return 0;
2204 if (NULL == aTHX) {
2205 c_ithread_t *t = NULL;
2207 pthread_mutex_lock(&perl_threads->mutex);
2208 t = c_ithread_create(perl_threads->head->interp);
2209 pthread_mutex_unlock(&perl_threads->mutex);
2211 aTHX = t->interp;
2212 }
2213 return pplugin_call(aTHX_ PLUGIN_NOTIF, user_data->data, notif);
2214 } /* static int perl_notify (const notification_t *) */
2216 static int perl_flush(cdtime_t timeout, const char *identifier,
2217 user_data_t *user_data) {
2218 dTHX;
2220 if (NULL == perl_threads)
2221 return 0;
2223 if (NULL == aTHX) {
2224 c_ithread_t *t = NULL;
2226 pthread_mutex_lock(&perl_threads->mutex);
2227 t = c_ithread_create(perl_threads->head->interp);
2228 pthread_mutex_unlock(&perl_threads->mutex);
2230 aTHX = t->interp;
2231 }
2233 /* For collectd-5.6 only, #1731 */
2234 if (user_data == NULL || user_data->data == NULL)
2235 return pplugin_call(aTHX_ PLUGIN_FLUSH_ALL, timeout, identifier);
2237 return pplugin_call(aTHX_ PLUGIN_FLUSH, user_data->data, timeout, identifier);
2238 } /* static int perl_flush (const int) */
2240 static int perl_shutdown(void) {
2241 c_ithread_t *t;
2242 int ret;
2244 dTHX;
2246 plugin_unregister_complex_config("perl");
2247 plugin_unregister_read_group("perl");
2249 if (NULL == perl_threads)
2250 return 0;
2252 if (NULL == aTHX) {
2253 pthread_mutex_lock(&perl_threads->mutex);
2254 t = c_ithread_create(perl_threads->head->interp);
2255 pthread_mutex_unlock(&perl_threads->mutex);
2257 aTHX = t->interp;
2258 }
2260 log_debug("perl_shutdown: c_ithread: interp = %p (active threads: %i)", aTHX,
2261 perl_threads->number_of_threads);
2263 plugin_unregister_init("perl");
2264 plugin_unregister_flush("perl"); /* For collectd-5.6 only, #1731 */
2266 ret = pplugin_call(aTHX_ PLUGIN_SHUTDOWN);
2268 pthread_mutex_lock(&perl_threads->mutex);
2269 t = perl_threads->tail;
2271 while (NULL != t) {
2272 struct timespec ts_wait;
2273 c_ithread_t *thr = t;
2275 /* the pointer has to be advanced before destroying
2276 * the thread as this will free the memory */
2277 t = t->prev;
2279 thr->shutdown = 1;
2280 if (thr->running) {
2281 /* Give some time to thread to exit from Perl interpreter */
2282 WARNING("perl shutdown: Thread is running inside Perl. Waiting.");
2283 ts_wait.tv_sec = 0;
2284 ts_wait.tv_nsec = 500000;
2285 nanosleep(&ts_wait, NULL);
2286 }
2287 if (thr->running) {
2288 pthread_kill(thr->pthread, SIGTERM);
2289 ERROR("perl shutdown: Thread hangs inside Perl. Thread killed.");
2290 }
2291 c_ithread_destroy(thr);
2292 }
2294 pthread_mutex_unlock(&perl_threads->mutex);
2295 pthread_mutex_destroy(&perl_threads->mutex);
2296 pthread_mutexattr_destroy(&perl_threads->mutexattr);
2298 sfree(perl_threads);
2300 pthread_key_delete(perl_thr_key);
2302 PERL_SYS_TERM();
2304 plugin_unregister_shutdown("perl");
2305 return ret;
2306 } /* static void perl_shutdown (void) */
2308 /*
2309 * Access functions for global variables.
2310 *
2311 * These functions implement the "magic" used to access
2312 * the global variables from Perl.
2313 */
2315 static int g_pv_get(pTHX_ SV *var, MAGIC *mg) {
2316 char *pv = mg->mg_ptr;
2317 sv_setpv(var, pv);
2318 return 0;
2319 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
2321 static int g_pv_set(pTHX_ SV *var, MAGIC *mg) {
2322 char *pv = mg->mg_ptr;
2323 sstrncpy(pv, SvPV_nolen(var), DATA_MAX_NAME_LEN);
2324 return 0;
2325 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
2327 static int g_interval_get(pTHX_ SV *var, MAGIC *mg) {
2328 log_warn("Accessing $interval_g is deprecated (and might not "
2329 "give the desired results) - plugin_get_interval() should "
2330 "be used instead.");
2331 sv_setnv(var, CDTIME_T_TO_DOUBLE(interval_g));
2332 return 0;
2333 } /* static int g_interval_get (pTHX_ SV *, MAGIC *) */
2335 static int g_interval_set(pTHX_ SV *var, MAGIC *mg) {
2336 double nv = (double)SvNV(var);
2337 log_warn("Accessing $interval_g is deprecated (and might not "
2338 "give the desired results) - plugin_get_interval() should "
2339 "be used instead.");
2340 interval_g = DOUBLE_TO_CDTIME_T(nv);
2341 return 0;
2342 } /* static int g_interval_set (pTHX_ SV *, MAGIC *) */
2344 static MGVTBL g_pv_vtbl = {g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL
2345 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2346 ,
2347 NULL
2348 #endif
2349 };
2350 static MGVTBL g_interval_vtbl = {g_interval_get, g_interval_set, NULL, NULL,
2351 NULL, NULL, NULL
2352 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2353 ,
2354 NULL
2355 #endif
2356 };
2358 /* bootstrap the Collectd module */
2359 static void xs_init(pTHX) {
2360 HV *stash = NULL;
2361 SV *tmp = NULL;
2362 char *file = __FILE__;
2364 dXSUB_SYS;
2366 /* enable usage of Perl modules using shared libraries */
2367 newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2369 /* register API */
2370 for (int i = 0; NULL != api[i].f; ++i)
2371 newXS(api[i].name, api[i].f, file);
2373 stash = gv_stashpv("Collectd", 1);
2375 /* export "constants" */
2376 for (int i = 0; '\0' != constants[i].name[0]; ++i)
2377 newCONSTSUB(stash, constants[i].name, newSViv(constants[i].value));
2379 /* export global variables
2380 * by adding "magic" to the SV's representing the globale variables
2381 * perl is able to automagically call the get/set function when
2382 * accessing any such variable (this is basically the same as using
2383 * tie() in Perl) */
2384 /* global strings */
2385 for (int i = 0; '\0' != g_strings[i].name[0]; ++i) {
2386 tmp = get_sv(g_strings[i].name, 1);
2387 sv_magicext(tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl, g_strings[i].var, 0);
2388 }
2390 tmp = get_sv("Collectd::interval_g", /* create = */ 1);
2391 sv_magicext(tmp, NULL, /* how = */ PERL_MAGIC_ext,
2392 /* vtbl = */ &g_interval_vtbl,
2393 /* name = */ NULL, /* namelen = */ 0);
2395 return;
2396 } /* static void xs_init (pTHX) */
2398 /* Initialize the global Perl interpreter. */
2399 static int init_pi(int argc, char **argv) {
2400 dTHXa(NULL);
2402 if (NULL != perl_threads)
2403 return 0;
2405 log_info("Initializing Perl interpreter...");
2406 #if COLLECT_DEBUG
2407 {
2408 for (int i = 0; i < argc; ++i)
2409 log_debug("argv[%i] = \"%s\"", i, argv[i]);
2410 }
2411 #endif /* COLLECT_DEBUG */
2413 if (0 != pthread_key_create(&perl_thr_key, c_ithread_destructor)) {
2414 log_err("init_pi: pthread_key_create failed");
2416 /* this must not happen - cowardly giving up if it does */
2417 return -1;
2418 }
2420 #ifdef __FreeBSD__
2421 /* On FreeBSD, PERL_SYS_INIT3 expands to some expression which
2422 * triggers a "value computed is not used" warning by gcc. */
2423 (void)
2424 #endif
2425 PERL_SYS_INIT3(&argc, &argv, &environ);
2427 perl_threads = smalloc(sizeof(*perl_threads));
2428 memset(perl_threads, 0, sizeof(c_ithread_list_t));
2430 pthread_mutexattr_init(&perl_threads->mutexattr);
2431 pthread_mutexattr_settype(&perl_threads->mutexattr, PTHREAD_MUTEX_RECURSIVE);
2432 pthread_mutex_init(&perl_threads->mutex, &perl_threads->mutexattr);
2433 /* locking the mutex should not be necessary at this point
2434 * but let's just do it for the sake of completeness */
2435 pthread_mutex_lock(&perl_threads->mutex);
2437 perl_threads->head = c_ithread_create(NULL);
2438 perl_threads->tail = perl_threads->head;
2440 if (NULL == (perl_threads->head->interp = perl_alloc())) {
2441 log_err("init_pi: Not enough memory.");
2442 exit(3);
2443 }
2445 aTHX = perl_threads->head->interp;
2446 pthread_mutex_unlock(&perl_threads->mutex);
2448 perl_construct(aTHX);
2450 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
2452 if (0 != perl_parse(aTHX_ xs_init, argc, argv, NULL)) {
2453 SV *err = get_sv("@", 1);
2454 log_err("init_pi: Unable to bootstrap Collectd: %s", SvPV_nolen(err));
2456 perl_destruct(perl_threads->head->interp);
2457 perl_free(perl_threads->head->interp);
2458 sfree(perl_threads);
2460 pthread_key_delete(perl_thr_key);
2461 return -1;
2462 }
2464 /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
2465 sv_setpv(get_sv("0", 0), "collectd");
2467 perl_run(aTHX);
2469 plugin_register_init("perl", perl_init);
2470 plugin_register_shutdown("perl", perl_shutdown);
2471 return 0;
2472 } /* static int init_pi (const char **, const int) */
2474 /*
2475 * LoadPlugin "<Plugin>"
2476 */
2477 static int perl_config_loadplugin(pTHX_ oconfig_item_t *ci) {
2478 char module_name[DATA_MAX_NAME_LEN];
2480 char *value = NULL;
2482 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2483 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2484 log_err("LoadPlugin expects a single string argument.");
2485 return 1;
2486 }
2488 value = ci->values[0].value.string;
2490 if (NULL == get_module_name(module_name, sizeof(module_name), value)) {
2491 log_err("Invalid module name %s", value);
2492 return (1);
2493 }
2495 if (0 != init_pi(perl_argc, perl_argv))
2496 return -1;
2498 assert(NULL != perl_threads);
2499 assert(NULL != perl_threads->head);
2501 aTHX = perl_threads->head->interp;
2503 log_debug("perl_config: Loading Perl plugin \"%s\"", value);
2504 load_module(PERL_LOADMOD_NOIMPORT, newSVpv(module_name, strlen(module_name)),
2505 Nullsv);
2506 return 0;
2507 } /* static int perl_config_loadplugin (oconfig_item_it *) */
2509 /*
2510 * BaseName "<Name>"
2511 */
2512 static int perl_config_basename(pTHX_ oconfig_item_t *ci) {
2513 char *value = NULL;
2515 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2516 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2517 log_err("BaseName expects a single string argument.");
2518 return 1;
2519 }
2521 value = ci->values[0].value.string;
2523 log_debug("perl_config: Setting plugin basename to \"%s\"", value);
2524 sstrncpy(base_name, value, sizeof(base_name));
2525 return 0;
2526 } /* static int perl_config_basename (oconfig_item_it *) */
2528 /*
2529 * EnableDebugger "<Package>"|""
2530 */
2531 static int perl_config_enabledebugger(pTHX_ oconfig_item_t *ci) {
2532 char *value = NULL;
2534 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2535 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2536 log_err("EnableDebugger expects a single string argument.");
2537 return 1;
2538 }
2540 if (NULL != perl_threads) {
2541 log_warn("EnableDebugger has no effects if used after LoadPlugin.");
2542 return 1;
2543 }
2545 value = ci->values[0].value.string;
2547 perl_argv = realloc(perl_argv, (++perl_argc + 1) * sizeof(char *));
2549 if (NULL == perl_argv) {
2550 log_err("perl_config: Not enough memory.");
2551 exit(3);
2552 }
2554 if ('\0' == value[0]) {
2555 perl_argv[perl_argc - 1] = "-d";
2556 } else {
2557 perl_argv[perl_argc - 1] = smalloc(strlen(value) + 4);
2558 sstrncpy(perl_argv[perl_argc - 1], "-d:", 4);
2559 sstrncpy(perl_argv[perl_argc - 1] + 3, value, strlen(value) + 1);
2560 }
2562 perl_argv[perl_argc] = NULL;
2563 return 0;
2564 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
2566 /*
2567 * IncludeDir "<Dir>"
2568 */
2569 static int perl_config_includedir(pTHX_ oconfig_item_t *ci) {
2570 char *value = NULL;
2572 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2573 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2574 log_err("IncludeDir expects a single string argument.");
2575 return 1;
2576 }
2578 value = ci->values[0].value.string;
2580 if (NULL == aTHX) {
2581 perl_argv = realloc(perl_argv, (++perl_argc + 1) * sizeof(char *));
2583 if (NULL == perl_argv) {
2584 log_err("perl_config: Not enough memory.");
2585 exit(3);
2586 }
2588 perl_argv[perl_argc - 1] = smalloc(strlen(value) + 3);
2589 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
2590 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen(value) + 1);
2592 perl_argv[perl_argc] = NULL;
2593 } else {
2594 /* prepend the directory to @INC */
2595 av_unshift(GvAVn(PL_incgv), 1);
2596 av_store(GvAVn(PL_incgv), 0, newSVpv(value, strlen(value)));
2597 }
2598 return 0;
2599 } /* static int perl_config_includedir (oconfig_item_it *) */
2601 /*
2602 * <Plugin> block
2603 */
2604 static int perl_config_plugin(pTHX_ oconfig_item_t *ci) {
2605 int retvals = 0;
2606 int ret = 0;
2608 char *plugin;
2609 HV *config;
2611 dSP;
2613 if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2614 log_err("LoadPlugin expects a single string argument.");
2615 return 1;
2616 }
2618 plugin = ci->values[0].value.string;
2619 config = newHV();
2621 if (0 != oconfig_item2hv(aTHX_ ci, config)) {
2622 hv_clear(config);
2623 hv_undef(config);
2625 log_err("Unable to convert configuration to a Perl hash value.");
2626 config = (HV *)&PL_sv_undef;
2627 }
2629 ENTER;
2630 SAVETMPS;
2632 PUSHMARK(SP);
2634 XPUSHs(sv_2mortal(newSVpv(plugin, 0)));
2635 XPUSHs(sv_2mortal(newRV_noinc((SV *)config)));
2637 PUTBACK;
2639 retvals = call_pv("Collectd::_plugin_dispatch_config", G_SCALAR);
2641 SPAGAIN;
2642 if (0 < retvals) {
2643 SV *tmp = POPs;
2644 if (!SvTRUE(tmp))
2645 ret = 1;
2646 } else
2647 ret = 1;
2649 PUTBACK;
2650 FREETMPS;
2651 LEAVE;
2652 return ret;
2653 } /* static int perl_config_plugin (oconfig_item_it *) */
2655 static int perl_config(oconfig_item_t *ci) {
2656 int status = 0;
2658 dTHXa(NULL);
2660 for (int i = 0; i < ci->children_num; ++i) {
2661 oconfig_item_t *c = ci->children + i;
2662 int current_status = 0;
2664 if (NULL != perl_threads) {
2665 if ((aTHX = PERL_GET_CONTEXT) == NULL)
2666 return -1;
2667 }
2669 if (0 == strcasecmp(c->key, "LoadPlugin"))
2670 current_status = perl_config_loadplugin(aTHX_ c);
2671 else if (0 == strcasecmp(c->key, "BaseName"))
2672 current_status = perl_config_basename(aTHX_ c);
2673 else if (0 == strcasecmp(c->key, "EnableDebugger"))
2674 current_status = perl_config_enabledebugger(aTHX_ c);
2675 else if (0 == strcasecmp(c->key, "IncludeDir"))
2676 current_status = perl_config_includedir(aTHX_ c);
2677 else if (0 == strcasecmp(c->key, "Plugin"))
2678 current_status = perl_config_plugin(aTHX_ c);
2679 else if (0 == strcasecmp(c->key, "RegisterLegacyFlush"))
2680 cf_util_get_boolean(c, ®ister_legacy_flush);
2681 else {
2682 log_warn("Ignoring unknown config key \"%s\".", c->key);
2683 current_status = 0;
2684 }
2686 /* fatal error - it's up to perl_config_* to clean up */
2687 if (0 > current_status) {
2688 log_err("Configuration failed with a fatal error - "
2689 "plugin disabled!");
2690 return current_status;
2691 }
2693 status += current_status;
2694 }
2695 return status;
2696 } /* static int perl_config (oconfig_item_t *) */
2698 void module_register(void) {
2699 perl_argc = 4;
2700 perl_argv = smalloc((perl_argc + 1) * sizeof(*perl_argv));
2702 /* default options for the Perl interpreter */
2703 perl_argv[0] = "";
2704 perl_argv[1] = "-MCollectd";
2705 perl_argv[2] = "-e";
2706 perl_argv[3] = "1";
2707 perl_argv[4] = NULL;
2709 plugin_register_complex_config("perl", perl_config);
2710 return;
2711 } /* void module_register (void) */