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 **ret_meta) {
498 notification_meta_t *tail = NULL;
500 int len = av_len(array);
502 for (int i = 0; i <= len; ++i) {
503 SV **tmp = av_fetch(array, i, 0);
505 if (tmp == NULL)
506 return -1;
508 if (!(SvROK(*tmp) && (SVt_PVHV == SvTYPE(SvRV(*tmp))))) {
509 log_warn("av2notification_meta: Skipping invalid "
510 "meta information.");
511 continue;
512 }
514 HV *hash = (HV *)SvRV(*tmp);
516 notification_meta_t *m = calloc(1, sizeof(*m));
517 if (m == NULL)
518 return ENOMEM;
520 SV **name = hv_fetch(hash, "name", strlen("name"), 0);
521 if (name == NULL) {
522 log_warn("av2notification_meta: Skipping invalid "
523 "meta information.");
524 sfree(m);
525 continue;
526 }
527 sstrncpy(m->name, SvPV_nolen(*name), sizeof(m->name));
529 SV **value = hv_fetch(hash, "value", strlen("value"), 0);
530 if (value == NULL) {
531 log_warn("av2notification_meta: Skipping invalid "
532 "meta information.");
533 sfree(m);
534 continue;
535 }
537 if (SvNOK(*value)) {
538 m->nm_value.nm_double = SvNVX(*value);
539 m->type = NM_TYPE_DOUBLE;
540 } else if (SvUOK(*value)) {
541 m->nm_value.nm_unsigned_int = SvUVX(*value);
542 m->type = NM_TYPE_UNSIGNED_INT;
543 } else if (SvIOK(*value)) {
544 m->nm_value.nm_signed_int = SvIVX(*value);
545 m->type = NM_TYPE_SIGNED_INT;
546 } else {
547 m->nm_value.nm_string = sstrdup(SvPV_nolen(*value));
548 m->type = NM_TYPE_STRING;
549 }
551 m->next = NULL;
552 if (tail == NULL)
553 *ret_meta = m;
554 else
555 tail->next = m;
556 tail = m;
557 }
559 return 0;
560 } /* static int av2notification_meta (AV *, notification_meta_t *) */
562 static int hv2notification(pTHX_ HV *hash, notification_t *n) {
563 SV **tmp = NULL;
565 if ((NULL == hash) || (NULL == n))
566 return -1;
568 if (NULL != (tmp = hv_fetch(hash, "severity", 8, 0)))
569 n->severity = SvIV(*tmp);
570 else
571 n->severity = NOTIF_FAILURE;
573 if (NULL != (tmp = hv_fetch(hash, "time", 4, 0))) {
574 double t = SvNV(*tmp);
575 n->time = DOUBLE_TO_CDTIME_T(t);
576 } else
577 n->time = cdtime();
579 if (NULL != (tmp = hv_fetch(hash, "message", 7, 0)))
580 sstrncpy(n->message, SvPV_nolen(*tmp), sizeof(n->message));
582 if (NULL != (tmp = hv_fetch(hash, "host", 4, 0)))
583 sstrncpy(n->host, SvPV_nolen(*tmp), sizeof(n->host));
584 else
585 sstrncpy(n->host, hostname_g, sizeof(n->host));
587 if (NULL != (tmp = hv_fetch(hash, "plugin", 6, 0)))
588 sstrncpy(n->plugin, SvPV_nolen(*tmp), sizeof(n->plugin));
590 if (NULL != (tmp = hv_fetch(hash, "plugin_instance", 15, 0)))
591 sstrncpy(n->plugin_instance, SvPV_nolen(*tmp), sizeof(n->plugin_instance));
593 if (NULL != (tmp = hv_fetch(hash, "type", 4, 0)))
594 sstrncpy(n->type, SvPV_nolen(*tmp), sizeof(n->type));
596 if (NULL != (tmp = hv_fetch(hash, "type_instance", 13, 0)))
597 sstrncpy(n->type_instance, SvPV_nolen(*tmp), sizeof(n->type_instance));
599 n->meta = NULL;
600 while (NULL != (tmp = hv_fetch(hash, "meta", 4, 0))) {
601 if (!(SvROK(*tmp) && (SVt_PVAV == SvTYPE(SvRV(*tmp))))) {
602 log_warn("hv2notification: Ignoring invalid meta information.");
603 break;
604 }
606 if (0 != av2notification_meta(aTHX_(AV *) SvRV(*tmp), &n->meta)) {
607 plugin_notification_meta_free(n->meta);
608 n->meta = NULL;
609 return -1;
610 }
611 break;
612 }
613 return 0;
614 } /* static int hv2notification (pTHX_ HV *, notification_t *) */
616 static int data_set2av(pTHX_ data_set_t *ds, AV *array) {
617 if ((NULL == ds) || (NULL == array))
618 return -1;
620 av_extend(array, ds->ds_num);
622 for (size_t i = 0; i < ds->ds_num; ++i) {
623 HV *source = newHV();
625 if (NULL == hv_store(source, "name", 4, newSVpv(ds->ds[i].name, 0), 0))
626 return -1;
628 if (NULL == hv_store(source, "type", 4, newSViv(ds->ds[i].type), 0))
629 return -1;
631 if (!isnan(ds->ds[i].min))
632 if (NULL == hv_store(source, "min", 3, newSVnv(ds->ds[i].min), 0))
633 return -1;
635 if (!isnan(ds->ds[i].max))
636 if (NULL == hv_store(source, "max", 3, newSVnv(ds->ds[i].max), 0))
637 return -1;
639 if (NULL == av_store(array, i, newRV_noinc((SV *)source)))
640 return -1;
641 }
642 return 0;
643 } /* static int data_set2av (data_set_t *, AV *) */
645 static int value_list2hv(pTHX_ value_list_t *vl, data_set_t *ds, HV *hash) {
646 AV *values = NULL;
647 size_t i;
649 if ((NULL == vl) || (NULL == ds) || (NULL == hash))
650 return -1;
652 values = newAV();
653 /* av_extend takes the last *index* to which the array should be extended. */
654 av_extend(values, vl->values_len - 1);
656 assert(ds->ds_num == vl->values_len);
657 for (i = 0; i < vl->values_len; ++i) {
658 SV *val = NULL;
660 if (DS_TYPE_COUNTER == ds->ds[i].type)
661 val = newSViv(vl->values[i].counter);
662 else if (DS_TYPE_GAUGE == ds->ds[i].type)
663 val = newSVnv(vl->values[i].gauge);
664 else if (DS_TYPE_DERIVE == ds->ds[i].type)
665 val = newSViv(vl->values[i].derive);
666 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
667 val = newSViv(vl->values[i].absolute);
669 if (NULL == av_store(values, i, val)) {
670 av_undef(values);
671 return -1;
672 }
673 }
675 if (NULL == hv_store(hash, "values", 6, newRV_noinc((SV *)values), 0))
676 return -1;
678 if (0 != vl->time) {
679 double t = CDTIME_T_TO_DOUBLE(vl->time);
680 if (NULL == hv_store(hash, "time", 4, newSVnv(t), 0))
681 return -1;
682 }
684 {
685 double t = CDTIME_T_TO_DOUBLE(vl->interval);
686 if (NULL == hv_store(hash, "interval", 8, newSVnv(t), 0))
687 return -1;
688 }
690 if ('\0' != vl->host[0])
691 if (NULL == hv_store(hash, "host", 4, newSVpv(vl->host, 0), 0))
692 return -1;
694 if ('\0' != vl->plugin[0])
695 if (NULL == hv_store(hash, "plugin", 6, newSVpv(vl->plugin, 0), 0))
696 return -1;
698 if ('\0' != vl->plugin_instance[0])
699 if (NULL == hv_store(hash, "plugin_instance", 15,
700 newSVpv(vl->plugin_instance, 0), 0))
701 return -1;
703 if ('\0' != vl->type[0])
704 if (NULL == hv_store(hash, "type", 4, newSVpv(vl->type, 0), 0))
705 return -1;
707 if ('\0' != vl->type_instance[0])
708 if (NULL ==
709 hv_store(hash, "type_instance", 13, newSVpv(vl->type_instance, 0), 0))
710 return -1;
711 return 0;
712 } /* static int value2av (value_list_t *, data_set_t *, HV *) */
714 static int notification_meta2av(pTHX_ notification_meta_t *meta, AV *array) {
715 int meta_num = 0;
717 while (meta) {
718 ++meta_num;
719 meta = meta->next;
720 }
722 av_extend(array, meta_num);
724 for (int i = 0; NULL != meta; meta = meta->next, ++i) {
725 HV *m = newHV();
726 SV *value;
728 if (NULL == hv_store(m, "name", 4, newSVpv(meta->name, 0), 0))
729 return -1;
731 if (NM_TYPE_STRING == meta->type)
732 value = newSVpv(meta->nm_value.nm_string, 0);
733 else if (NM_TYPE_SIGNED_INT == meta->type)
734 value = newSViv(meta->nm_value.nm_signed_int);
735 else if (NM_TYPE_UNSIGNED_INT == meta->type)
736 value = newSVuv(meta->nm_value.nm_unsigned_int);
737 else if (NM_TYPE_DOUBLE == meta->type)
738 value = newSVnv(meta->nm_value.nm_double);
739 else if (NM_TYPE_BOOLEAN == meta->type)
740 value = meta->nm_value.nm_boolean ? &PL_sv_yes : &PL_sv_no;
741 else
742 return -1;
744 if (NULL == hv_store(m, "value", 5, value, 0)) {
745 sv_free(value);
746 return -1;
747 }
749 if (NULL == av_store(array, i, newRV_noinc((SV *)m))) {
750 hv_clear(m);
751 hv_undef(m);
752 return -1;
753 }
754 }
755 return 0;
756 } /* static int notification_meta2av (notification_meta_t *, AV *) */
758 static int notification2hv(pTHX_ notification_t *n, HV *hash) {
759 if (NULL == hv_store(hash, "severity", 8, newSViv(n->severity), 0))
760 return -1;
762 if (0 != n->time) {
763 double t = CDTIME_T_TO_DOUBLE(n->time);
764 if (NULL == hv_store(hash, "time", 4, newSVnv(t), 0))
765 return -1;
766 }
768 if ('\0' != *n->message)
769 if (NULL == hv_store(hash, "message", 7, newSVpv(n->message, 0), 0))
770 return -1;
772 if ('\0' != *n->host)
773 if (NULL == hv_store(hash, "host", 4, newSVpv(n->host, 0), 0))
774 return -1;
776 if ('\0' != *n->plugin)
777 if (NULL == hv_store(hash, "plugin", 6, newSVpv(n->plugin, 0), 0))
778 return -1;
780 if ('\0' != *n->plugin_instance)
781 if (NULL == hv_store(hash, "plugin_instance", 15,
782 newSVpv(n->plugin_instance, 0), 0))
783 return -1;
785 if ('\0' != *n->type)
786 if (NULL == hv_store(hash, "type", 4, newSVpv(n->type, 0), 0))
787 return -1;
789 if ('\0' != *n->type_instance)
790 if (NULL ==
791 hv_store(hash, "type_instance", 13, newSVpv(n->type_instance, 0), 0))
792 return -1;
794 if (NULL != n->meta) {
795 AV *meta = newAV();
796 if ((0 != notification_meta2av(aTHX_ n->meta, meta)) ||
797 (NULL == hv_store(hash, "meta", 4, newRV_noinc((SV *)meta), 0))) {
798 av_clear(meta);
799 av_undef(meta);
800 return -1;
801 }
802 }
803 return 0;
804 } /* static int notification2hv (notification_t *, HV *) */
806 static int oconfig_item2hv(pTHX_ oconfig_item_t *ci, HV *hash) {
807 AV *values;
808 AV *children;
810 if (NULL == hv_store(hash, "key", 3, newSVpv(ci->key, 0), 0))
811 return -1;
813 values = newAV();
814 if (0 < ci->values_num)
815 av_extend(values, ci->values_num);
817 if (NULL == hv_store(hash, "values", 6, newRV_noinc((SV *)values), 0)) {
818 av_clear(values);
819 av_undef(values);
820 return -1;
821 }
823 for (int i = 0; i < ci->values_num; ++i) {
824 SV *value;
826 switch (ci->values[i].type) {
827 case OCONFIG_TYPE_STRING:
828 value = newSVpv(ci->values[i].value.string, 0);
829 break;
830 case OCONFIG_TYPE_NUMBER:
831 value = newSVnv((NV)ci->values[i].value.number);
832 break;
833 case OCONFIG_TYPE_BOOLEAN:
834 value = ci->values[i].value.boolean ? &PL_sv_yes : &PL_sv_no;
835 break;
836 default:
837 log_err("oconfig_item2hv: Invalid value type %i.", ci->values[i].type);
838 value = &PL_sv_undef;
839 }
841 if (NULL == av_store(values, i, value)) {
842 sv_free(value);
843 return -1;
844 }
845 }
847 /* ignoring 'parent' member which is uninteresting in this case */
849 children = newAV();
850 if (0 < ci->children_num)
851 av_extend(children, ci->children_num);
853 if (NULL == hv_store(hash, "children", 8, newRV_noinc((SV *)children), 0)) {
854 av_clear(children);
855 av_undef(children);
856 return -1;
857 }
859 for (int i = 0; i < ci->children_num; ++i) {
860 HV *child = newHV();
862 if (0 != oconfig_item2hv(aTHX_ ci->children + i, child)) {
863 hv_clear(child);
864 hv_undef(child);
865 return -1;
866 }
868 if (NULL == av_store(children, i, newRV_noinc((SV *)child))) {
869 hv_clear(child);
870 hv_undef(child);
871 return -1;
872 }
873 }
874 return 0;
875 } /* static int oconfig_item2hv (pTHX_ oconfig_item_t *, HV *) */
877 /*
878 * Internal functions.
879 */
881 static char *get_module_name(char *buf, size_t buf_len, const char *module) {
882 int status = 0;
883 if (base_name[0] == '\0')
884 status = ssnprintf(buf, buf_len, "%s", module);
885 else
886 status = ssnprintf(buf, buf_len, "%s::%s", base_name, module);
887 if ((status < 0) || ((unsigned int)status >= buf_len))
888 return NULL;
889 return buf;
890 } /* char *get_module_name */
892 /*
893 * Add a plugin's data set definition.
894 */
895 static int pplugin_register_data_set(pTHX_ char *name, AV *dataset) {
896 int ret = 0;
898 data_set_t ds;
900 if ((NULL == name) || (NULL == dataset))
901 return -1;
903 if (0 != av2data_set(aTHX_ dataset, name, &ds))
904 return -1;
906 ret = plugin_register_data_set(&ds);
908 free(ds.ds);
909 return ret;
910 } /* static int pplugin_register_data_set (char *, SV *) */
912 /*
913 * Remove a plugin's data set definition.
914 */
915 static int pplugin_unregister_data_set(char *name) {
916 if (NULL == name)
917 return 0;
918 return plugin_unregister_data_set(name);
919 } /* static int pplugin_unregister_data_set (char *) */
921 /*
922 * Submit the values to the write functions.
923 */
924 static int pplugin_dispatch_values(pTHX_ HV *values) {
925 value_list_t vl = VALUE_LIST_INIT;
927 int ret = 0;
929 if (NULL == values)
930 return -1;
932 if (0 != hv2value_list(aTHX_ values, &vl))
933 return -1;
935 ret = plugin_dispatch_values(&vl);
937 sfree(vl.values);
938 return ret;
939 } /* static int pplugin_dispatch_values (char *, HV *) */
941 /*
942 * Submit the values to a single write function.
943 */
944 static int pplugin_write(pTHX_ const char *plugin, AV *data_set, HV *values) {
945 data_set_t ds;
946 value_list_t vl = VALUE_LIST_INIT;
948 int ret;
950 if (NULL == values)
951 return -1;
953 if (0 != hv2value_list(aTHX_ values, &vl))
954 return -1;
956 if ((NULL != data_set) && (0 != av2data_set(aTHX_ data_set, vl.type, &ds)))
957 return -1;
959 ret = plugin_write(plugin, NULL == data_set ? NULL : &ds, &vl);
960 if (0 != ret)
961 log_warn("Dispatching value to plugin \"%s\" failed with status %i.",
962 NULL == plugin ? "<any>" : plugin, ret);
964 if (NULL != data_set)
965 sfree(ds.ds);
966 sfree(vl.values);
967 return ret;
968 } /* static int pplugin_write (const char *plugin, HV *, HV *) */
970 /*
971 * Dispatch a notification.
972 */
973 static int pplugin_dispatch_notification(pTHX_ HV *notif) {
974 notification_t n = {0};
976 int ret;
978 if (NULL == notif)
979 return -1;
981 if (0 != hv2notification(aTHX_ notif, &n))
982 return -1;
984 ret = plugin_dispatch_notification(&n);
985 plugin_notification_meta_free(n.meta);
986 return ret;
987 } /* static int pplugin_dispatch_notification (HV *) */
989 /*
990 * Call perl sub with thread locking flags handled.
991 */
992 static int call_pv_locked(pTHX_ const char *sub_name) {
993 _Bool old_running;
994 int ret;
996 c_ithread_t *t = (c_ithread_t *)pthread_getspecific(perl_thr_key);
997 if (t == NULL) /* thread destroyed */
998 return 0;
1000 old_running = t->running;
1001 t->running = 1;
1003 if (t->shutdown) {
1004 t->running = old_running;
1005 return 0;
1006 }
1008 ret = call_pv(sub_name, G_SCALAR | G_EVAL);
1010 t->running = old_running;
1011 return ret;
1012 } /* static int call_pv_locked (pTHX, *sub_name) */
1014 /*
1015 * Call all working functions of the given type.
1016 */
1017 static int pplugin_call(pTHX_ int type, ...) {
1018 int retvals = 0;
1020 va_list ap;
1021 int ret = 0;
1022 char *subname;
1024 dSP;
1026 if ((type < 0) || (type >= PLUGIN_TYPES))
1027 return -1;
1029 va_start(ap, type);
1031 ENTER;
1032 SAVETMPS;
1034 PUSHMARK(SP);
1036 if (PLUGIN_READ == type) {
1037 subname = va_arg(ap, char *);
1038 } else if (PLUGIN_WRITE == type) {
1039 data_set_t *ds;
1040 value_list_t *vl;
1042 AV *pds = newAV();
1043 HV *pvl = newHV();
1045 subname = va_arg(ap, char *);
1046 /*
1047 * $_[0] = $plugin_type;
1048 *
1049 * $_[1] =
1050 * [
1051 * {
1052 * name => $ds_name,
1053 * type => $ds_type,
1054 * min => $ds_min,
1055 * max => $ds_max
1056 * },
1057 * ...
1058 * ];
1059 *
1060 * $_[2] =
1061 * {
1062 * values => [ $v1, ... ],
1063 * time => $time,
1064 * host => $hostname,
1065 * plugin => $plugin,
1066 * type => $type,
1067 * plugin_instance => $instance,
1068 * type_instance => $type_instance
1069 * };
1070 */
1071 ds = va_arg(ap, data_set_t *);
1072 vl = va_arg(ap, value_list_t *);
1074 if (-1 == data_set2av(aTHX_ ds, pds)) {
1075 av_clear(pds);
1076 av_undef(pds);
1077 pds = (AV *)&PL_sv_undef;
1078 ret = -1;
1079 }
1081 if (-1 == value_list2hv(aTHX_ vl, ds, pvl)) {
1082 hv_clear(pvl);
1083 hv_undef(pvl);
1084 pvl = (HV *)&PL_sv_undef;
1085 ret = -1;
1086 }
1088 XPUSHs(sv_2mortal(newSVpv(ds->type, 0)));
1089 XPUSHs(sv_2mortal(newRV_noinc((SV *)pds)));
1090 XPUSHs(sv_2mortal(newRV_noinc((SV *)pvl)));
1091 } else if (PLUGIN_LOG == type) {
1092 subname = va_arg(ap, char *);
1093 /*
1094 * $_[0] = $level;
1095 *
1096 * $_[1] = $message;
1097 */
1098 XPUSHs(sv_2mortal(newSViv(va_arg(ap, int))));
1099 XPUSHs(sv_2mortal(newSVpv(va_arg(ap, char *), 0)));
1100 } else if (PLUGIN_NOTIF == type) {
1101 notification_t *n;
1102 HV *notif = newHV();
1104 subname = va_arg(ap, char *);
1105 /*
1106 * $_[0] =
1107 * {
1108 * severity => $severity,
1109 * time => $time,
1110 * message => $msg,
1111 * host => $host,
1112 * plugin => $plugin,
1113 * type => $type,
1114 * plugin_instance => $instance,
1115 * type_instance => $type_instance
1116 * };
1117 */
1118 n = va_arg(ap, notification_t *);
1120 if (-1 == notification2hv(aTHX_ n, notif)) {
1121 hv_clear(notif);
1122 hv_undef(notif);
1123 notif = (HV *)&PL_sv_undef;
1124 ret = -1;
1125 }
1127 XPUSHs(sv_2mortal(newRV_noinc((SV *)notif)));
1128 } else if (PLUGIN_FLUSH == type) {
1129 cdtime_t timeout;
1130 subname = va_arg(ap, char *);
1131 /*
1132 * $_[0] = $timeout;
1133 * $_[1] = $identifier;
1134 */
1135 timeout = va_arg(ap, cdtime_t);
1137 XPUSHs(sv_2mortal(newSVnv(CDTIME_T_TO_DOUBLE(timeout))));
1138 XPUSHs(sv_2mortal(newSVpv(va_arg(ap, char *), 0)));
1139 } else if (PLUGIN_FLUSH_ALL == type) {
1140 cdtime_t timeout;
1141 subname = "Collectd::plugin_call_all";
1142 /*
1143 * $_[0] = $timeout;
1144 * $_[1] = $identifier;
1145 */
1146 timeout = va_arg(ap, cdtime_t);
1148 XPUSHs(sv_2mortal(newSViv((IV)PLUGIN_FLUSH)));
1149 XPUSHs(sv_2mortal(newSVnv(CDTIME_T_TO_DOUBLE(timeout))));
1150 XPUSHs(sv_2mortal(newSVpv(va_arg(ap, char *), 0)));
1151 } else if (PLUGIN_INIT == type) {
1152 subname = "Collectd::plugin_call_all";
1153 XPUSHs(sv_2mortal(newSViv((IV)type)));
1154 } else if (PLUGIN_SHUTDOWN == type) {
1155 subname = "Collectd::plugin_call_all";
1156 XPUSHs(sv_2mortal(newSViv((IV)type)));
1157 } else { /* Unknown type. Run 'plugin_call_all' and make compiler happy */
1158 subname = "Collectd::plugin_call_all";
1159 XPUSHs(sv_2mortal(newSViv((IV)type)));
1160 }
1162 PUTBACK;
1164 retvals = call_pv_locked(aTHX_ subname);
1166 SPAGAIN;
1167 if (SvTRUE(ERRSV)) {
1168 if (PLUGIN_LOG != type)
1169 ERROR("perl: %s error: %s", subname, SvPV_nolen(ERRSV));
1170 ret = -1;
1171 } else if (0 < retvals) {
1172 SV *tmp = POPs;
1173 if (!SvTRUE(tmp))
1174 ret = -1;
1175 }
1177 PUTBACK;
1178 FREETMPS;
1179 LEAVE;
1181 va_end(ap);
1182 return ret;
1183 } /* static int pplugin_call (int, ...) */
1185 /*
1186 * collectd's Perl interpreter based thread implementation.
1187 *
1188 * This has been inspired by Perl's ithreads introduced in version 5.6.0.
1189 */
1191 /* must be called with perl_threads->mutex locked */
1192 static void c_ithread_destroy(c_ithread_t *ithread) {
1193 dTHXa(ithread->interp);
1195 assert(NULL != perl_threads);
1197 PERL_SET_CONTEXT(aTHX);
1198 /* Mark as running to avoid deadlock:
1199 c_ithread_destroy -> log_debug -> perl_log()
1200 */
1201 ithread->running = 1;
1202 log_debug("Shutting down Perl interpreter %p...", aTHX);
1204 #if COLLECT_DEBUG
1205 sv_report_used();
1207 --perl_threads->number_of_threads;
1208 #endif /* COLLECT_DEBUG */
1210 perl_destruct(aTHX);
1211 perl_free(aTHX);
1213 if (NULL == ithread->prev)
1214 perl_threads->head = ithread->next;
1215 else
1216 ithread->prev->next = ithread->next;
1218 if (NULL == ithread->next)
1219 perl_threads->tail = ithread->prev;
1220 else
1221 ithread->next->prev = ithread->prev;
1223 sfree(ithread);
1224 return;
1225 } /* static void c_ithread_destroy (c_ithread_t *) */
1227 static void c_ithread_destructor(void *arg) {
1228 c_ithread_t *ithread = (c_ithread_t *)arg;
1229 c_ithread_t *t = NULL;
1231 if (NULL == perl_threads)
1232 return;
1234 pthread_mutex_lock(&perl_threads->mutex);
1236 for (t = perl_threads->head; NULL != t; t = t->next)
1237 if (t == ithread)
1238 break;
1240 /* the ithread no longer exists */
1241 if (NULL == t) {
1242 pthread_mutex_unlock(&perl_threads->mutex);
1243 return;
1244 }
1246 c_ithread_destroy(ithread);
1248 pthread_mutex_unlock(&perl_threads->mutex);
1249 return;
1250 } /* static void c_ithread_destructor (void *) */
1252 /* must be called with perl_threads->mutex locked */
1253 static c_ithread_t *c_ithread_create(PerlInterpreter *base) {
1254 c_ithread_t *t = NULL;
1255 dTHXa(NULL);
1257 assert(NULL != perl_threads);
1259 t = smalloc(sizeof(*t));
1260 memset(t, 0, sizeof(c_ithread_t));
1262 t->interp = (NULL == base) ? NULL : perl_clone(base, CLONEf_KEEP_PTR_TABLE);
1264 aTHX = t->interp;
1266 if ((NULL != base) && (NULL != PL_endav)) {
1267 av_clear(PL_endav);
1268 av_undef(PL_endav);
1269 PL_endav = Nullav;
1270 }
1272 #if COLLECT_DEBUG
1273 ++perl_threads->number_of_threads;
1274 #endif /* COLLECT_DEBUG */
1276 t->next = NULL;
1278 if (NULL == perl_threads->tail) {
1279 perl_threads->head = t;
1280 t->prev = NULL;
1281 } else {
1282 perl_threads->tail->next = t;
1283 t->prev = perl_threads->tail;
1284 }
1286 t->pthread = pthread_self();
1287 t->running = 0;
1288 t->shutdown = 0;
1289 perl_threads->tail = t;
1291 pthread_setspecific(perl_thr_key, (const void *)t);
1292 return t;
1293 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
1295 /*
1296 * Filter chains implementation.
1297 */
1299 static int fc_call(pTHX_ int type, int cb_type, pfc_user_data_t *data, ...) {
1300 int retvals = 0;
1302 va_list ap;
1303 int ret = 0;
1305 notification_meta_t **meta = NULL;
1306 AV *pmeta = NULL;
1308 dSP;
1310 if ((type < 0) || (type >= FC_TYPES))
1311 return -1;
1313 if ((cb_type < 0) || (cb_type >= FC_CB_TYPES))
1314 return -1;
1316 va_start(ap, data);
1318 ENTER;
1319 SAVETMPS;
1321 PUSHMARK(SP);
1323 XPUSHs(sv_2mortal(newSViv((IV)type)));
1324 XPUSHs(sv_2mortal(newSVpv(data->name, 0)));
1325 XPUSHs(sv_2mortal(newSViv((IV)cb_type)));
1327 if (FC_CB_CREATE == cb_type) {
1328 /*
1329 * $_[0] = $ci;
1330 * $_[1] = $user_data;
1331 */
1332 oconfig_item_t *ci;
1333 HV *config = newHV();
1335 ci = va_arg(ap, oconfig_item_t *);
1337 if (0 != oconfig_item2hv(aTHX_ ci, config)) {
1338 hv_clear(config);
1339 hv_undef(config);
1340 config = (HV *)&PL_sv_undef;
1341 ret = -1;
1342 }
1344 XPUSHs(sv_2mortal(newRV_noinc((SV *)config)));
1345 } else if (FC_CB_DESTROY == cb_type) {
1346 /*
1347 * $_[1] = $user_data;
1348 */
1350 /* nothing to be done - the user data pointer
1351 * is pushed onto the stack later */
1352 } else if (FC_CB_EXEC == cb_type) {
1353 /*
1354 * $_[0] = $ds;
1355 * $_[1] = $vl;
1356 * $_[2] = $meta;
1357 * $_[3] = $user_data;
1358 */
1359 data_set_t *ds;
1360 value_list_t *vl;
1362 AV *pds = newAV();
1363 HV *pvl = newHV();
1365 ds = va_arg(ap, data_set_t *);
1366 vl = va_arg(ap, value_list_t *);
1367 meta = va_arg(ap, notification_meta_t **);
1369 if (0 != data_set2av(aTHX_ ds, pds)) {
1370 av_clear(pds);
1371 av_undef(pds);
1372 pds = (AV *)&PL_sv_undef;
1373 ret = -1;
1374 }
1376 if (0 != value_list2hv(aTHX_ vl, ds, pvl)) {
1377 hv_clear(pvl);
1378 hv_undef(pvl);
1379 pvl = (HV *)&PL_sv_undef;
1380 ret = -1;
1381 }
1383 if (NULL != meta) {
1384 pmeta = newAV();
1386 if (0 != notification_meta2av(aTHX_ * meta, pmeta)) {
1387 av_clear(pmeta);
1388 av_undef(pmeta);
1389 pmeta = (AV *)&PL_sv_undef;
1390 ret = -1;
1391 }
1392 } else {
1393 pmeta = (AV *)&PL_sv_undef;
1394 }
1396 XPUSHs(sv_2mortal(newRV_noinc((SV *)pds)));
1397 XPUSHs(sv_2mortal(newRV_noinc((SV *)pvl)));
1398 XPUSHs(sv_2mortal(newRV_noinc((SV *)pmeta)));
1399 }
1401 XPUSHs(sv_2mortal(newRV_inc(data->user_data)));
1403 PUTBACK;
1405 retvals = call_pv_locked(aTHX_ "Collectd::fc_call");
1407 if ((FC_CB_EXEC == cb_type) && (meta != NULL)) {
1408 assert(pmeta != NULL);
1410 plugin_notification_meta_free(*meta);
1411 av2notification_meta(aTHX_ pmeta, meta);
1412 }
1414 SPAGAIN;
1415 if (SvTRUE(ERRSV)) {
1416 ERROR("perl: Collectd::fc_call error: %s", SvPV_nolen(ERRSV));
1417 ret = -1;
1418 } else if (0 < retvals) {
1419 SV *tmp = POPs;
1421 /* the exec callbacks return a status, while
1422 * the others return a boolean value */
1423 if (FC_CB_EXEC == cb_type)
1424 ret = SvIV(tmp);
1425 else if (!SvTRUE(tmp))
1426 ret = -1;
1427 }
1429 PUTBACK;
1430 FREETMPS;
1431 LEAVE;
1433 va_end(ap);
1434 return ret;
1435 } /* static int fc_call (int, int, pfc_user_data_t *, ...) */
1437 static int fc_create(int type, const oconfig_item_t *ci, void **user_data) {
1438 pfc_user_data_t *data;
1440 int ret = 0;
1442 dTHX;
1444 if (NULL == perl_threads)
1445 return 0;
1447 if (NULL == aTHX) {
1448 c_ithread_t *t = NULL;
1450 pthread_mutex_lock(&perl_threads->mutex);
1451 t = c_ithread_create(perl_threads->head->interp);
1452 pthread_mutex_unlock(&perl_threads->mutex);
1454 aTHX = t->interp;
1455 }
1457 log_debug("fc_create: c_ithread: interp = %p (active threads: %i)", aTHX,
1458 perl_threads->number_of_threads);
1460 if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1461 log_warn("A \"%s\" block expects a single string argument.",
1462 (FC_MATCH == type) ? "Match" : "Target");
1463 return -1;
1464 }
1466 data = smalloc(sizeof(*data));
1467 data->name = sstrdup(ci->values[0].value.string);
1468 data->user_data = newSV(0);
1470 ret = fc_call(aTHX_ type, FC_CB_CREATE, data, ci);
1472 if (0 != ret)
1473 PFC_USER_DATA_FREE(data);
1474 else
1475 *user_data = data;
1476 return ret;
1477 } /* static int fc_create (int, const oconfig_item_t *, void **) */
1479 static int fc_destroy(int type, void **user_data) {
1480 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1482 int ret = 0;
1484 dTHX;
1486 if ((NULL == perl_threads) || (NULL == data))
1487 return 0;
1489 if (NULL == aTHX) {
1490 c_ithread_t *t = NULL;
1492 pthread_mutex_lock(&perl_threads->mutex);
1493 t = c_ithread_create(perl_threads->head->interp);
1494 pthread_mutex_unlock(&perl_threads->mutex);
1496 aTHX = t->interp;
1497 }
1499 log_debug("fc_destroy: c_ithread: interp = %p (active threads: %i)", aTHX,
1500 perl_threads->number_of_threads);
1502 ret = fc_call(aTHX_ type, FC_CB_DESTROY, data);
1504 PFC_USER_DATA_FREE(data);
1505 *user_data = NULL;
1506 return ret;
1507 } /* static int fc_destroy (int, void **) */
1509 static int fc_exec(int type, const data_set_t *ds, const value_list_t *vl,
1510 notification_meta_t **meta, void **user_data) {
1511 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1513 dTHX;
1515 if (NULL == perl_threads)
1516 return 0;
1518 assert(NULL != data);
1520 if (NULL == aTHX) {
1521 c_ithread_t *t = NULL;
1523 pthread_mutex_lock(&perl_threads->mutex);
1524 t = c_ithread_create(perl_threads->head->interp);
1525 pthread_mutex_unlock(&perl_threads->mutex);
1527 aTHX = t->interp;
1528 }
1530 log_debug("fc_exec: c_ithread: interp = %p (active threads: %i)", aTHX,
1531 perl_threads->number_of_threads);
1533 return fc_call(aTHX_ type, FC_CB_EXEC, data, ds, vl, meta);
1534 } /* static int fc_exec (int, const data_set_t *, const value_list_t *,
1535 notification_meta_t **, void **) */
1537 static int pmatch_create(const oconfig_item_t *ci, void **user_data) {
1538 return fc_create(FC_MATCH, ci, user_data);
1539 } /* static int pmatch_create (const oconfig_item_t *, void **) */
1541 static int pmatch_destroy(void **user_data) {
1542 return fc_destroy(FC_MATCH, user_data);
1543 } /* static int pmatch_destroy (void **) */
1545 static int pmatch_match(const data_set_t *ds, const value_list_t *vl,
1546 notification_meta_t **meta, void **user_data) {
1547 return fc_exec(FC_MATCH, ds, vl, meta, user_data);
1548 } /* static int pmatch_match (const data_set_t *, const value_list_t *,
1549 notification_meta_t **, void **) */
1551 static match_proc_t pmatch = {pmatch_create, pmatch_destroy, pmatch_match};
1553 static int ptarget_create(const oconfig_item_t *ci, void **user_data) {
1554 return fc_create(FC_TARGET, ci, user_data);
1555 } /* static int ptarget_create (const oconfig_item_t *, void **) */
1557 static int ptarget_destroy(void **user_data) {
1558 return fc_destroy(FC_TARGET, user_data);
1559 } /* static int ptarget_destroy (void **) */
1561 static int ptarget_invoke(const data_set_t *ds, value_list_t *vl,
1562 notification_meta_t **meta, void **user_data) {
1563 return fc_exec(FC_TARGET, ds, vl, meta, user_data);
1564 } /* static int ptarget_invoke (const data_set_t *, value_list_t *,
1565 notification_meta_t **, void **) */
1567 static target_proc_t ptarget = {ptarget_create, ptarget_destroy,
1568 ptarget_invoke};
1570 /*
1571 * Exported Perl API.
1572 */
1574 static void _plugin_register_generic_userdata(pTHX, int type,
1575 const char *desc) {
1576 int ret = 0;
1577 user_data_t userdata;
1578 char *pluginname;
1580 dXSARGS;
1582 if (2 != items) {
1583 log_err("Usage: Collectd::plugin_register_%s(pluginname, subname)", desc);
1584 XSRETURN_EMPTY;
1585 }
1587 if (!SvOK(ST(0))) {
1588 log_err("Collectd::plugin_register_%s(pluginname, subname): "
1589 "Invalid pluginname",
1590 desc);
1591 XSRETURN_EMPTY;
1592 }
1593 if (!SvOK(ST(1))) {
1594 log_err("Collectd::plugin_register_%s(pluginname, subname): "
1595 "Invalid subname",
1596 desc);
1597 XSRETURN_EMPTY;
1598 }
1600 /* Use pluginname as-is to allow flush a single perl plugin */
1601 pluginname = SvPV_nolen(ST(0));
1603 log_debug("Collectd::plugin_register_%s: "
1604 "plugin = \"%s\", sub = \"%s\"",
1605 desc, pluginname, SvPV_nolen(ST(1)));
1607 memset(&userdata, 0, sizeof(userdata));
1608 userdata.data = strdup(SvPV_nolen(ST(1)));
1609 userdata.free_func = free;
1611 if (PLUGIN_READ == type) {
1612 ret = plugin_register_complex_read(
1613 "perl", /* group */
1614 pluginname, perl_read, plugin_get_interval(), /* Default interval */
1615 &userdata);
1616 } else if (PLUGIN_WRITE == type) {
1617 ret = plugin_register_write(pluginname, perl_write, &userdata);
1618 } else if (PLUGIN_LOG == type) {
1619 ret = plugin_register_log(pluginname, perl_log, &userdata);
1620 } else if (PLUGIN_NOTIF == type) {
1621 ret = plugin_register_notification(pluginname, perl_notify, &userdata);
1622 } else if (PLUGIN_FLUSH == type) {
1623 if (1 == register_legacy_flush) { /* For collectd-5.7 only, #1731 */
1624 register_legacy_flush = 0;
1625 ret = plugin_register_flush("perl", perl_flush, /* user_data = */ NULL);
1626 }
1628 if (0 == ret)
1629 ret = plugin_register_flush(pluginname, perl_flush, &userdata);
1630 } else {
1631 ret = -1;
1632 }
1634 if (0 == ret)
1635 XSRETURN_YES;
1636 else {
1637 free(userdata.data);
1638 XSRETURN_EMPTY;
1639 }
1640 } /* static void _plugin_register_generic_userdata ( ... ) */
1642 /*
1643 * Collectd::plugin_register_TYPE (pluginname, subname).
1644 *
1645 * pluginname:
1646 * name of the perl plugin
1647 *
1648 * subname:
1649 * name of the plugin's subroutine that does the work
1650 */
1652 static XS(Collectd_plugin_register_read) {
1653 return _plugin_register_generic_userdata(aTHX, PLUGIN_READ, "read");
1654 }
1656 static XS(Collectd_plugin_register_write) {
1657 return _plugin_register_generic_userdata(aTHX, PLUGIN_WRITE, "write");
1658 }
1660 static XS(Collectd_plugin_register_log) {
1661 return _plugin_register_generic_userdata(aTHX, PLUGIN_LOG, "log");
1662 }
1664 static XS(Collectd_plugin_register_notification) {
1665 return _plugin_register_generic_userdata(aTHX, PLUGIN_NOTIF, "notification");
1666 }
1668 static XS(Collectd_plugin_register_flush) {
1669 return _plugin_register_generic_userdata(aTHX, PLUGIN_FLUSH, "flush");
1670 }
1672 typedef int perl_unregister_function_t(const char *name);
1674 static void _plugin_unregister_generic(pTHX, perl_unregister_function_t *unreg,
1675 const char *desc) {
1676 dXSARGS;
1678 if (1 != items) {
1679 log_err("Usage: Collectd::plugin_unregister_%s(pluginname)", desc);
1680 XSRETURN_EMPTY;
1681 }
1683 if (!SvOK(ST(0))) {
1684 log_err("Collectd::plugin_unregister_%s(pluginname): "
1685 "Invalid pluginname",
1686 desc);
1687 XSRETURN_EMPTY;
1688 }
1690 log_debug("Collectd::plugin_unregister_%s: plugin = \"%s\"", desc,
1691 SvPV_nolen(ST(0)));
1693 unreg(SvPV_nolen(ST(0)));
1695 XSRETURN_EMPTY;
1697 return;
1698 } /* static void _plugin_unregister_generic ( ... ) */
1700 /*
1701 * Collectd::plugin_unregister_TYPE (pluginname).
1702 *
1703 * TYPE:
1704 * type of callback to be unregistered: read, write, log, notification, flush
1705 *
1706 * pluginname:
1707 * name of the perl plugin
1708 */
1710 static XS(Collectd_plugin_unregister_read) {
1711 return _plugin_unregister_generic(aTHX, plugin_unregister_read, "read");
1712 }
1714 static XS(Collectd_plugin_unregister_write) {
1715 return _plugin_unregister_generic(aTHX, plugin_unregister_write, "write");
1716 }
1718 static XS(Collectd_plugin_unregister_log) {
1719 return _plugin_unregister_generic(aTHX, plugin_unregister_log, "log");
1720 }
1722 static XS(Collectd_plugin_unregister_notification) {
1723 return _plugin_unregister_generic(aTHX, plugin_unregister_notification,
1724 "notification");
1725 }
1727 static XS(Collectd_plugin_unregister_flush) {
1728 return _plugin_unregister_generic(aTHX, plugin_unregister_flush, "flush");
1729 }
1731 /*
1732 * Collectd::plugin_register_data_set (type, dataset).
1733 *
1734 * type:
1735 * type of the dataset
1736 *
1737 * dataset:
1738 * dataset to be registered
1739 */
1740 static XS(Collectd_plugin_register_ds) {
1741 SV *data = NULL;
1742 int ret = 0;
1744 dXSARGS;
1746 log_warn("Using plugin_register() to register new data-sets is "
1747 "deprecated - add new entries to a custom types.db instead.");
1749 if (2 != items) {
1750 log_err("Usage: Collectd::plugin_register_data_set(type, dataset)");
1751 XSRETURN_EMPTY;
1752 }
1754 log_debug("Collectd::plugin_register_data_set: "
1755 "type = \"%s\", dataset = \"%s\"",
1756 SvPV_nolen(ST(0)), SvPV_nolen(ST(1)));
1758 data = ST(1);
1760 if (SvROK(data) && (SVt_PVAV == SvTYPE(SvRV(data)))) {
1761 ret = pplugin_register_data_set(aTHX_ SvPV_nolen(ST(0)), (AV *)SvRV(data));
1762 } else {
1763 log_err("Collectd::plugin_register_data_set: Invalid data.");
1764 XSRETURN_EMPTY;
1765 }
1767 if (0 == ret)
1768 XSRETURN_YES;
1769 else
1770 XSRETURN_EMPTY;
1771 } /* static XS (Collectd_plugin_register_ds) */
1773 /*
1774 * Collectd::plugin_unregister_data_set (type).
1775 *
1776 * type:
1777 * type of the dataset
1778 */
1779 static XS(Collectd_plugin_unregister_ds) {
1780 dXSARGS;
1782 if (1 != items) {
1783 log_err("Usage: Collectd::plugin_unregister_data_set(type)");
1784 XSRETURN_EMPTY;
1785 }
1787 log_debug("Collectd::plugin_unregister_data_set: type = \"%s\"",
1788 SvPV_nolen(ST(0)));
1790 if (0 == pplugin_unregister_data_set(SvPV_nolen(ST(0))))
1791 XSRETURN_YES;
1792 else
1793 XSRETURN_EMPTY;
1794 } /* static XS (Collectd_plugin_register_ds) */
1796 /*
1797 * Collectd::plugin_dispatch_values (name, values).
1798 *
1799 * name:
1800 * name of the plugin
1801 *
1802 * values:
1803 * value list to submit
1804 */
1805 static XS(Collectd_plugin_dispatch_values) {
1806 SV *values = NULL;
1808 int ret = 0;
1810 dXSARGS;
1812 if (1 != items) {
1813 log_err("Usage: Collectd::plugin_dispatch_values(values)");
1814 XSRETURN_EMPTY;
1815 }
1817 log_debug("Collectd::plugin_dispatch_values: values=\"%s\"",
1818 SvPV_nolen(ST(/* stack index = */ 0)));
1820 values = ST(/* stack index = */ 0);
1822 if (NULL == values)
1823 XSRETURN_EMPTY;
1825 /* Make sure the argument is a hash reference. */
1826 if (!(SvROK(values) && (SVt_PVHV == SvTYPE(SvRV(values))))) {
1827 log_err("Collectd::plugin_dispatch_values: Invalid values.");
1828 XSRETURN_EMPTY;
1829 }
1831 ret = pplugin_dispatch_values(aTHX_(HV *) SvRV(values));
1833 if (0 == ret)
1834 XSRETURN_YES;
1835 else
1836 XSRETURN_EMPTY;
1837 } /* static XS (Collectd_plugin_dispatch_values) */
1839 /*
1840 * Collectd::plugin_get_interval ().
1841 */
1842 static XS(Collectd_plugin_get_interval) {
1843 dXSARGS;
1845 /* make sure we don't get any unused variable warnings for 'items';
1846 * don't abort, though */
1847 if (items)
1848 log_err("Usage: Collectd::plugin_get_interval()");
1850 XSRETURN_NV((NV)CDTIME_T_TO_DOUBLE(plugin_get_interval()));
1851 } /* static XS (Collectd_plugin_get_interval) */
1853 /* Collectd::plugin_write (plugin, ds, vl).
1854 *
1855 * plugin:
1856 * name of the plugin to call, may be 'undef'
1857 *
1858 * ds:
1859 * data-set that describes the submitted values, may be 'undef'
1860 *
1861 * vl:
1862 * value-list to be written
1863 */
1864 static XS(Collectd__plugin_write) {
1865 char *plugin;
1866 SV *ds, *vl;
1867 AV *ds_array;
1869 int ret;
1871 dXSARGS;
1873 if (3 != items) {
1874 log_err("Usage: Collectd::plugin_write(plugin, ds, vl)");
1875 XSRETURN_EMPTY;
1876 }
1878 log_debug("Collectd::plugin_write: plugin=\"%s\", ds=\"%s\", vl=\"%s\"",
1879 SvPV_nolen(ST(0)), SvOK(ST(1)) ? SvPV_nolen(ST(1)) : "",
1880 SvPV_nolen(ST(2)));
1882 if (!SvOK(ST(0)))
1883 plugin = NULL;
1884 else
1885 plugin = SvPV_nolen(ST(0));
1887 ds = ST(1);
1888 if (SvROK(ds) && (SVt_PVAV == SvTYPE(SvRV(ds))))
1889 ds_array = (AV *)SvRV(ds);
1890 else if (!SvOK(ds))
1891 ds_array = NULL;
1892 else {
1893 log_err("Collectd::plugin_write: Invalid data-set.");
1894 XSRETURN_EMPTY;
1895 }
1897 vl = ST(2);
1898 if (!(SvROK(vl) && (SVt_PVHV == SvTYPE(SvRV(vl))))) {
1899 log_err("Collectd::plugin_write: Invalid value-list.");
1900 XSRETURN_EMPTY;
1901 }
1903 ret = pplugin_write(aTHX_ plugin, ds_array, (HV *)SvRV(vl));
1905 if (0 == ret)
1906 XSRETURN_YES;
1907 else
1908 XSRETURN_EMPTY;
1909 } /* static XS (Collectd__plugin_write) */
1911 /*
1912 * Collectd::_plugin_flush (plugin, timeout, identifier).
1913 *
1914 * plugin:
1915 * name of the plugin to flush
1916 *
1917 * timeout:
1918 * timeout to use when flushing the data
1919 *
1920 * identifier:
1921 * data-set identifier to flush
1922 */
1923 static XS(Collectd__plugin_flush) {
1924 char *plugin = NULL;
1925 int timeout = -1;
1926 char *id = NULL;
1928 dXSARGS;
1930 if (3 != items) {
1931 log_err("Usage: Collectd::_plugin_flush(plugin, timeout, id)");
1932 XSRETURN_EMPTY;
1933 }
1935 if (SvOK(ST(0)))
1936 plugin = SvPV_nolen(ST(0));
1938 if (SvOK(ST(1)))
1939 timeout = (int)SvIV(ST(1));
1941 if (SvOK(ST(2)))
1942 id = SvPV_nolen(ST(2));
1944 log_debug("Collectd::_plugin_flush: plugin = \"%s\", timeout = %i, "
1945 "id = \"%s\"",
1946 plugin, timeout, id);
1948 if (0 == plugin_flush(plugin, timeout, id))
1949 XSRETURN_YES;
1950 else
1951 XSRETURN_EMPTY;
1952 } /* static XS (Collectd__plugin_flush) */
1954 /*
1955 * Collectd::plugin_dispatch_notification (notif).
1956 *
1957 * notif:
1958 * notification to dispatch
1959 */
1960 static XS(Collectd_plugin_dispatch_notification) {
1961 SV *notif = NULL;
1963 int ret = 0;
1965 dXSARGS;
1967 if (1 != items) {
1968 log_err("Usage: Collectd::plugin_dispatch_notification(notif)");
1969 XSRETURN_EMPTY;
1970 }
1972 log_debug("Collectd::plugin_dispatch_notification: notif = \"%s\"",
1973 SvPV_nolen(ST(0)));
1975 notif = ST(0);
1977 if (!(SvROK(notif) && (SVt_PVHV == SvTYPE(SvRV(notif))))) {
1978 log_err("Collectd::plugin_dispatch_notification: Invalid notif.");
1979 XSRETURN_EMPTY;
1980 }
1982 ret = pplugin_dispatch_notification(aTHX_(HV *) SvRV(notif));
1984 if (0 == ret)
1985 XSRETURN_YES;
1986 else
1987 XSRETURN_EMPTY;
1988 } /* static XS (Collectd_plugin_dispatch_notification) */
1990 /*
1991 * Collectd::plugin_log (level, message).
1992 *
1993 * level:
1994 * log level (LOG_DEBUG, ... LOG_ERR)
1995 *
1996 * message:
1997 * log message
1998 */
1999 static XS(Collectd_plugin_log) {
2000 dXSARGS;
2002 if (2 != items) {
2003 log_err("Usage: Collectd::plugin_log(level, message)");
2004 XSRETURN_EMPTY;
2005 }
2007 plugin_log(SvIV(ST(0)), "%s", SvPV_nolen(ST(1)));
2008 XSRETURN_YES;
2009 } /* static XS (Collectd_plugin_log) */
2011 /*
2012 * Collectd::_fc_register (type, name)
2013 *
2014 * type:
2015 * match | target
2016 *
2017 * name:
2018 * name of the match
2019 */
2020 static XS(Collectd__fc_register) {
2021 int type;
2022 char *name;
2024 int ret = 0;
2026 dXSARGS;
2028 if (2 != items) {
2029 log_err("Usage: Collectd::_fc_register(type, name)");
2030 XSRETURN_EMPTY;
2031 }
2033 type = SvIV(ST(0));
2034 name = SvPV_nolen(ST(1));
2036 if (FC_MATCH == type)
2037 ret = fc_register_match(name, pmatch);
2038 else if (FC_TARGET == type)
2039 ret = fc_register_target(name, ptarget);
2041 if (0 == ret)
2042 XSRETURN_YES;
2043 else
2044 XSRETURN_EMPTY;
2045 } /* static XS (Collectd_fc_register) */
2047 /*
2048 * Collectd::call_by_name (...).
2049 *
2050 * Call a Perl sub identified by its name passed through $Collectd::cb_name.
2051 */
2052 static XS(Collectd_call_by_name) {
2053 SV *tmp = NULL;
2054 char *name = NULL;
2056 if (NULL == (tmp = get_sv("Collectd::cb_name", 0))) {
2057 sv_setpv(get_sv("@", 1), "cb_name has not been set");
2058 CLEAR_STACK_FRAME;
2059 return;
2060 }
2062 name = SvPV_nolen(tmp);
2064 if (NULL == get_cv(name, 0)) {
2065 sv_setpvf(get_sv("@", 1), "unknown callback \"%s\"", name);
2066 CLEAR_STACK_FRAME;
2067 return;
2068 }
2070 /* simply pass on the subroutine call without touching the stack,
2071 * thus leaving any arguments and return values in place */
2072 call_pv(name, 0);
2073 } /* static XS (Collectd_call_by_name) */
2075 /*
2076 * Interface to collectd.
2077 */
2079 static int perl_init(void) {
2080 int status;
2081 dTHX;
2083 if (NULL == perl_threads)
2084 return 0;
2086 if (NULL == aTHX) {
2087 c_ithread_t *t = NULL;
2089 pthread_mutex_lock(&perl_threads->mutex);
2090 t = c_ithread_create(perl_threads->head->interp);
2091 pthread_mutex_unlock(&perl_threads->mutex);
2093 aTHX = t->interp;
2094 }
2096 log_debug("perl_init: c_ithread: interp = %p (active threads: %i)", aTHX,
2097 perl_threads->number_of_threads);
2099 /* Lock the base thread to avoid race conditions with c_ithread_create().
2100 * See https://github.com/collectd/collectd/issues/9 and
2101 * https://github.com/collectd/collectd/issues/1706 for details.
2102 */
2103 assert(aTHX == perl_threads->head->interp);
2104 pthread_mutex_lock(&perl_threads->mutex);
2106 status = pplugin_call(aTHX_ PLUGIN_INIT);
2108 pthread_mutex_unlock(&perl_threads->mutex);
2110 return status;
2111 } /* static int perl_init (void) */
2113 static int perl_read(user_data_t *user_data) {
2114 dTHX;
2116 if (NULL == perl_threads)
2117 return 0;
2119 if (NULL == aTHX) {
2120 c_ithread_t *t = NULL;
2122 pthread_mutex_lock(&perl_threads->mutex);
2123 t = c_ithread_create(perl_threads->head->interp);
2124 pthread_mutex_unlock(&perl_threads->mutex);
2126 aTHX = t->interp;
2127 }
2129 /* Assert that we're not running as the base thread. Otherwise, we might
2130 * run into concurrency issues with c_ithread_create(). See
2131 * https://github.com/collectd/collectd/issues/9 for details. */
2132 assert(aTHX != perl_threads->head->interp);
2134 log_debug("perl_read: c_ithread: interp = %p (active threads: %i)", aTHX,
2135 perl_threads->number_of_threads);
2137 return pplugin_call(aTHX_ PLUGIN_READ, user_data->data);
2138 } /* static int perl_read (user_data_t *user_data) */
2140 static int perl_write(const data_set_t *ds, const value_list_t *vl,
2141 user_data_t *user_data) {
2142 int status;
2143 dTHX;
2145 if (NULL == perl_threads)
2146 return 0;
2148 if (NULL == aTHX) {
2149 c_ithread_t *t = NULL;
2151 pthread_mutex_lock(&perl_threads->mutex);
2152 t = c_ithread_create(perl_threads->head->interp);
2153 pthread_mutex_unlock(&perl_threads->mutex);
2155 aTHX = t->interp;
2156 }
2158 /* Lock the base thread if this is not called from one of the read threads
2159 * to avoid race conditions with c_ithread_create(). See
2160 * https://github.com/collectd/collectd/issues/9 for details. */
2161 if (aTHX == perl_threads->head->interp)
2162 pthread_mutex_lock(&perl_threads->mutex);
2164 log_debug("perl_write: c_ithread: interp = %p (active threads: %i)", aTHX,
2165 perl_threads->number_of_threads);
2166 status = pplugin_call(aTHX_ PLUGIN_WRITE, user_data->data, ds, vl);
2168 if (aTHX == perl_threads->head->interp)
2169 pthread_mutex_unlock(&perl_threads->mutex);
2171 return status;
2172 } /* static int perl_write (const data_set_t *, const value_list_t *) */
2174 static void perl_log(int level, const char *msg, user_data_t *user_data) {
2175 dTHX;
2177 if (NULL == perl_threads)
2178 return;
2180 if (NULL == aTHX) {
2181 c_ithread_t *t = NULL;
2183 pthread_mutex_lock(&perl_threads->mutex);
2184 t = c_ithread_create(perl_threads->head->interp);
2185 pthread_mutex_unlock(&perl_threads->mutex);
2187 aTHX = t->interp;
2188 }
2190 /* Lock the base thread if this is not called from one of the read threads
2191 * to avoid race conditions with c_ithread_create(). See
2192 * https://github.com/collectd/collectd/issues/9 for details.
2193 */
2195 if (aTHX == perl_threads->head->interp)
2196 pthread_mutex_lock(&perl_threads->mutex);
2198 pplugin_call(aTHX_ PLUGIN_LOG, user_data->data, level, msg);
2200 if (aTHX == perl_threads->head->interp)
2201 pthread_mutex_unlock(&perl_threads->mutex);
2203 return;
2204 } /* static void perl_log (int, const char *) */
2206 static int perl_notify(const notification_t *notif, user_data_t *user_data) {
2207 dTHX;
2209 if (NULL == perl_threads)
2210 return 0;
2212 if (NULL == aTHX) {
2213 c_ithread_t *t = NULL;
2215 pthread_mutex_lock(&perl_threads->mutex);
2216 t = c_ithread_create(perl_threads->head->interp);
2217 pthread_mutex_unlock(&perl_threads->mutex);
2219 aTHX = t->interp;
2220 }
2221 return pplugin_call(aTHX_ PLUGIN_NOTIF, user_data->data, notif);
2222 } /* static int perl_notify (const notification_t *) */
2224 static int perl_flush(cdtime_t timeout, const char *identifier,
2225 user_data_t *user_data) {
2226 dTHX;
2228 if (NULL == perl_threads)
2229 return 0;
2231 if (NULL == aTHX) {
2232 c_ithread_t *t = NULL;
2234 pthread_mutex_lock(&perl_threads->mutex);
2235 t = c_ithread_create(perl_threads->head->interp);
2236 pthread_mutex_unlock(&perl_threads->mutex);
2238 aTHX = t->interp;
2239 }
2241 /* For collectd-5.6 only, #1731 */
2242 if (user_data == NULL || user_data->data == NULL)
2243 return pplugin_call(aTHX_ PLUGIN_FLUSH_ALL, timeout, identifier);
2245 return pplugin_call(aTHX_ PLUGIN_FLUSH, user_data->data, timeout, identifier);
2246 } /* static int perl_flush (const int) */
2248 static int perl_shutdown(void) {
2249 c_ithread_t *t;
2250 int ret;
2252 dTHX;
2254 plugin_unregister_complex_config("perl");
2255 plugin_unregister_read_group("perl");
2257 if (NULL == perl_threads)
2258 return 0;
2260 if (NULL == aTHX) {
2261 pthread_mutex_lock(&perl_threads->mutex);
2262 t = c_ithread_create(perl_threads->head->interp);
2263 pthread_mutex_unlock(&perl_threads->mutex);
2265 aTHX = t->interp;
2266 }
2268 log_debug("perl_shutdown: c_ithread: interp = %p (active threads: %i)", aTHX,
2269 perl_threads->number_of_threads);
2271 plugin_unregister_init("perl");
2272 plugin_unregister_flush("perl"); /* For collectd-5.6 only, #1731 */
2274 ret = pplugin_call(aTHX_ PLUGIN_SHUTDOWN);
2276 pthread_mutex_lock(&perl_threads->mutex);
2277 t = perl_threads->tail;
2279 while (NULL != t) {
2280 struct timespec ts_wait;
2281 c_ithread_t *thr = t;
2283 /* the pointer has to be advanced before destroying
2284 * the thread as this will free the memory */
2285 t = t->prev;
2287 thr->shutdown = 1;
2288 if (thr->running) {
2289 /* Give some time to thread to exit from Perl interpreter */
2290 WARNING("perl shutdown: Thread is running inside Perl. Waiting.");
2291 ts_wait.tv_sec = 0;
2292 ts_wait.tv_nsec = 500000;
2293 nanosleep(&ts_wait, NULL);
2294 }
2295 if (thr->running) {
2296 pthread_kill(thr->pthread, SIGTERM);
2297 ERROR("perl shutdown: Thread hangs inside Perl. Thread killed.");
2298 }
2299 c_ithread_destroy(thr);
2300 }
2302 pthread_mutex_unlock(&perl_threads->mutex);
2303 pthread_mutex_destroy(&perl_threads->mutex);
2304 pthread_mutexattr_destroy(&perl_threads->mutexattr);
2306 sfree(perl_threads);
2308 pthread_key_delete(perl_thr_key);
2310 PERL_SYS_TERM();
2312 plugin_unregister_shutdown("perl");
2313 return ret;
2314 } /* static void perl_shutdown (void) */
2316 /*
2317 * Access functions for global variables.
2318 *
2319 * These functions implement the "magic" used to access
2320 * the global variables from Perl.
2321 */
2323 static int g_pv_get(pTHX_ SV *var, MAGIC *mg) {
2324 char *pv = mg->mg_ptr;
2325 sv_setpv(var, pv);
2326 return 0;
2327 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
2329 static int g_pv_set(pTHX_ SV *var, MAGIC *mg) {
2330 char *pv = mg->mg_ptr;
2331 sstrncpy(pv, SvPV_nolen(var), DATA_MAX_NAME_LEN);
2332 return 0;
2333 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
2335 static int g_interval_get(pTHX_ SV *var, MAGIC *mg) {
2336 log_warn("Accessing $interval_g is deprecated (and might not "
2337 "give the desired results) - plugin_get_interval() should "
2338 "be used instead.");
2339 sv_setnv(var, CDTIME_T_TO_DOUBLE(interval_g));
2340 return 0;
2341 } /* static int g_interval_get (pTHX_ SV *, MAGIC *) */
2343 static int g_interval_set(pTHX_ SV *var, MAGIC *mg) {
2344 double nv = (double)SvNV(var);
2345 log_warn("Accessing $interval_g is deprecated (and might not "
2346 "give the desired results) - plugin_get_interval() should "
2347 "be used instead.");
2348 interval_g = DOUBLE_TO_CDTIME_T(nv);
2349 return 0;
2350 } /* static int g_interval_set (pTHX_ SV *, MAGIC *) */
2352 static MGVTBL g_pv_vtbl = {g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL
2353 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2354 ,
2355 NULL
2356 #endif
2357 };
2358 static MGVTBL g_interval_vtbl = {g_interval_get, g_interval_set, NULL, NULL,
2359 NULL, NULL, NULL
2360 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2361 ,
2362 NULL
2363 #endif
2364 };
2366 /* bootstrap the Collectd module */
2367 static void xs_init(pTHX) {
2368 HV *stash = NULL;
2369 SV *tmp = NULL;
2370 char *file = __FILE__;
2372 dXSUB_SYS;
2374 /* enable usage of Perl modules using shared libraries */
2375 newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2377 /* register API */
2378 for (int i = 0; NULL != api[i].f; ++i)
2379 newXS(api[i].name, api[i].f, file);
2381 stash = gv_stashpv("Collectd", 1);
2383 /* export "constants" */
2384 for (int i = 0; '\0' != constants[i].name[0]; ++i)
2385 newCONSTSUB(stash, constants[i].name, newSViv(constants[i].value));
2387 /* export global variables
2388 * by adding "magic" to the SV's representing the globale variables
2389 * perl is able to automagically call the get/set function when
2390 * accessing any such variable (this is basically the same as using
2391 * tie() in Perl) */
2392 /* global strings */
2393 for (int i = 0; '\0' != g_strings[i].name[0]; ++i) {
2394 tmp = get_sv(g_strings[i].name, 1);
2395 sv_magicext(tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl, g_strings[i].var, 0);
2396 }
2398 tmp = get_sv("Collectd::interval_g", /* create = */ 1);
2399 sv_magicext(tmp, NULL, /* how = */ PERL_MAGIC_ext,
2400 /* vtbl = */ &g_interval_vtbl,
2401 /* name = */ NULL, /* namelen = */ 0);
2403 return;
2404 } /* static void xs_init (pTHX) */
2406 /* Initialize the global Perl interpreter. */
2407 static int init_pi(int argc, char **argv) {
2408 dTHXa(NULL);
2410 if (NULL != perl_threads)
2411 return 0;
2413 log_info("Initializing Perl interpreter...");
2414 #if COLLECT_DEBUG
2415 {
2416 for (int i = 0; i < argc; ++i)
2417 log_debug("argv[%i] = \"%s\"", i, argv[i]);
2418 }
2419 #endif /* COLLECT_DEBUG */
2421 if (0 != pthread_key_create(&perl_thr_key, c_ithread_destructor)) {
2422 log_err("init_pi: pthread_key_create failed");
2424 /* this must not happen - cowardly giving up if it does */
2425 return -1;
2426 }
2428 #ifdef __FreeBSD__
2429 /* On FreeBSD, PERL_SYS_INIT3 expands to some expression which
2430 * triggers a "value computed is not used" warning by gcc. */
2431 (void)
2432 #endif
2433 PERL_SYS_INIT3(&argc, &argv, &environ);
2435 perl_threads = smalloc(sizeof(*perl_threads));
2436 memset(perl_threads, 0, sizeof(c_ithread_list_t));
2438 pthread_mutexattr_init(&perl_threads->mutexattr);
2439 pthread_mutexattr_settype(&perl_threads->mutexattr, PTHREAD_MUTEX_RECURSIVE);
2440 pthread_mutex_init(&perl_threads->mutex, &perl_threads->mutexattr);
2441 /* locking the mutex should not be necessary at this point
2442 * but let's just do it for the sake of completeness */
2443 pthread_mutex_lock(&perl_threads->mutex);
2445 perl_threads->head = c_ithread_create(NULL);
2446 perl_threads->tail = perl_threads->head;
2448 if (NULL == (perl_threads->head->interp = perl_alloc())) {
2449 log_err("init_pi: Not enough memory.");
2450 exit(3);
2451 }
2453 aTHX = perl_threads->head->interp;
2454 pthread_mutex_unlock(&perl_threads->mutex);
2456 perl_construct(aTHX);
2458 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
2460 if (0 != perl_parse(aTHX_ xs_init, argc, argv, NULL)) {
2461 SV *err = get_sv("@", 1);
2462 log_err("init_pi: Unable to bootstrap Collectd: %s", SvPV_nolen(err));
2464 perl_destruct(perl_threads->head->interp);
2465 perl_free(perl_threads->head->interp);
2466 sfree(perl_threads);
2468 pthread_key_delete(perl_thr_key);
2469 return -1;
2470 }
2472 /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
2473 sv_setpv(get_sv("0", 0), "collectd");
2475 perl_run(aTHX);
2477 plugin_register_init("perl", perl_init);
2478 plugin_register_shutdown("perl", perl_shutdown);
2479 return 0;
2480 } /* static int init_pi (const char **, const int) */
2482 /*
2483 * LoadPlugin "<Plugin>"
2484 */
2485 static int perl_config_loadplugin(pTHX_ oconfig_item_t *ci) {
2486 char module_name[DATA_MAX_NAME_LEN];
2488 char *value = NULL;
2490 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2491 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2492 log_err("LoadPlugin expects a single string argument.");
2493 return 1;
2494 }
2496 value = ci->values[0].value.string;
2498 if (NULL == get_module_name(module_name, sizeof(module_name), value)) {
2499 log_err("Invalid module name %s", value);
2500 return 1;
2501 }
2503 if (0 != init_pi(perl_argc, perl_argv))
2504 return -1;
2506 assert(NULL != perl_threads);
2507 assert(NULL != perl_threads->head);
2509 aTHX = perl_threads->head->interp;
2511 log_debug("perl_config: Loading Perl plugin \"%s\"", value);
2512 load_module(PERL_LOADMOD_NOIMPORT, newSVpv(module_name, strlen(module_name)),
2513 Nullsv);
2514 return 0;
2515 } /* static int perl_config_loadplugin (oconfig_item_it *) */
2517 /*
2518 * BaseName "<Name>"
2519 */
2520 static int perl_config_basename(pTHX_ oconfig_item_t *ci) {
2521 char *value = NULL;
2523 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2524 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2525 log_err("BaseName expects a single string argument.");
2526 return 1;
2527 }
2529 value = ci->values[0].value.string;
2531 log_debug("perl_config: Setting plugin basename to \"%s\"", value);
2532 sstrncpy(base_name, value, sizeof(base_name));
2533 return 0;
2534 } /* static int perl_config_basename (oconfig_item_it *) */
2536 /*
2537 * EnableDebugger "<Package>"|""
2538 */
2539 static int perl_config_enabledebugger(pTHX_ oconfig_item_t *ci) {
2540 char *value = NULL;
2542 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2543 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2544 log_err("EnableDebugger expects a single string argument.");
2545 return 1;
2546 }
2548 if (NULL != perl_threads) {
2549 log_warn("EnableDebugger has no effects if used after LoadPlugin.");
2550 return 1;
2551 }
2553 value = ci->values[0].value.string;
2555 perl_argv = realloc(perl_argv, (++perl_argc + 1) * sizeof(char *));
2557 if (NULL == perl_argv) {
2558 log_err("perl_config: Not enough memory.");
2559 exit(3);
2560 }
2562 if ('\0' == value[0]) {
2563 perl_argv[perl_argc - 1] = "-d";
2564 } else {
2565 perl_argv[perl_argc - 1] = smalloc(strlen(value) + 4);
2566 sstrncpy(perl_argv[perl_argc - 1], "-d:", 4);
2567 sstrncpy(perl_argv[perl_argc - 1] + 3, value, strlen(value) + 1);
2568 }
2570 perl_argv[perl_argc] = NULL;
2571 return 0;
2572 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
2574 /*
2575 * IncludeDir "<Dir>"
2576 */
2577 static int perl_config_includedir(pTHX_ oconfig_item_t *ci) {
2578 char *value = NULL;
2580 if ((0 != ci->children_num) || (1 != ci->values_num) ||
2581 (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2582 log_err("IncludeDir expects a single string argument.");
2583 return 1;
2584 }
2586 value = ci->values[0].value.string;
2588 if (NULL == aTHX) {
2589 perl_argv = realloc(perl_argv, (++perl_argc + 1) * sizeof(char *));
2591 if (NULL == perl_argv) {
2592 log_err("perl_config: Not enough memory.");
2593 exit(3);
2594 }
2596 perl_argv[perl_argc - 1] = smalloc(strlen(value) + 3);
2597 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
2598 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen(value) + 1);
2600 perl_argv[perl_argc] = NULL;
2601 } else {
2602 /* prepend the directory to @INC */
2603 av_unshift(GvAVn(PL_incgv), 1);
2604 av_store(GvAVn(PL_incgv), 0, newSVpv(value, strlen(value)));
2605 }
2606 return 0;
2607 } /* static int perl_config_includedir (oconfig_item_it *) */
2609 /*
2610 * <Plugin> block
2611 */
2612 static int perl_config_plugin(pTHX_ oconfig_item_t *ci) {
2613 int retvals = 0;
2614 int ret = 0;
2616 char *plugin;
2617 HV *config;
2619 dSP;
2621 if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2622 log_err("LoadPlugin expects a single string argument.");
2623 return 1;
2624 }
2626 plugin = ci->values[0].value.string;
2627 config = newHV();
2629 if (0 != oconfig_item2hv(aTHX_ ci, config)) {
2630 hv_clear(config);
2631 hv_undef(config);
2633 log_err("Unable to convert configuration to a Perl hash value.");
2634 config = (HV *)&PL_sv_undef;
2635 }
2637 ENTER;
2638 SAVETMPS;
2640 PUSHMARK(SP);
2642 XPUSHs(sv_2mortal(newSVpv(plugin, 0)));
2643 XPUSHs(sv_2mortal(newRV_noinc((SV *)config)));
2645 PUTBACK;
2647 retvals = call_pv("Collectd::_plugin_dispatch_config", G_SCALAR);
2649 SPAGAIN;
2650 if (0 < retvals) {
2651 SV *tmp = POPs;
2652 if (!SvTRUE(tmp))
2653 ret = 1;
2654 } else
2655 ret = 1;
2657 PUTBACK;
2658 FREETMPS;
2659 LEAVE;
2660 return ret;
2661 } /* static int perl_config_plugin (oconfig_item_it *) */
2663 static int perl_config(oconfig_item_t *ci) {
2664 int status = 0;
2666 dTHXa(NULL);
2668 for (int i = 0; i < ci->children_num; ++i) {
2669 oconfig_item_t *c = ci->children + i;
2670 int current_status = 0;
2672 if (NULL != perl_threads) {
2673 if ((aTHX = PERL_GET_CONTEXT) == NULL)
2674 return -1;
2675 }
2677 if (0 == strcasecmp(c->key, "LoadPlugin"))
2678 current_status = perl_config_loadplugin(aTHX_ c);
2679 else if (0 == strcasecmp(c->key, "BaseName"))
2680 current_status = perl_config_basename(aTHX_ c);
2681 else if (0 == strcasecmp(c->key, "EnableDebugger"))
2682 current_status = perl_config_enabledebugger(aTHX_ c);
2683 else if (0 == strcasecmp(c->key, "IncludeDir"))
2684 current_status = perl_config_includedir(aTHX_ c);
2685 else if (0 == strcasecmp(c->key, "Plugin"))
2686 current_status = perl_config_plugin(aTHX_ c);
2687 else if (0 == strcasecmp(c->key, "RegisterLegacyFlush"))
2688 cf_util_get_boolean(c, ®ister_legacy_flush);
2689 else {
2690 log_warn("Ignoring unknown config key \"%s\".", c->key);
2691 current_status = 0;
2692 }
2694 /* fatal error - it's up to perl_config_* to clean up */
2695 if (0 > current_status) {
2696 log_err("Configuration failed with a fatal error - "
2697 "plugin disabled!");
2698 return current_status;
2699 }
2701 status += current_status;
2702 }
2703 return status;
2704 } /* static int perl_config (oconfig_item_t *) */
2706 void module_register(void) {
2707 perl_argc = 4;
2708 perl_argv = smalloc((perl_argc + 1) * sizeof(*perl_argv));
2710 /* default options for the Perl interpreter */
2711 perl_argv[0] = "";
2712 perl_argv[1] = "-MCollectd";
2713 perl_argv[2] = "-e";
2714 perl_argv[3] = "1";
2715 perl_argv[4] = NULL;
2717 plugin_register_complex_config("perl", perl_config);
2718 return;
2719 } /* void module_register (void) */