700bb989cb856d8a24757690ab2b3a89cd52bff5
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 #if HAVE_STDBOOL_H
42 # include <stdbool.h>
43 #endif
45 #include <EXTERN.h>
46 #include <perl.h>
48 #if defined(COLLECT_DEBUG) && COLLECT_DEBUG && defined(__GNUC__) && __GNUC__
49 # undef sprintf
50 # pragma GCC poison sprintf
51 #endif
53 #include <XSUB.h>
55 /* Some versions of Perl define their own version of DEBUG... :-/ */
56 #ifdef DEBUG
57 # undef DEBUG
58 #endif /* DEBUG */
60 /* ... while we want the definition found in plugin.h. */
61 #include "plugin.h"
62 #include "common.h"
64 #include "filter_chain.h"
66 #if !defined(USE_ITHREADS)
67 # error "Perl does not support ithreads!"
68 #endif /* !defined(USE_ITHREADS) */
70 /* clear the Perl sub's stack frame
71 * (this should only be used inside an XSUB) */
72 #define CLEAR_STACK_FRAME PL_stack_sp = PL_stack_base + *PL_markstack_ptr
74 #define PLUGIN_INIT 0
75 #define PLUGIN_READ 1
76 #define PLUGIN_WRITE 2
77 #define PLUGIN_SHUTDOWN 3
78 #define PLUGIN_LOG 4
79 #define PLUGIN_NOTIF 5
80 #define PLUGIN_FLUSH 6
82 #define PLUGIN_TYPES 7
84 #define PLUGIN_CONFIG 254
85 #define PLUGIN_DATASET 255
87 #define FC_MATCH 0
88 #define FC_TARGET 1
90 #define FC_TYPES 2
92 #define FC_CB_CREATE 0
93 #define FC_CB_DESTROY 1
94 #define FC_CB_EXEC 2
96 #define FC_CB_TYPES 3
98 #define log_debug(...) DEBUG ("perl: " __VA_ARGS__)
99 #define log_info(...) INFO ("perl: " __VA_ARGS__)
100 #define log_warn(...) WARNING ("perl: " __VA_ARGS__)
101 #define log_err(...) ERROR ("perl: " __VA_ARGS__)
103 /* this is defined in DynaLoader.a */
104 void boot_DynaLoader (PerlInterpreter *, CV *);
106 static XS (Collectd_plugin_register_read);
107 static XS (Collectd_plugin_register_write);
108 static XS (Collectd_plugin_register_log);
109 static XS (Collectd_plugin_register_notification);
110 static XS (Collectd_plugin_register_flush);
111 static XS (Collectd_plugin_unregister_read);
112 static XS (Collectd_plugin_unregister_write);
113 static XS (Collectd_plugin_unregister_log);
114 static XS (Collectd_plugin_unregister_notification);
115 static XS (Collectd_plugin_unregister_flush);
116 static XS (Collectd_plugin_register_ds);
117 static XS (Collectd_plugin_unregister_ds);
118 static XS (Collectd_plugin_dispatch_values);
119 static XS (Collectd_plugin_get_interval);
120 static XS (Collectd__plugin_write);
121 static XS (Collectd__plugin_flush);
122 static XS (Collectd_plugin_dispatch_notification);
123 static XS (Collectd_plugin_log);
124 static XS (Collectd__fc_register);
125 static XS (Collectd_call_by_name);
127 static int perl_read (user_data_t *ud);
128 static int perl_write (const data_set_t *ds, const value_list_t *vl,
129 user_data_t *user_data);
130 static void perl_log (int level, const char *msg, user_data_t *user_data);
131 static int perl_notify (const notification_t *notif, user_data_t *user_data);
132 static int perl_flush (cdtime_t timeout, const char *identifier,
133 user_data_t *user_data);
135 /*
136 * private data types
137 */
139 typedef struct c_ithread_s {
140 /* the thread's Perl interpreter */
141 PerlInterpreter *interp;
142 _Bool running; /* thread is inside Perl interpreter */
143 _Bool shutdown;
144 pthread_t pthread;
146 /* double linked list of threads */
147 struct c_ithread_s *prev;
148 struct c_ithread_s *next;
149 } c_ithread_t;
151 typedef struct {
152 c_ithread_t *head;
153 c_ithread_t *tail;
155 #if COLLECT_DEBUG
156 /* some usage stats */
157 int number_of_threads;
158 #endif /* COLLECT_DEBUG */
160 pthread_mutex_t mutex;
161 pthread_mutexattr_t mutexattr;
162 } c_ithread_list_t;
164 /* name / user_data for Perl matches / targets */
165 typedef struct {
166 char *name;
167 SV *user_data;
168 } pfc_user_data_t;
170 #define PFC_USER_DATA_FREE(data) \
171 do { \
172 sfree ((data)->name); \
173 if (NULL != (data)->user_data) \
174 sv_free ((data)->user_data); \
175 sfree (data); \
176 } while (0)
178 /*
179 * Public variable
180 */
181 extern char **environ;
183 /*
184 * private variables
185 */
187 /* if perl_threads != NULL perl_threads->head must
188 * point to the "base" thread */
189 static c_ithread_list_t *perl_threads = NULL;
191 /* the key used to store each pthread's ithread */
192 static pthread_key_t perl_thr_key;
194 static int perl_argc = 0;
195 static char **perl_argv = NULL;
197 static char base_name[DATA_MAX_NAME_LEN] = "";
199 static struct {
200 char name[64];
201 XS ((*f));
202 } api[] =
203 {
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 }
228 };
230 struct {
231 char name[64];
232 int value;
233 } constants[] =
234 {
235 { "Collectd::TYPE_INIT", PLUGIN_INIT },
236 { "Collectd::TYPE_READ", PLUGIN_READ },
237 { "Collectd::TYPE_WRITE", PLUGIN_WRITE },
238 { "Collectd::TYPE_SHUTDOWN", PLUGIN_SHUTDOWN },
239 { "Collectd::TYPE_LOG", PLUGIN_LOG },
240 { "Collectd::TYPE_NOTIF", PLUGIN_NOTIF },
241 { "Collectd::TYPE_FLUSH", PLUGIN_FLUSH },
242 { "Collectd::TYPE_CONFIG", PLUGIN_CONFIG },
243 { "Collectd::TYPE_DATASET", PLUGIN_DATASET },
244 { "Collectd::DS_TYPE_COUNTER", DS_TYPE_COUNTER },
245 { "Collectd::DS_TYPE_GAUGE", DS_TYPE_GAUGE },
246 { "Collectd::DS_TYPE_DERIVE", DS_TYPE_DERIVE },
247 { "Collectd::DS_TYPE_ABSOLUTE", DS_TYPE_ABSOLUTE },
248 { "Collectd::LOG_ERR", LOG_ERR },
249 { "Collectd::LOG_WARNING", LOG_WARNING },
250 { "Collectd::LOG_NOTICE", LOG_NOTICE },
251 { "Collectd::LOG_INFO", LOG_INFO },
252 { "Collectd::LOG_DEBUG", LOG_DEBUG },
253 { "Collectd::FC_MATCH", FC_MATCH },
254 { "Collectd::FC_TARGET", FC_TARGET },
255 { "Collectd::FC_CB_CREATE", FC_CB_CREATE },
256 { "Collectd::FC_CB_DESTROY", FC_CB_DESTROY },
257 { "Collectd::FC_CB_EXEC", FC_CB_EXEC },
258 { "Collectd::FC_MATCH_NO_MATCH", FC_MATCH_NO_MATCH },
259 { "Collectd::FC_MATCH_MATCHES", FC_MATCH_MATCHES },
260 { "Collectd::FC_TARGET_CONTINUE", FC_TARGET_CONTINUE },
261 { "Collectd::FC_TARGET_STOP", FC_TARGET_STOP },
262 { "Collectd::FC_TARGET_RETURN", FC_TARGET_RETURN },
263 { "Collectd::NOTIF_FAILURE", NOTIF_FAILURE },
264 { "Collectd::NOTIF_WARNING", NOTIF_WARNING },
265 { "Collectd::NOTIF_OKAY", NOTIF_OKAY },
266 { "", 0 }
267 };
269 struct {
270 char name[64];
271 char *var;
272 } g_strings[] =
273 {
274 { "Collectd::hostname_g", hostname_g },
275 { "", NULL }
276 };
278 /*
279 * Helper functions for data type conversion.
280 */
282 /*
283 * data source:
284 * [
285 * {
286 * name => $ds_name,
287 * type => $ds_type,
288 * min => $ds_min,
289 * max => $ds_max
290 * },
291 * ...
292 * ]
293 */
294 static int hv2data_source (pTHX_ HV *hash, data_source_t *ds)
295 {
296 SV **tmp = NULL;
298 if ((NULL == hash) || (NULL == ds))
299 return -1;
301 if (NULL != (tmp = hv_fetch (hash, "name", 4, 0))) {
302 sstrncpy (ds->name, SvPV_nolen (*tmp), sizeof (ds->name));
303 }
304 else {
305 log_err ("hv2data_source: No DS name given.");
306 return -1;
307 }
309 if (NULL != (tmp = hv_fetch (hash, "type", 4, 0))) {
310 ds->type = SvIV (*tmp);
312 if ((DS_TYPE_COUNTER != ds->type)
313 && (DS_TYPE_GAUGE != ds->type)
314 && (DS_TYPE_DERIVE != ds->type)
315 && (DS_TYPE_ABSOLUTE != ds->type)) {
316 log_err ("hv2data_source: Invalid DS type.");
317 return -1;
318 }
319 }
320 else {
321 ds->type = DS_TYPE_COUNTER;
322 }
324 if (NULL != (tmp = hv_fetch (hash, "min", 3, 0)))
325 ds->min = SvNV (*tmp);
326 else
327 ds->min = NAN;
329 if (NULL != (tmp = hv_fetch (hash, "max", 3, 0)))
330 ds->max = SvNV (*tmp);
331 else
332 ds->max = NAN;
333 return 0;
334 } /* static int hv2data_source (HV *, data_source_t *) */
336 /* av2value converts at most "len" elements from "array" to "value". Returns the
337 * number of elements converted or zero on error. */
338 static size_t av2value (pTHX_ char *name, AV *array, value_t *value, size_t array_len)
339 {
340 const data_set_t *ds;
342 if ((NULL == name) || (NULL == array) || (NULL == value) || (array_len == 0))
343 return 0;
345 ds = plugin_get_ds (name);
346 if (NULL == ds) {
347 log_err ("av2value: Unknown dataset \"%s\"", name);
348 return 0;
349 }
351 if (array_len < ds->ds_num) {
352 log_warn ("av2value: array does not contain enough elements for type \"%s\": got %zu, want %zu",
353 name, array_len, ds->ds_num);
354 return 0;
355 } else if (array_len > ds->ds_num) {
356 log_warn ("av2value: array contains excess elements for type \"%s\": got %zu, want %zu",
357 name, array_len, ds->ds_num);
358 }
360 for (size_t i = 0; i < ds->ds_num; ++i) {
361 SV **tmp = av_fetch (array, i, 0);
363 if (NULL != tmp) {
364 if (DS_TYPE_COUNTER == ds->ds[i].type)
365 value[i].counter = SvIV (*tmp);
366 else if (DS_TYPE_GAUGE == ds->ds[i].type)
367 value[i].gauge = SvNV (*tmp);
368 else if (DS_TYPE_DERIVE == ds->ds[i].type)
369 value[i].derive = SvIV (*tmp);
370 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
371 value[i].absolute = SvIV (*tmp);
372 }
373 else {
374 return 0;
375 }
376 }
378 return ds->ds_num;
379 } /* static size_t av2value (char *, AV *, value_t *, size_t) */
381 /*
382 * value list:
383 * {
384 * values => [ @values ],
385 * time => $time,
386 * host => $host,
387 * plugin => $plugin,
388 * plugin_instance => $pinstance,
389 * type_instance => $tinstance,
390 * }
391 */
392 static int hv2value_list (pTHX_ HV *hash, value_list_t *vl)
393 {
394 SV **tmp;
396 if ((NULL == hash) || (NULL == vl))
397 return -1;
399 if (NULL == (tmp = hv_fetch (hash, "type", 4, 0))) {
400 log_err ("hv2value_list: No type given.");
401 return -1;
402 }
404 sstrncpy (vl->type, SvPV_nolen (*tmp), sizeof (vl->type));
406 if ((NULL == (tmp = hv_fetch (hash, "values", 6, 0)))
407 || (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp)))))) {
408 log_err ("hv2value_list: No valid values given.");
409 return -1;
410 }
412 {
413 AV *array = (AV *)SvRV (*tmp);
414 /* av_len returns the highest index, not the actual length. */
415 size_t array_len = (size_t) (av_len (array) + 1);
416 if (array_len == 0)
417 return -1;
419 vl->values = calloc (array_len, sizeof (*vl->values));
420 vl->values_len = av2value (aTHX_ vl->type, (AV *)SvRV (*tmp), vl->values, array_len);
421 if (vl->values_len == 0) {
422 sfree (vl->values);
423 return -1;
424 }
425 }
427 if (NULL != (tmp = hv_fetch (hash, "time", 4, 0)))
428 {
429 double t = SvNV (*tmp);
430 vl->time = DOUBLE_TO_CDTIME_T (t);
431 }
433 if (NULL != (tmp = hv_fetch (hash, "interval", 8, 0)))
434 {
435 double t = SvNV (*tmp);
436 vl->interval = DOUBLE_TO_CDTIME_T (t);
437 }
439 if (NULL != (tmp = hv_fetch (hash, "host", 4, 0)))
440 sstrncpy (vl->host, SvPV_nolen (*tmp), sizeof (vl->host));
441 else
442 sstrncpy (vl->host, hostname_g, sizeof (vl->host));
444 if (NULL != (tmp = hv_fetch (hash, "plugin", 6, 0)))
445 sstrncpy (vl->plugin, SvPV_nolen (*tmp), sizeof (vl->plugin));
447 if (NULL != (tmp = hv_fetch (hash, "plugin_instance", 15, 0)))
448 sstrncpy (vl->plugin_instance, SvPV_nolen (*tmp),
449 sizeof (vl->plugin_instance));
451 if (NULL != (tmp = hv_fetch (hash, "type_instance", 13, 0)))
452 sstrncpy (vl->type_instance, SvPV_nolen (*tmp),
453 sizeof (vl->type_instance));
454 return 0;
455 } /* static int hv2value_list (pTHX_ HV *, value_list_t *) */
457 static int av2data_set (pTHX_ AV *array, char *name, data_set_t *ds)
458 {
459 int len;
461 if ((NULL == array) || (NULL == name) || (NULL == ds))
462 return -1;
464 len = av_len (array);
466 if (-1 == len) {
467 log_err ("av2data_set: Invalid data set.");
468 return -1;
469 }
471 ds->ds = smalloc ((len + 1) * sizeof (*ds->ds));
472 ds->ds_num = len + 1;
474 for (int i = 0; i <= len; ++i) {
475 SV **elem = av_fetch (array, i, 0);
477 if (NULL == elem) {
478 log_err ("av2data_set: Failed to fetch data source %i.", i);
479 return -1;
480 }
482 if (! (SvROK (*elem) && (SVt_PVHV == SvTYPE (SvRV (*elem))))) {
483 log_err ("av2data_set: Invalid data source.");
484 return -1;
485 }
487 if (-1 == hv2data_source (aTHX_ (HV *)SvRV (*elem), &ds->ds[i]))
488 return -1;
490 log_debug ("av2data_set: "
491 "DS.name = \"%s\", DS.type = %i, DS.min = %f, DS.max = %f",
492 ds->ds[i].name, ds->ds[i].type, ds->ds[i].min, ds->ds[i].max);
493 }
495 sstrncpy (ds->type, name, sizeof (ds->type));
496 return 0;
497 } /* static int av2data_set (pTHX_ AV *, data_set_t *) */
499 /*
500 * notification:
501 * {
502 * severity => $severity,
503 * time => $time,
504 * message => $msg,
505 * host => $host,
506 * plugin => $plugin,
507 * type => $type,
508 * plugin_instance => $instance,
509 * type_instance => $type_instance,
510 * meta => [ { name => <name>, value => <value> }, ... ]
511 * }
512 */
513 static int av2notification_meta (pTHX_ AV *array, notification_meta_t **meta)
514 {
515 notification_meta_t **m = meta;
517 int len = av_len (array);
519 for (int i = 0; i <= len; ++i) {
520 SV **tmp = av_fetch (array, i, 0);
521 HV *hash;
523 if (NULL == tmp)
524 return -1;
526 if (! (SvROK (*tmp) && (SVt_PVHV == SvTYPE (SvRV (*tmp))))) {
527 log_warn ("av2notification_meta: Skipping invalid "
528 "meta information.");
529 continue;
530 }
532 hash = (HV *)SvRV (*tmp);
534 *m = smalloc (sizeof (**m));
536 if (NULL == (tmp = hv_fetch (hash, "name", 4, 0))) {
537 log_warn ("av2notification_meta: Skipping invalid "
538 "meta information.");
539 free (*m);
540 continue;
541 }
542 sstrncpy ((*m)->name, SvPV_nolen (*tmp), sizeof ((*m)->name));
544 if (NULL == (tmp = hv_fetch (hash, "value", 5, 0))) {
545 log_warn ("av2notification_meta: Skipping invalid "
546 "meta information.");
547 free (*m);
548 continue;
549 }
551 if (SvNOK (*tmp)) {
552 (*m)->nm_value.nm_double = SvNVX (*tmp);
553 (*m)->type = NM_TYPE_DOUBLE;
554 }
555 else if (SvUOK (*tmp)) {
556 (*m)->nm_value.nm_unsigned_int = SvUVX (*tmp);
557 (*m)->type = NM_TYPE_UNSIGNED_INT;
558 }
559 else if (SvIOK (*tmp)) {
560 (*m)->nm_value.nm_signed_int = SvIVX (*tmp);
561 (*m)->type = NM_TYPE_SIGNED_INT;
562 }
563 else {
564 (*m)->nm_value.nm_string = sstrdup (SvPV_nolen (*tmp));
565 (*m)->type = NM_TYPE_STRING;
566 }
568 (*m)->next = NULL;
569 m = &((*m)->next);
570 }
571 return 0;
572 } /* static int av2notification_meta (AV *, notification_meta_t *) */
574 static int hv2notification (pTHX_ HV *hash, notification_t *n)
575 {
576 SV **tmp = NULL;
578 if ((NULL == hash) || (NULL == n))
579 return -1;
581 if (NULL != (tmp = hv_fetch (hash, "severity", 8, 0)))
582 n->severity = SvIV (*tmp);
583 else
584 n->severity = NOTIF_FAILURE;
586 if (NULL != (tmp = hv_fetch (hash, "time", 4, 0)))
587 {
588 double t = SvNV (*tmp);
589 n->time = DOUBLE_TO_CDTIME_T (t);
590 }
591 else
592 n->time = cdtime ();
594 if (NULL != (tmp = hv_fetch (hash, "message", 7, 0)))
595 sstrncpy (n->message, SvPV_nolen (*tmp), sizeof (n->message));
597 if (NULL != (tmp = hv_fetch (hash, "host", 4, 0)))
598 sstrncpy (n->host, SvPV_nolen (*tmp), sizeof (n->host));
599 else
600 sstrncpy (n->host, hostname_g, sizeof (n->host));
602 if (NULL != (tmp = hv_fetch (hash, "plugin", 6, 0)))
603 sstrncpy (n->plugin, SvPV_nolen (*tmp), sizeof (n->plugin));
605 if (NULL != (tmp = hv_fetch (hash, "plugin_instance", 15, 0)))
606 sstrncpy (n->plugin_instance, SvPV_nolen (*tmp),
607 sizeof (n->plugin_instance));
609 if (NULL != (tmp = hv_fetch (hash, "type", 4, 0)))
610 sstrncpy (n->type, SvPV_nolen (*tmp), sizeof (n->type));
612 if (NULL != (tmp = hv_fetch (hash, "type_instance", 13, 0)))
613 sstrncpy (n->type_instance, SvPV_nolen (*tmp),
614 sizeof (n->type_instance));
616 n->meta = NULL;
617 while (NULL != (tmp = hv_fetch (hash, "meta", 4, 0))) {
618 if (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp))))) {
619 log_warn ("hv2notification: Ignoring invalid meta information.");
620 break;
621 }
623 if (0 != av2notification_meta (aTHX_ (AV *)SvRV (*tmp), &n->meta)) {
624 plugin_notification_meta_free (n->meta);
625 n->meta = NULL;
626 return -1;
627 }
628 break;
629 }
630 return 0;
631 } /* static int hv2notification (pTHX_ HV *, notification_t *) */
633 static int data_set2av (pTHX_ data_set_t *ds, AV *array)
634 {
635 if ((NULL == ds) || (NULL == array))
636 return -1;
638 av_extend (array, ds->ds_num);
640 for (size_t i = 0; i < ds->ds_num; ++i) {
641 HV *source = newHV ();
643 if (NULL == hv_store (source, "name", 4,
644 newSVpv (ds->ds[i].name, 0), 0))
645 return -1;
647 if (NULL == hv_store (source, "type", 4, newSViv (ds->ds[i].type), 0))
648 return -1;
650 if (! isnan (ds->ds[i].min))
651 if (NULL == hv_store (source, "min", 3,
652 newSVnv (ds->ds[i].min), 0))
653 return -1;
655 if (! isnan (ds->ds[i].max))
656 if (NULL == hv_store (source, "max", 3,
657 newSVnv (ds->ds[i].max), 0))
658 return -1;
660 if (NULL == av_store (array, i, newRV_noinc ((SV *)source)))
661 return -1;
662 }
663 return 0;
664 } /* static int data_set2av (data_set_t *, AV *) */
666 static int value_list2hv (pTHX_ value_list_t *vl, data_set_t *ds, HV *hash)
667 {
668 AV *values = NULL;
669 size_t i;
671 if ((NULL == vl) || (NULL == ds) || (NULL == hash))
672 return -1;
674 values = newAV ();
675 /* av_extend takes the last *index* to which the array should be extended. */
676 av_extend (values, vl->values_len - 1);
678 assert (ds->ds_num == vl->values_len);
679 for (i = 0; i < vl->values_len; ++i) {
680 SV *val = NULL;
682 if (DS_TYPE_COUNTER == ds->ds[i].type)
683 val = newSViv (vl->values[i].counter);
684 else if (DS_TYPE_GAUGE == ds->ds[i].type)
685 val = newSVnv (vl->values[i].gauge);
686 else if (DS_TYPE_DERIVE == ds->ds[i].type)
687 val = newSViv (vl->values[i].derive);
688 else if (DS_TYPE_ABSOLUTE == ds->ds[i].type)
689 val = newSViv (vl->values[i].absolute);
691 if (NULL == av_store (values, i, val)) {
692 av_undef (values);
693 return -1;
694 }
695 }
697 if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0))
698 return -1;
700 if (0 != vl->time)
701 {
702 double t = CDTIME_T_TO_DOUBLE (vl->time);
703 if (NULL == hv_store (hash, "time", 4, newSVnv (t), 0))
704 return -1;
705 }
707 {
708 double t = CDTIME_T_TO_DOUBLE (vl->interval);
709 if (NULL == hv_store (hash, "interval", 8, newSVnv (t), 0))
710 return -1;
711 }
713 if ('\0' != vl->host[0])
714 if (NULL == hv_store (hash, "host", 4, newSVpv (vl->host, 0), 0))
715 return -1;
717 if ('\0' != vl->plugin[0])
718 if (NULL == hv_store (hash, "plugin", 6, newSVpv (vl->plugin, 0), 0))
719 return -1;
721 if ('\0' != vl->plugin_instance[0])
722 if (NULL == hv_store (hash, "plugin_instance", 15,
723 newSVpv (vl->plugin_instance, 0), 0))
724 return -1;
726 if ('\0' != vl->type[0])
727 if (NULL == hv_store (hash, "type", 4, newSVpv (vl->type, 0), 0))
728 return -1;
730 if ('\0' != vl->type_instance[0])
731 if (NULL == hv_store (hash, "type_instance", 13,
732 newSVpv (vl->type_instance, 0), 0))
733 return -1;
734 return 0;
735 } /* static int value2av (value_list_t *, data_set_t *, HV *) */
737 static int notification_meta2av (pTHX_ notification_meta_t *meta, AV *array)
738 {
739 int meta_num = 0;
741 while (meta) {
742 ++meta_num;
743 meta = meta->next;
744 }
746 av_extend (array, meta_num);
748 for (int i = 0; NULL != meta; meta = meta->next, ++i) {
749 HV *m = newHV ();
750 SV *value;
752 if (NULL == hv_store (m, "name", 4, newSVpv (meta->name, 0), 0))
753 return -1;
755 if (NM_TYPE_STRING == meta->type)
756 value = newSVpv (meta->nm_value.nm_string, 0);
757 else if (NM_TYPE_SIGNED_INT == meta->type)
758 value = newSViv (meta->nm_value.nm_signed_int);
759 else if (NM_TYPE_UNSIGNED_INT == meta->type)
760 value = newSVuv (meta->nm_value.nm_unsigned_int);
761 else if (NM_TYPE_DOUBLE == meta->type)
762 value = newSVnv (meta->nm_value.nm_double);
763 else if (NM_TYPE_BOOLEAN == meta->type)
764 value = meta->nm_value.nm_boolean ? &PL_sv_yes : &PL_sv_no;
765 else
766 return -1;
768 if (NULL == hv_store (m, "value", 5, value, 0)) {
769 sv_free (value);
770 return -1;
771 }
773 if (NULL == av_store (array, i, newRV_noinc ((SV *)m))) {
774 hv_clear (m);
775 hv_undef (m);
776 return -1;
777 }
778 }
779 return 0;
780 } /* static int notification_meta2av (notification_meta_t *, AV *) */
782 static int notification2hv (pTHX_ notification_t *n, HV *hash)
783 {
784 if (NULL == hv_store (hash, "severity", 8, newSViv (n->severity), 0))
785 return -1;
787 if (0 != n->time)
788 {
789 double t = CDTIME_T_TO_DOUBLE (n->time);
790 if (NULL == hv_store (hash, "time", 4, newSVnv (t), 0))
791 return -1;
792 }
794 if ('\0' != *n->message)
795 if (NULL == hv_store (hash, "message", 7, newSVpv (n->message, 0), 0))
796 return -1;
798 if ('\0' != *n->host)
799 if (NULL == hv_store (hash, "host", 4, newSVpv (n->host, 0), 0))
800 return -1;
802 if ('\0' != *n->plugin)
803 if (NULL == hv_store (hash, "plugin", 6, newSVpv (n->plugin, 0), 0))
804 return -1;
806 if ('\0' != *n->plugin_instance)
807 if (NULL == hv_store (hash, "plugin_instance", 15,
808 newSVpv (n->plugin_instance, 0), 0))
809 return -1;
811 if ('\0' != *n->type)
812 if (NULL == hv_store (hash, "type", 4, newSVpv (n->type, 0), 0))
813 return -1;
815 if ('\0' != *n->type_instance)
816 if (NULL == hv_store (hash, "type_instance", 13,
817 newSVpv (n->type_instance, 0), 0))
818 return -1;
820 if (NULL != n->meta) {
821 AV *meta = newAV ();
822 if ((0 != notification_meta2av (aTHX_ n->meta, meta))
823 || (NULL == hv_store (hash, "meta", 4,
824 newRV_noinc ((SV *)meta), 0))) {
825 av_clear (meta);
826 av_undef (meta);
827 return -1;
828 }
829 }
830 return 0;
831 } /* static int notification2hv (notification_t *, HV *) */
833 static int oconfig_item2hv (pTHX_ oconfig_item_t *ci, HV *hash)
834 {
835 AV *values;
836 AV *children;
838 if (NULL == hv_store (hash, "key", 3, newSVpv (ci->key, 0), 0))
839 return -1;
841 values = newAV ();
842 if (0 < ci->values_num)
843 av_extend (values, ci->values_num);
845 if (NULL == hv_store (hash, "values", 6, newRV_noinc ((SV *)values), 0)) {
846 av_clear (values);
847 av_undef (values);
848 return -1;
849 }
851 for (int i = 0; i < ci->values_num; ++i) {
852 SV *value;
854 switch (ci->values[i].type) {
855 case OCONFIG_TYPE_STRING:
856 value = newSVpv (ci->values[i].value.string, 0);
857 break;
858 case OCONFIG_TYPE_NUMBER:
859 value = newSVnv ((NV)ci->values[i].value.number);
860 break;
861 case OCONFIG_TYPE_BOOLEAN:
862 value = ci->values[i].value.boolean ? &PL_sv_yes : &PL_sv_no;
863 break;
864 default:
865 log_err ("oconfig_item2hv: Invalid value type %i.",
866 ci->values[i].type);
867 value = &PL_sv_undef;
868 }
870 if (NULL == av_store (values, i, value)) {
871 sv_free (value);
872 return -1;
873 }
874 }
876 /* ignoring 'parent' member which is uninteresting in this case */
878 children = newAV ();
879 if (0 < ci->children_num)
880 av_extend (children, ci->children_num);
882 if (NULL == hv_store (hash, "children", 8, newRV_noinc ((SV *)children), 0)) {
883 av_clear (children);
884 av_undef (children);
885 return -1;
886 }
888 for (int i = 0; i < ci->children_num; ++i) {
889 HV *child = newHV ();
891 if (0 != oconfig_item2hv (aTHX_ ci->children + i, child)) {
892 hv_clear (child);
893 hv_undef (child);
894 return -1;
895 }
897 if (NULL == av_store (children, i, newRV_noinc ((SV *)child))) {
898 hv_clear (child);
899 hv_undef (child);
900 return -1;
901 }
902 }
903 return 0;
904 } /* static int oconfig_item2hv (pTHX_ oconfig_item_t *, HV *) */
906 /*
907 * Internal functions.
908 */
910 static char *get_module_name (char *buf, size_t buf_len, const char *module) {
911 int status = 0;
912 if (base_name[0] == '\0')
913 status = ssnprintf (buf, buf_len, "%s", module);
914 else
915 status = ssnprintf (buf, buf_len, "%s::%s", base_name, module);
916 if ((status < 0) || ((unsigned int)status >= buf_len))
917 return (NULL);
918 return (buf);
919 } /* char *get_module_name */
921 /*
922 * Add a plugin's data set definition.
923 */
924 static int pplugin_register_data_set (pTHX_ char *name, AV *dataset)
925 {
926 int ret = 0;
928 data_set_t ds;
930 if ((NULL == name) || (NULL == dataset))
931 return -1;
933 if (0 != av2data_set (aTHX_ dataset, name, &ds))
934 return -1;
936 ret = plugin_register_data_set (&ds);
938 free (ds.ds);
939 return ret;
940 } /* static int pplugin_register_data_set (char *, SV *) */
942 /*
943 * Remove a plugin's data set definition.
944 */
945 static int pplugin_unregister_data_set (char *name)
946 {
947 if (NULL == name)
948 return 0;
949 return plugin_unregister_data_set (name);
950 } /* static int pplugin_unregister_data_set (char *) */
952 /*
953 * Submit the values to the write functions.
954 */
955 static int pplugin_dispatch_values (pTHX_ HV *values)
956 {
957 value_list_t vl = VALUE_LIST_INIT;
959 int ret = 0;
961 if (NULL == values)
962 return -1;
964 if (0 != hv2value_list (aTHX_ values, &vl))
965 return -1;
967 ret = plugin_dispatch_values (&vl);
969 sfree (vl.values);
970 return ret;
971 } /* static int pplugin_dispatch_values (char *, HV *) */
973 /*
974 * Submit the values to a single write function.
975 */
976 static int pplugin_write (pTHX_ const char *plugin, AV *data_set, HV *values)
977 {
978 data_set_t ds;
979 value_list_t vl = VALUE_LIST_INIT;
981 int ret;
983 if (NULL == values)
984 return -1;
986 if (0 != hv2value_list (aTHX_ values, &vl))
987 return -1;
989 if ((NULL != data_set)
990 && (0 != av2data_set (aTHX_ data_set, vl.type, &ds)))
991 return -1;
993 ret = plugin_write (plugin, NULL == data_set ? NULL : &ds, &vl);
994 if (0 != ret)
995 log_warn ("Dispatching value to plugin \"%s\" failed with status %i.",
996 NULL == plugin ? "<any>" : plugin, ret);
998 if (NULL != data_set)
999 sfree (ds.ds);
1000 sfree (vl.values);
1001 return ret;
1002 } /* static int pplugin_write (const char *plugin, HV *, HV *) */
1004 /*
1005 * Dispatch a notification.
1006 */
1007 static int pplugin_dispatch_notification (pTHX_ HV *notif)
1008 {
1009 notification_t n = { 0 };
1011 int ret;
1013 if (NULL == notif)
1014 return -1;
1016 if (0 != hv2notification (aTHX_ notif, &n))
1017 return -1;
1019 ret = plugin_dispatch_notification (&n);
1020 plugin_notification_meta_free (n.meta);
1021 return ret;
1022 } /* static int pplugin_dispatch_notification (HV *) */
1024 /*
1025 * Call perl sub with thread locking flags handled.
1026 */
1027 static int call_pv_locked (pTHX_ const char* sub_name)
1028 {
1029 _Bool old_running;
1030 int ret;
1032 c_ithread_t *t = (c_ithread_t *)pthread_getspecific(perl_thr_key);
1033 if (t == NULL) /* thread destroyed */
1034 return 0;
1036 old_running = t->running;
1037 t->running = 1;
1039 if (t->shutdown) {
1040 t->running = old_running;
1041 return 0;
1042 }
1044 ret = call_pv (sub_name, G_SCALAR|G_EVAL);
1046 t->running = old_running;
1047 return ret;
1048 } /* static int call_pv_locked (pTHX, *sub_name) */
1050 /*
1051 * Call all working functions of the given type.
1052 */
1053 static int pplugin_call (pTHX_ int type, ...)
1054 {
1055 int retvals = 0;
1057 va_list ap;
1058 int ret = 0;
1059 char *subname;
1061 dSP;
1063 if ((type < 0) || (type >= PLUGIN_TYPES))
1064 return -1;
1066 va_start (ap, type);
1068 ENTER;
1069 SAVETMPS;
1071 PUSHMARK (SP);
1073 if (PLUGIN_READ == type) {
1074 subname = va_arg(ap, char *);
1075 }
1076 else if (PLUGIN_WRITE == type) {
1077 data_set_t *ds;
1078 value_list_t *vl;
1080 AV *pds = newAV ();
1081 HV *pvl = newHV ();
1083 subname = va_arg(ap, char *);
1084 /*
1085 * $_[0] = $plugin_type;
1086 *
1087 * $_[1] =
1088 * [
1089 * {
1090 * name => $ds_name,
1091 * type => $ds_type,
1092 * min => $ds_min,
1093 * max => $ds_max
1094 * },
1095 * ...
1096 * ];
1097 *
1098 * $_[2] =
1099 * {
1100 * values => [ $v1, ... ],
1101 * time => $time,
1102 * host => $hostname,
1103 * plugin => $plugin,
1104 * type => $type,
1105 * plugin_instance => $instance,
1106 * type_instance => $type_instance
1107 * };
1108 */
1109 ds = va_arg (ap, data_set_t *);
1110 vl = va_arg (ap, value_list_t *);
1112 if (-1 == data_set2av (aTHX_ ds, pds)) {
1113 av_clear (pds);
1114 av_undef (pds);
1115 pds = (AV *)&PL_sv_undef;
1116 ret = -1;
1117 }
1119 if (-1 == value_list2hv (aTHX_ vl, ds, pvl)) {
1120 hv_clear (pvl);
1121 hv_undef (pvl);
1122 pvl = (HV *)&PL_sv_undef;
1123 ret = -1;
1124 }
1126 XPUSHs (sv_2mortal (newSVpv (ds->type, 0)));
1127 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1128 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1129 }
1130 else if (PLUGIN_LOG == type) {
1131 subname = va_arg(ap, char *);
1132 /*
1133 * $_[0] = $level;
1134 *
1135 * $_[1] = $message;
1136 */
1137 XPUSHs (sv_2mortal (newSViv (va_arg (ap, int))));
1138 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1139 }
1140 else if (PLUGIN_NOTIF == type) {
1141 notification_t *n;
1142 HV *notif = newHV ();
1144 subname = va_arg(ap, char *);
1145 /*
1146 * $_[0] =
1147 * {
1148 * severity => $severity,
1149 * time => $time,
1150 * message => $msg,
1151 * host => $host,
1152 * plugin => $plugin,
1153 * type => $type,
1154 * plugin_instance => $instance,
1155 * type_instance => $type_instance
1156 * };
1157 */
1158 n = va_arg (ap, notification_t *);
1160 if (-1 == notification2hv (aTHX_ n, notif)) {
1161 hv_clear (notif);
1162 hv_undef (notif);
1163 notif = (HV *)&PL_sv_undef;
1164 ret = -1;
1165 }
1167 XPUSHs (sv_2mortal (newRV_noinc ((SV *)notif)));
1168 }
1169 else if (PLUGIN_FLUSH == type) {
1170 cdtime_t timeout;
1171 subname = va_arg(ap, char *);
1172 /*
1173 * $_[0] = $timeout;
1174 * $_[1] = $identifier;
1175 */
1176 timeout = va_arg (ap, cdtime_t);
1178 XPUSHs (sv_2mortal (newSVnv (CDTIME_T_TO_DOUBLE (timeout))));
1179 XPUSHs (sv_2mortal (newSVpv (va_arg (ap, char *), 0)));
1180 }
1181 else if (PLUGIN_INIT == type) {
1182 subname = "Collectd::plugin_call_all";
1183 XPUSHs (sv_2mortal (newSViv ((IV)type)));
1184 }
1185 else if (PLUGIN_SHUTDOWN == type) {
1186 subname = "Collectd::plugin_call_all";
1187 XPUSHs (sv_2mortal (newSViv ((IV)type)));
1188 }
1189 else { /* Unknown type. Run 'plugin_call_all' and make compiler happy */
1190 subname = "Collectd::plugin_call_all";
1191 XPUSHs (sv_2mortal (newSViv ((IV)type)));
1192 }
1194 PUTBACK;
1196 retvals = call_pv_locked (aTHX_ subname);
1198 SPAGAIN;
1199 if (SvTRUE(ERRSV)) {
1200 if (PLUGIN_LOG != type)
1201 ERROR ("perl: %s error: %s", subname, SvPV_nolen(ERRSV));
1202 ret = -1;
1203 }
1204 else if (0 < retvals) {
1205 SV *tmp = POPs;
1206 if (! SvTRUE (tmp))
1207 ret = -1;
1208 }
1210 PUTBACK;
1211 FREETMPS;
1212 LEAVE;
1214 va_end (ap);
1215 return ret;
1216 } /* static int pplugin_call (int, ...) */
1218 /*
1219 * collectd's Perl interpreter based thread implementation.
1220 *
1221 * This has been inspired by Perl's ithreads introduced in version 5.6.0.
1222 */
1224 /* must be called with perl_threads->mutex locked */
1225 static void c_ithread_destroy (c_ithread_t *ithread)
1226 {
1227 dTHXa (ithread->interp);
1229 assert (NULL != perl_threads);
1231 PERL_SET_CONTEXT (aTHX);
1232 /* Mark as running to avoid deadlock:
1233 c_ithread_destroy -> log_debug -> perl_log()
1234 */
1235 ithread->running = 1;
1236 log_debug ("Shutting down Perl interpreter %p...", aTHX);
1238 #if COLLECT_DEBUG
1239 sv_report_used ();
1241 --perl_threads->number_of_threads;
1242 #endif /* COLLECT_DEBUG */
1244 perl_destruct (aTHX);
1245 perl_free (aTHX);
1247 if (NULL == ithread->prev)
1248 perl_threads->head = ithread->next;
1249 else
1250 ithread->prev->next = ithread->next;
1252 if (NULL == ithread->next)
1253 perl_threads->tail = ithread->prev;
1254 else
1255 ithread->next->prev = ithread->prev;
1257 sfree (ithread);
1258 return;
1259 } /* static void c_ithread_destroy (c_ithread_t *) */
1261 static void c_ithread_destructor (void *arg)
1262 {
1263 c_ithread_t *ithread = (c_ithread_t *)arg;
1264 c_ithread_t *t = NULL;
1266 if (NULL == perl_threads)
1267 return;
1269 pthread_mutex_lock (&perl_threads->mutex);
1271 for (t = perl_threads->head; NULL != t; t = t->next)
1272 if (t == ithread)
1273 break;
1275 /* the ithread no longer exists */
1276 if (NULL == t)
1277 {
1278 pthread_mutex_unlock (&perl_threads->mutex);
1279 return;
1280 }
1282 c_ithread_destroy (ithread);
1284 pthread_mutex_unlock (&perl_threads->mutex);
1285 return;
1286 } /* static void c_ithread_destructor (void *) */
1288 /* must be called with perl_threads->mutex locked */
1289 static c_ithread_t *c_ithread_create (PerlInterpreter *base)
1290 {
1291 c_ithread_t *t = NULL;
1292 dTHXa (NULL);
1294 assert (NULL != perl_threads);
1296 t = smalloc (sizeof (*t));
1297 memset (t, 0, sizeof (c_ithread_t));
1299 t->interp = (NULL == base)
1300 ? NULL
1301 : perl_clone (base, CLONEf_KEEP_PTR_TABLE);
1303 aTHX = t->interp;
1305 if ((NULL != base) && (NULL != PL_endav)) {
1306 av_clear (PL_endav);
1307 av_undef (PL_endav);
1308 PL_endav = Nullav;
1309 }
1311 #if COLLECT_DEBUG
1312 ++perl_threads->number_of_threads;
1313 #endif /* COLLECT_DEBUG */
1315 t->next = NULL;
1317 if (NULL == perl_threads->tail) {
1318 perl_threads->head = t;
1319 t->prev = NULL;
1320 }
1321 else {
1322 perl_threads->tail->next = t;
1323 t->prev = perl_threads->tail;
1324 }
1326 t->pthread = pthread_self();
1327 t->running = 0;
1328 t->shutdown = 0;
1329 perl_threads->tail = t;
1331 pthread_setspecific (perl_thr_key, (const void *)t);
1332 return t;
1333 } /* static c_ithread_t *c_ithread_create (PerlInterpreter *) */
1335 /*
1336 * Filter chains implementation.
1337 */
1339 static int fc_call (pTHX_ int type, int cb_type, pfc_user_data_t *data, ...)
1340 {
1341 int retvals = 0;
1343 va_list ap;
1344 int ret = 0;
1346 notification_meta_t **meta = NULL;
1347 AV *pmeta = NULL;
1349 dSP;
1351 if ((type < 0) || (type >= FC_TYPES))
1352 return -1;
1354 if ((cb_type < 0) || (cb_type >= FC_CB_TYPES))
1355 return -1;
1357 va_start (ap, data);
1359 ENTER;
1360 SAVETMPS;
1362 PUSHMARK (SP);
1364 XPUSHs (sv_2mortal (newSViv ((IV)type)));
1365 XPUSHs (sv_2mortal (newSVpv (data->name, 0)));
1366 XPUSHs (sv_2mortal (newSViv ((IV)cb_type)));
1368 if (FC_CB_CREATE == cb_type) {
1369 /*
1370 * $_[0] = $ci;
1371 * $_[1] = $user_data;
1372 */
1373 oconfig_item_t *ci;
1374 HV *config = newHV ();
1376 ci = va_arg (ap, oconfig_item_t *);
1378 if (0 != oconfig_item2hv (aTHX_ ci, config)) {
1379 hv_clear (config);
1380 hv_undef (config);
1381 config = (HV *)&PL_sv_undef;
1382 ret = -1;
1383 }
1385 XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
1386 }
1387 else if (FC_CB_DESTROY == cb_type) {
1388 /*
1389 * $_[1] = $user_data;
1390 */
1392 /* nothing to be done - the user data pointer
1393 * is pushed onto the stack later */
1394 }
1395 else if (FC_CB_EXEC == cb_type) {
1396 /*
1397 * $_[0] = $ds;
1398 * $_[1] = $vl;
1399 * $_[2] = $meta;
1400 * $_[3] = $user_data;
1401 */
1402 data_set_t *ds;
1403 value_list_t *vl;
1405 AV *pds = newAV ();
1406 HV *pvl = newHV ();
1408 ds = va_arg (ap, data_set_t *);
1409 vl = va_arg (ap, value_list_t *);
1410 meta = va_arg (ap, notification_meta_t **);
1412 if (0 != data_set2av (aTHX_ ds, pds)) {
1413 av_clear (pds);
1414 av_undef (pds);
1415 pds = (AV *)&PL_sv_undef;
1416 ret = -1;
1417 }
1419 if (0 != value_list2hv (aTHX_ vl, ds, pvl)) {
1420 hv_clear (pvl);
1421 hv_undef (pvl);
1422 pvl = (HV *)&PL_sv_undef;
1423 ret = -1;
1424 }
1426 if (NULL != meta) {
1427 pmeta = newAV ();
1429 if (0 != notification_meta2av (aTHX_ *meta, pmeta)) {
1430 av_clear (pmeta);
1431 av_undef (pmeta);
1432 pmeta = (AV *)&PL_sv_undef;
1433 ret = -1;
1434 }
1435 }
1436 else {
1437 pmeta = (AV *)&PL_sv_undef;
1438 }
1440 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pds)));
1441 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pvl)));
1442 XPUSHs (sv_2mortal (newRV_noinc ((SV *)pmeta)));
1443 }
1445 XPUSHs (sv_2mortal (newRV_inc (data->user_data)));
1447 PUTBACK;
1449 retvals = call_pv_locked (aTHX_ "Collectd::fc_call");
1451 if ((FC_CB_EXEC == cb_type) && (meta != NULL)) {
1452 assert (pmeta != NULL);
1454 plugin_notification_meta_free (*meta);
1455 av2notification_meta (aTHX_ pmeta, meta);
1456 }
1458 SPAGAIN;
1459 if (SvTRUE(ERRSV)) {
1460 ERROR ("perl: Collectd::fc_call error: %s", SvPV_nolen(ERRSV));
1461 ret = -1;
1462 }
1463 else if (0 < retvals) {
1464 SV *tmp = POPs;
1466 /* the exec callbacks return a status, while
1467 * the others return a boolean value */
1468 if (FC_CB_EXEC == cb_type)
1469 ret = SvIV (tmp);
1470 else if (! SvTRUE (tmp))
1471 ret = -1;
1472 }
1474 PUTBACK;
1475 FREETMPS;
1476 LEAVE;
1478 va_end (ap);
1479 return ret;
1480 } /* static int fc_call (int, int, pfc_user_data_t *, ...) */
1482 static int fc_create (int type, const oconfig_item_t *ci, void **user_data)
1483 {
1484 pfc_user_data_t *data;
1486 int ret = 0;
1488 dTHX;
1490 if (NULL == perl_threads)
1491 return 0;
1493 if (NULL == aTHX) {
1494 c_ithread_t *t = NULL;
1496 pthread_mutex_lock (&perl_threads->mutex);
1497 t = c_ithread_create (perl_threads->head->interp);
1498 pthread_mutex_unlock (&perl_threads->mutex);
1500 aTHX = t->interp;
1501 }
1503 log_debug ("fc_create: c_ithread: interp = %p (active threads: %i)",
1504 aTHX, perl_threads->number_of_threads);
1506 if ((1 != ci->values_num)
1507 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
1508 log_warn ("A \"%s\" block expects a single string argument.",
1509 (FC_MATCH == type) ? "Match" : "Target");
1510 return -1;
1511 }
1513 data = smalloc (sizeof (*data));
1514 data->name = sstrdup (ci->values[0].value.string);
1515 data->user_data = newSV (0);
1517 ret = fc_call (aTHX_ type, FC_CB_CREATE, data, ci);
1519 if (0 != ret)
1520 PFC_USER_DATA_FREE (data);
1521 else
1522 *user_data = data;
1523 return ret;
1524 } /* static int fc_create (int, const oconfig_item_t *, void **) */
1526 static int fc_destroy (int type, void **user_data)
1527 {
1528 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1530 int ret = 0;
1532 dTHX;
1534 if ((NULL == perl_threads) || (NULL == data))
1535 return 0;
1537 if (NULL == aTHX) {
1538 c_ithread_t *t = NULL;
1540 pthread_mutex_lock (&perl_threads->mutex);
1541 t = c_ithread_create (perl_threads->head->interp);
1542 pthread_mutex_unlock (&perl_threads->mutex);
1544 aTHX = t->interp;
1545 }
1547 log_debug ("fc_destroy: c_ithread: interp = %p (active threads: %i)",
1548 aTHX, perl_threads->number_of_threads);
1550 ret = fc_call (aTHX_ type, FC_CB_DESTROY, data);
1552 PFC_USER_DATA_FREE (data);
1553 *user_data = NULL;
1554 return ret;
1555 } /* static int fc_destroy (int, void **) */
1557 static int fc_exec (int type, const data_set_t *ds, const value_list_t *vl,
1558 notification_meta_t **meta, void **user_data)
1559 {
1560 pfc_user_data_t *data = *(pfc_user_data_t **)user_data;
1562 dTHX;
1564 if (NULL == perl_threads)
1565 return 0;
1567 assert (NULL != data);
1569 if (NULL == aTHX) {
1570 c_ithread_t *t = NULL;
1572 pthread_mutex_lock (&perl_threads->mutex);
1573 t = c_ithread_create (perl_threads->head->interp);
1574 pthread_mutex_unlock (&perl_threads->mutex);
1576 aTHX = t->interp;
1577 }
1579 log_debug ("fc_exec: c_ithread: interp = %p (active threads: %i)",
1580 aTHX, perl_threads->number_of_threads);
1582 return fc_call (aTHX_ type, FC_CB_EXEC, data, ds, vl, meta);
1583 } /* static int fc_exec (int, const data_set_t *, const value_list_t *,
1584 notification_meta_t **, void **) */
1586 static int pmatch_create (const oconfig_item_t *ci, void **user_data)
1587 {
1588 return fc_create (FC_MATCH, ci, user_data);
1589 } /* static int pmatch_create (const oconfig_item_t *, void **) */
1591 static int pmatch_destroy (void **user_data)
1592 {
1593 return fc_destroy (FC_MATCH, user_data);
1594 } /* static int pmatch_destroy (void **) */
1596 static int pmatch_match (const data_set_t *ds, const value_list_t *vl,
1597 notification_meta_t **meta, void **user_data)
1598 {
1599 return fc_exec (FC_MATCH, ds, vl, meta, user_data);
1600 } /* static int pmatch_match (const data_set_t *, const value_list_t *,
1601 notification_meta_t **, void **) */
1603 static match_proc_t pmatch = {
1604 pmatch_create, pmatch_destroy, pmatch_match
1605 };
1607 static int ptarget_create (const oconfig_item_t *ci, void **user_data)
1608 {
1609 return fc_create (FC_TARGET, ci, user_data);
1610 } /* static int ptarget_create (const oconfig_item_t *, void **) */
1612 static int ptarget_destroy (void **user_data)
1613 {
1614 return fc_destroy (FC_TARGET, user_data);
1615 } /* static int ptarget_destroy (void **) */
1617 static int ptarget_invoke (const data_set_t *ds, value_list_t *vl,
1618 notification_meta_t **meta, void **user_data)
1619 {
1620 return fc_exec (FC_TARGET, ds, vl, meta, user_data);
1621 } /* static int ptarget_invoke (const data_set_t *, value_list_t *,
1622 notification_meta_t **, void **) */
1624 static target_proc_t ptarget = {
1625 ptarget_create, ptarget_destroy, ptarget_invoke
1626 };
1628 /*
1629 * Exported Perl API.
1630 */
1632 static void _plugin_register_generic_userdata (pTHX, int type, const char *desc)
1633 {
1634 int ret = 0;
1635 user_data_t userdata;
1636 char *pluginname;
1638 dXSARGS;
1640 if (2 != items) {
1641 log_err ("Usage: Collectd::plugin_register_%s(pluginname, subname)",
1642 desc);
1643 XSRETURN_EMPTY;
1644 }
1646 if (! SvOK (ST (0))) {
1647 log_err ("Collectd::plugin_register_%s(pluginname, subname): "
1648 "Invalid pluginname", desc);
1649 XSRETURN_EMPTY;
1650 }
1651 if (! SvOK (ST (1))) {
1652 log_err ("Collectd::plugin_register_%s(pluginname, subname): "
1653 "Invalid subname", desc);
1654 XSRETURN_EMPTY;
1655 }
1657 /* Use pluginname as-is to allow flush a single perl plugin */
1658 pluginname = SvPV_nolen (ST (0));
1660 log_debug ("Collectd::plugin_register_%s: "
1661 "plugin = \"%s\", sub = \"%s\"",
1662 desc, pluginname, SvPV_nolen (ST (1)));
1664 memset(&userdata, 0, sizeof(userdata));
1665 userdata.data = strdup(SvPV_nolen (ST (1)));
1666 userdata.free_func = free;
1668 if (PLUGIN_READ == type) {
1669 ret = plugin_register_complex_read(
1670 "perl", /* group */
1671 pluginname,
1672 perl_read,
1673 plugin_get_interval(), /* Default interval */
1674 &userdata);
1675 }
1676 else if (PLUGIN_WRITE == type) {
1677 ret = plugin_register_write(pluginname, perl_write, &userdata);
1678 }
1679 else if (PLUGIN_LOG == type) {
1680 ret = plugin_register_log(pluginname, perl_log, &userdata);
1681 }
1682 else if (PLUGIN_NOTIF == type) {
1683 ret = plugin_register_notification(pluginname, perl_notify, &userdata);
1684 }
1685 else if (PLUGIN_FLUSH == type) {
1686 ret = plugin_register_flush(pluginname, perl_flush, &userdata);
1687 }
1688 else {
1689 ret = -1;
1690 }
1692 if (0 == ret)
1693 XSRETURN_YES;
1694 else {
1695 free (userdata.data);
1696 XSRETURN_EMPTY;
1697 }
1698 } /* static void _plugin_register_generic_userdata ( ... ) */
1700 /*
1701 * Collectd::plugin_register_TYPE (pluginname, subname).
1702 *
1703 * pluginname:
1704 * name of the perl plugin
1705 *
1706 * subname:
1707 * name of the plugin's subroutine that does the work
1708 */
1710 static XS (Collectd_plugin_register_read) {
1711 return _plugin_register_generic_userdata(aTHX, PLUGIN_READ, "read");
1712 }
1714 static XS (Collectd_plugin_register_write) {
1715 return _plugin_register_generic_userdata(aTHX, PLUGIN_WRITE, "write");
1716 }
1718 static XS (Collectd_plugin_register_log) {
1719 return _plugin_register_generic_userdata(aTHX, PLUGIN_LOG, "log");
1720 }
1722 static XS (Collectd_plugin_register_notification) {
1723 return _plugin_register_generic_userdata(aTHX, PLUGIN_NOTIF, "notification");
1724 }
1726 static XS (Collectd_plugin_register_flush) {
1727 return _plugin_register_generic_userdata(aTHX, PLUGIN_FLUSH, "flush");
1728 }
1730 typedef int perl_unregister_function_t(const char *name);
1732 static void _plugin_unregister_generic (pTHX,
1733 perl_unregister_function_t *unreg, const char *desc)
1734 {
1735 dXSARGS;
1737 if (1 != items) {
1738 log_err ("Usage: Collectd::plugin_unregister_%s(pluginname)", desc);
1739 XSRETURN_EMPTY;
1740 }
1742 if (! SvOK (ST (0))) {
1743 log_err ("Collectd::plugin_unregister_%s(pluginname): "
1744 "Invalid pluginname", desc);
1745 XSRETURN_EMPTY;
1746 }
1748 log_debug ("Collectd::plugin_unregister_%s: plugin = \"%s\"",
1749 desc, SvPV_nolen (ST (0)));
1751 unreg(SvPV_nolen (ST (0)));
1753 XSRETURN_EMPTY;
1755 return;
1756 } /* static void _plugin_unregister_generic ( ... ) */
1758 /*
1759 * Collectd::plugin_unregister_TYPE (pluginname).
1760 *
1761 * TYPE:
1762 * type of callback to be unregistered: read, write, log, notification, flush
1763 *
1764 * pluginname:
1765 * name of the perl plugin
1766 */
1768 static XS (Collectd_plugin_unregister_read) {
1769 return _plugin_unregister_generic(aTHX,
1770 plugin_unregister_read, "read");
1771 }
1773 static XS (Collectd_plugin_unregister_write) {
1774 return _plugin_unregister_generic(aTHX,
1775 plugin_unregister_write, "write");
1776 }
1778 static XS (Collectd_plugin_unregister_log) {
1779 return _plugin_unregister_generic(aTHX,
1780 plugin_unregister_log, "log");
1781 }
1783 static XS (Collectd_plugin_unregister_notification) {
1784 return _plugin_unregister_generic(aTHX,
1785 plugin_unregister_notification, "notification");
1786 }
1788 static XS (Collectd_plugin_unregister_flush) {
1789 return _plugin_unregister_generic(aTHX,
1790 plugin_unregister_flush, "flush");
1791 }
1793 /*
1794 * Collectd::plugin_register_data_set (type, dataset).
1795 *
1796 * type:
1797 * type of the dataset
1798 *
1799 * dataset:
1800 * dataset to be registered
1801 */
1802 static XS (Collectd_plugin_register_ds)
1803 {
1804 SV *data = NULL;
1805 int ret = 0;
1807 dXSARGS;
1809 log_warn ("Using plugin_register() to register new data-sets is "
1810 "deprecated - add new entries to a custom types.db instead.");
1812 if (2 != items) {
1813 log_err ("Usage: Collectd::plugin_register_data_set(type, dataset)");
1814 XSRETURN_EMPTY;
1815 }
1817 log_debug ("Collectd::plugin_register_data_set: "
1818 "type = \"%s\", dataset = \"%s\"",
1819 SvPV_nolen (ST (0)), SvPV_nolen (ST (1)));
1821 data = ST (1);
1823 if (SvROK (data) && (SVt_PVAV == SvTYPE (SvRV (data)))) {
1824 ret = pplugin_register_data_set (aTHX_ SvPV_nolen (ST (0)),
1825 (AV *)SvRV (data));
1826 }
1827 else {
1828 log_err ("Collectd::plugin_register_data_set: Invalid data.");
1829 XSRETURN_EMPTY;
1830 }
1832 if (0 == ret)
1833 XSRETURN_YES;
1834 else
1835 XSRETURN_EMPTY;
1836 } /* static XS (Collectd_plugin_register_ds) */
1838 /*
1839 * Collectd::plugin_unregister_data_set (type).
1840 *
1841 * type:
1842 * type of the dataset
1843 */
1844 static XS (Collectd_plugin_unregister_ds)
1845 {
1846 dXSARGS;
1848 if (1 != items) {
1849 log_err ("Usage: Collectd::plugin_unregister_data_set(type)");
1850 XSRETURN_EMPTY;
1851 }
1853 log_debug ("Collectd::plugin_unregister_data_set: type = \"%s\"",
1854 SvPV_nolen (ST (0)));
1856 if (0 == pplugin_unregister_data_set (SvPV_nolen (ST (0))))
1857 XSRETURN_YES;
1858 else
1859 XSRETURN_EMPTY;
1860 } /* static XS (Collectd_plugin_register_ds) */
1862 /*
1863 * Collectd::plugin_dispatch_values (name, values).
1864 *
1865 * name:
1866 * name of the plugin
1867 *
1868 * values:
1869 * value list to submit
1870 */
1871 static XS (Collectd_plugin_dispatch_values)
1872 {
1873 SV *values = NULL;
1875 int ret = 0;
1877 dXSARGS;
1879 if (1 != items) {
1880 log_err ("Usage: Collectd::plugin_dispatch_values(values)");
1881 XSRETURN_EMPTY;
1882 }
1884 log_debug ("Collectd::plugin_dispatch_values: values=\"%s\"",
1885 SvPV_nolen (ST (/* stack index = */ 0)));
1887 values = ST (/* stack index = */ 0);
1889 if (NULL == values)
1890 XSRETURN_EMPTY;
1892 /* Make sure the argument is a hash reference. */
1893 if (! (SvROK (values) && (SVt_PVHV == SvTYPE (SvRV (values))))) {
1894 log_err ("Collectd::plugin_dispatch_values: Invalid values.");
1895 XSRETURN_EMPTY;
1896 }
1898 ret = pplugin_dispatch_values (aTHX_ (HV *)SvRV (values));
1900 if (0 == ret)
1901 XSRETURN_YES;
1902 else
1903 XSRETURN_EMPTY;
1904 } /* static XS (Collectd_plugin_dispatch_values) */
1906 /*
1907 * Collectd::plugin_get_interval ().
1908 */
1909 static XS (Collectd_plugin_get_interval)
1910 {
1911 dXSARGS;
1913 /* make sure we don't get any unused variable warnings for 'items';
1914 * don't abort, though */
1915 if (items)
1916 log_err ("Usage: Collectd::plugin_get_interval()");
1918 XSRETURN_NV ((NV) CDTIME_T_TO_DOUBLE (plugin_get_interval ()));
1919 } /* static XS (Collectd_plugin_get_interval) */
1921 /* Collectd::plugin_write (plugin, ds, vl).
1922 *
1923 * plugin:
1924 * name of the plugin to call, may be 'undef'
1925 *
1926 * ds:
1927 * data-set that describes the submitted values, may be 'undef'
1928 *
1929 * vl:
1930 * value-list to be written
1931 */
1932 static XS (Collectd__plugin_write)
1933 {
1934 char *plugin;
1935 SV *ds, *vl;
1936 AV *ds_array;
1938 int ret;
1940 dXSARGS;
1942 if (3 != items) {
1943 log_err ("Usage: Collectd::plugin_write(plugin, ds, vl)");
1944 XSRETURN_EMPTY;
1945 }
1947 log_debug ("Collectd::plugin_write: plugin=\"%s\", ds=\"%s\", vl=\"%s\"",
1948 SvPV_nolen (ST (0)), SvOK (ST (1)) ? SvPV_nolen (ST (1)) : "",
1949 SvPV_nolen (ST (2)));
1951 if (! SvOK (ST (0)))
1952 plugin = NULL;
1953 else
1954 plugin = SvPV_nolen (ST (0));
1956 ds = ST (1);
1957 if (SvROK (ds) && (SVt_PVAV == SvTYPE (SvRV (ds))))
1958 ds_array = (AV *)SvRV (ds);
1959 else if (! SvOK (ds))
1960 ds_array = NULL;
1961 else {
1962 log_err ("Collectd::plugin_write: Invalid data-set.");
1963 XSRETURN_EMPTY;
1964 }
1966 vl = ST (2);
1967 if (! (SvROK (vl) && (SVt_PVHV == SvTYPE (SvRV (vl))))) {
1968 log_err ("Collectd::plugin_write: Invalid value-list.");
1969 XSRETURN_EMPTY;
1970 }
1972 ret = pplugin_write (aTHX_ plugin, ds_array, (HV *)SvRV (vl));
1974 if (0 == ret)
1975 XSRETURN_YES;
1976 else
1977 XSRETURN_EMPTY;
1978 } /* static XS (Collectd__plugin_write) */
1980 /*
1981 * Collectd::_plugin_flush (plugin, timeout, identifier).
1982 *
1983 * plugin:
1984 * name of the plugin to flush
1985 *
1986 * timeout:
1987 * timeout to use when flushing the data
1988 *
1989 * identifier:
1990 * data-set identifier to flush
1991 */
1992 static XS (Collectd__plugin_flush)
1993 {
1994 char *plugin = NULL;
1995 int timeout = -1;
1996 char *id = NULL;
1998 dXSARGS;
2000 if (3 != items) {
2001 log_err ("Usage: Collectd::_plugin_flush(plugin, timeout, id)");
2002 XSRETURN_EMPTY;
2003 }
2005 if (SvOK (ST (0)))
2006 plugin = SvPV_nolen (ST (0));
2008 if (SvOK (ST (1)))
2009 timeout = (int)SvIV (ST (1));
2011 if (SvOK (ST (2)))
2012 id = SvPV_nolen (ST (2));
2014 log_debug ("Collectd::_plugin_flush: plugin = \"%s\", timeout = %i, "
2015 "id = \"%s\"", plugin, timeout, id);
2017 if (0 == plugin_flush (plugin, timeout, id))
2018 XSRETURN_YES;
2019 else
2020 XSRETURN_EMPTY;
2021 } /* static XS (Collectd__plugin_flush) */
2023 /*
2024 * Collectd::plugin_dispatch_notification (notif).
2025 *
2026 * notif:
2027 * notification to dispatch
2028 */
2029 static XS (Collectd_plugin_dispatch_notification)
2030 {
2031 SV *notif = NULL;
2033 int ret = 0;
2035 dXSARGS;
2037 if (1 != items) {
2038 log_err ("Usage: Collectd::plugin_dispatch_notification(notif)");
2039 XSRETURN_EMPTY;
2040 }
2042 log_debug ("Collectd::plugin_dispatch_notification: notif = \"%s\"",
2043 SvPV_nolen (ST (0)));
2045 notif = ST (0);
2047 if (! (SvROK (notif) && (SVt_PVHV == SvTYPE (SvRV (notif))))) {
2048 log_err ("Collectd::plugin_dispatch_notification: Invalid notif.");
2049 XSRETURN_EMPTY;
2050 }
2052 ret = pplugin_dispatch_notification (aTHX_ (HV *)SvRV (notif));
2054 if (0 == ret)
2055 XSRETURN_YES;
2056 else
2057 XSRETURN_EMPTY;
2058 } /* static XS (Collectd_plugin_dispatch_notification) */
2060 /*
2061 * Collectd::plugin_log (level, message).
2062 *
2063 * level:
2064 * log level (LOG_DEBUG, ... LOG_ERR)
2065 *
2066 * message:
2067 * log message
2068 */
2069 static XS (Collectd_plugin_log)
2070 {
2071 dXSARGS;
2073 if (2 != items) {
2074 log_err ("Usage: Collectd::plugin_log(level, message)");
2075 XSRETURN_EMPTY;
2076 }
2078 plugin_log (SvIV (ST (0)), "%s", SvPV_nolen (ST (1)));
2079 XSRETURN_YES;
2080 } /* static XS (Collectd_plugin_log) */
2082 /*
2083 * Collectd::_fc_register (type, name)
2084 *
2085 * type:
2086 * match | target
2087 *
2088 * name:
2089 * name of the match
2090 */
2091 static XS (Collectd__fc_register)
2092 {
2093 int type;
2094 char *name;
2096 int ret = 0;
2098 dXSARGS;
2100 if (2 != items) {
2101 log_err ("Usage: Collectd::_fc_register(type, name)");
2102 XSRETURN_EMPTY;
2103 }
2105 type = SvIV (ST (0));
2106 name = SvPV_nolen (ST (1));
2108 if (FC_MATCH == type)
2109 ret = fc_register_match (name, pmatch);
2110 else if (FC_TARGET == type)
2111 ret = fc_register_target (name, ptarget);
2113 if (0 == ret)
2114 XSRETURN_YES;
2115 else
2116 XSRETURN_EMPTY;
2117 } /* static XS (Collectd_fc_register) */
2119 /*
2120 * Collectd::call_by_name (...).
2121 *
2122 * Call a Perl sub identified by its name passed through $Collectd::cb_name.
2123 */
2124 static XS (Collectd_call_by_name)
2125 {
2126 SV *tmp = NULL;
2127 char *name = NULL;
2129 if (NULL == (tmp = get_sv ("Collectd::cb_name", 0))) {
2130 sv_setpv (get_sv ("@", 1), "cb_name has not been set");
2131 CLEAR_STACK_FRAME;
2132 return;
2133 }
2135 name = SvPV_nolen (tmp);
2137 if (NULL == get_cv (name, 0)) {
2138 sv_setpvf (get_sv ("@", 1), "unknown callback \"%s\"", name);
2139 CLEAR_STACK_FRAME;
2140 return;
2141 }
2143 /* simply pass on the subroutine call without touching the stack,
2144 * thus leaving any arguments and return values in place */
2145 call_pv (name, 0);
2146 } /* static XS (Collectd_call_by_name) */
2148 /*
2149 * Interface to collectd.
2150 */
2152 static int perl_init (void)
2153 {
2154 int status;
2155 dTHX;
2157 if (NULL == perl_threads)
2158 return 0;
2160 if (NULL == aTHX) {
2161 c_ithread_t *t = NULL;
2163 pthread_mutex_lock (&perl_threads->mutex);
2164 t = c_ithread_create (perl_threads->head->interp);
2165 pthread_mutex_unlock (&perl_threads->mutex);
2167 aTHX = t->interp;
2168 }
2170 log_debug ("perl_init: c_ithread: interp = %p (active threads: %i)",
2171 aTHX, perl_threads->number_of_threads);
2173 /* Lock the base thread to avoid race conditions with c_ithread_create().
2174 * See https://github.com/collectd/collectd/issues/9 and
2175 * https://github.com/collectd/collectd/issues/1706 for details.
2176 */
2177 assert (aTHX == perl_threads->head->interp);
2178 pthread_mutex_lock (&perl_threads->mutex);
2180 status = pplugin_call (aTHX_ PLUGIN_INIT);
2182 pthread_mutex_unlock (&perl_threads->mutex);
2184 return status;
2185 } /* static int perl_init (void) */
2187 static int perl_read (user_data_t *user_data)
2188 {
2189 dTHX;
2191 if (NULL == perl_threads)
2192 return 0;
2194 if (NULL == aTHX) {
2195 c_ithread_t *t = NULL;
2197 pthread_mutex_lock (&perl_threads->mutex);
2198 t = c_ithread_create (perl_threads->head->interp);
2199 pthread_mutex_unlock (&perl_threads->mutex);
2201 aTHX = t->interp;
2202 }
2204 /* Assert that we're not running as the base thread. Otherwise, we might
2205 * run into concurrency issues with c_ithread_create(). See
2206 * https://github.com/collectd/collectd/issues/9 for details. */
2207 assert (aTHX != perl_threads->head->interp);
2209 log_debug ("perl_read: c_ithread: interp = %p (active threads: %i)",
2210 aTHX, perl_threads->number_of_threads);
2212 return pplugin_call (aTHX_ PLUGIN_READ, user_data->data);
2213 } /* static int perl_read (user_data_t *user_data) */
2215 static int perl_write (const data_set_t *ds, const value_list_t *vl,
2216 user_data_t *user_data)
2217 {
2218 int status;
2219 dTHX;
2221 if (NULL == perl_threads)
2222 return 0;
2224 if (NULL == aTHX) {
2225 c_ithread_t *t = NULL;
2227 pthread_mutex_lock (&perl_threads->mutex);
2228 t = c_ithread_create (perl_threads->head->interp);
2229 pthread_mutex_unlock (&perl_threads->mutex);
2231 aTHX = t->interp;
2232 }
2234 /* Lock the base thread if this is not called from one of the read threads
2235 * to avoid race conditions with c_ithread_create(). See
2236 * https://github.com/collectd/collectd/issues/9 for details. */
2237 if (aTHX == perl_threads->head->interp)
2238 pthread_mutex_lock (&perl_threads->mutex);
2240 log_debug ("perl_write: c_ithread: interp = %p (active threads: %i)",
2241 aTHX, perl_threads->number_of_threads);
2242 status = pplugin_call (aTHX_ PLUGIN_WRITE, user_data->data, ds, vl);
2244 if (aTHX == perl_threads->head->interp)
2245 pthread_mutex_unlock (&perl_threads->mutex);
2247 return status;
2248 } /* static int perl_write (const data_set_t *, const value_list_t *) */
2250 static void perl_log (int level, const char *msg,
2251 user_data_t *user_data)
2252 {
2253 dTHX;
2255 if (NULL == perl_threads)
2256 return;
2258 if (NULL == aTHX) {
2259 c_ithread_t *t = NULL;
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 /* Lock the base thread if this is not called from one of the read threads
2269 * to avoid race conditions with c_ithread_create(). See
2270 * https://github.com/collectd/collectd/issues/9 for details.
2271 */
2273 if (aTHX == perl_threads->head->interp)
2274 pthread_mutex_lock (&perl_threads->mutex);
2276 pplugin_call (aTHX_ PLUGIN_LOG, user_data->data, level, msg);
2278 if (aTHX == perl_threads->head->interp)
2279 pthread_mutex_unlock (&perl_threads->mutex);
2281 return;
2282 } /* static void perl_log (int, const char *) */
2284 static int perl_notify (const notification_t *notif, user_data_t *user_data)
2285 {
2286 dTHX;
2288 if (NULL == perl_threads)
2289 return 0;
2291 if (NULL == aTHX) {
2292 c_ithread_t *t = NULL;
2294 pthread_mutex_lock (&perl_threads->mutex);
2295 t = c_ithread_create (perl_threads->head->interp);
2296 pthread_mutex_unlock (&perl_threads->mutex);
2298 aTHX = t->interp;
2299 }
2300 return pplugin_call (aTHX_ PLUGIN_NOTIF, user_data->data, notif);
2301 } /* static int perl_notify (const notification_t *) */
2303 static int perl_flush (cdtime_t timeout, const char *identifier,
2304 user_data_t *user_data)
2305 {
2306 dTHX;
2308 if (NULL == perl_threads)
2309 return 0;
2311 if (NULL == aTHX) {
2312 c_ithread_t *t = NULL;
2314 pthread_mutex_lock (&perl_threads->mutex);
2315 t = c_ithread_create (perl_threads->head->interp);
2316 pthread_mutex_unlock (&perl_threads->mutex);
2318 aTHX = t->interp;
2319 }
2320 return pplugin_call (aTHX_ PLUGIN_FLUSH, user_data->data, timeout, identifier);
2321 } /* static int perl_flush (const int) */
2323 static int perl_shutdown (void)
2324 {
2325 c_ithread_t *t;
2326 int ret;
2328 dTHX;
2330 plugin_unregister_complex_config ("perl");
2331 plugin_unregister_read_group ("perl");
2333 if (NULL == perl_threads)
2334 return 0;
2336 if (NULL == aTHX) {
2337 pthread_mutex_lock (&perl_threads->mutex);
2338 t = c_ithread_create (perl_threads->head->interp);
2339 pthread_mutex_unlock (&perl_threads->mutex);
2341 aTHX = t->interp;
2342 }
2344 log_debug ("perl_shutdown: c_ithread: interp = %p (active threads: %i)",
2345 aTHX, perl_threads->number_of_threads);
2347 plugin_unregister_init ("perl");
2349 ret = pplugin_call (aTHX_ PLUGIN_SHUTDOWN);
2351 pthread_mutex_lock (&perl_threads->mutex);
2352 t = perl_threads->tail;
2354 while (NULL != t) {
2355 struct timespec ts_wait;
2356 c_ithread_t *thr = t;
2358 /* the pointer has to be advanced before destroying
2359 * the thread as this will free the memory */
2360 t = t->prev;
2362 thr->shutdown = 1;
2363 if (thr->running) {
2364 /* Give some time to thread to exit from Perl interpreter */
2365 WARNING ("perl shutdown: Thread is running inside Perl. Waiting.");
2366 ts_wait.tv_sec = 0;
2367 ts_wait.tv_nsec = 500000;
2368 nanosleep (&ts_wait, NULL);
2369 }
2370 if (thr->running) {
2371 pthread_kill (thr->pthread, SIGTERM);
2372 ERROR ("perl shutdown: Thread hangs inside Perl. Thread killed.");
2373 }
2374 c_ithread_destroy (thr);
2375 }
2377 pthread_mutex_unlock (&perl_threads->mutex);
2378 pthread_mutex_destroy (&perl_threads->mutex);
2379 pthread_mutexattr_destroy (&perl_threads->mutexattr);
2381 sfree (perl_threads);
2383 pthread_key_delete (perl_thr_key);
2385 PERL_SYS_TERM ();
2387 plugin_unregister_shutdown ("perl");
2388 return ret;
2389 } /* static void perl_shutdown (void) */
2391 /*
2392 * Access functions for global variables.
2393 *
2394 * These functions implement the "magic" used to access
2395 * the global variables from Perl.
2396 */
2398 static int g_pv_get (pTHX_ SV *var, MAGIC *mg)
2399 {
2400 char *pv = mg->mg_ptr;
2401 sv_setpv (var, pv);
2402 return 0;
2403 } /* static int g_pv_get (pTHX_ SV *, MAGIC *) */
2405 static int g_pv_set (pTHX_ SV *var, MAGIC *mg)
2406 {
2407 char *pv = mg->mg_ptr;
2408 sstrncpy (pv, SvPV_nolen (var), DATA_MAX_NAME_LEN);
2409 return 0;
2410 } /* static int g_pv_set (pTHX_ SV *, MAGIC *) */
2412 static int g_interval_get (pTHX_ SV *var, MAGIC *mg)
2413 {
2414 log_warn ("Accessing $interval_g is deprecated (and might not "
2415 "give the desired results) - plugin_get_interval() should "
2416 "be used instead.");
2417 sv_setnv (var, CDTIME_T_TO_DOUBLE (interval_g));
2418 return 0;
2419 } /* static int g_interval_get (pTHX_ SV *, MAGIC *) */
2421 static int g_interval_set (pTHX_ SV *var, MAGIC *mg)
2422 {
2423 double nv = (double)SvNV (var);
2424 log_warn ("Accessing $interval_g is deprecated (and might not "
2425 "give the desired results) - plugin_get_interval() should "
2426 "be used instead.");
2427 interval_g = DOUBLE_TO_CDTIME_T (nv);
2428 return 0;
2429 } /* static int g_interval_set (pTHX_ SV *, MAGIC *) */
2431 static MGVTBL g_pv_vtbl = {
2432 g_pv_get, g_pv_set, NULL, NULL, NULL, NULL, NULL
2433 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2434 , NULL
2435 #endif
2436 };
2437 static MGVTBL g_interval_vtbl = {
2438 g_interval_get, g_interval_set, NULL, NULL, NULL, NULL, NULL
2439 #if HAVE_PERL_STRUCT_MGVTBL_SVT_LOCAL
2440 , NULL
2441 #endif
2442 };
2444 /* bootstrap the Collectd module */
2445 static void xs_init (pTHX)
2446 {
2447 HV *stash = NULL;
2448 SV *tmp = NULL;
2449 char *file = __FILE__;
2451 dXSUB_SYS;
2453 /* enable usage of Perl modules using shared libraries */
2454 newXS ("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2456 /* register API */
2457 for (int i = 0; NULL != api[i].f; ++i)
2458 newXS (api[i].name, api[i].f, file);
2460 stash = gv_stashpv ("Collectd", 1);
2462 /* export "constants" */
2463 for (int i = 0; '\0' != constants[i].name[0]; ++i)
2464 newCONSTSUB (stash, constants[i].name, newSViv (constants[i].value));
2466 /* export global variables
2467 * by adding "magic" to the SV's representing the globale variables
2468 * perl is able to automagically call the get/set function when
2469 * accessing any such variable (this is basically the same as using
2470 * tie() in Perl) */
2471 /* global strings */
2472 for (int i = 0; '\0' != g_strings[i].name[0]; ++i) {
2473 tmp = get_sv (g_strings[i].name, 1);
2474 sv_magicext (tmp, NULL, PERL_MAGIC_ext, &g_pv_vtbl,
2475 g_strings[i].var, 0);
2476 }
2478 tmp = get_sv ("Collectd::interval_g", /* create = */ 1);
2479 sv_magicext (tmp, NULL, /* how = */ PERL_MAGIC_ext,
2480 /* vtbl = */ &g_interval_vtbl,
2481 /* name = */ NULL, /* namelen = */ 0);
2483 return;
2484 } /* static void xs_init (pTHX) */
2486 /* Initialize the global Perl interpreter. */
2487 static int init_pi (int argc, char **argv)
2488 {
2489 dTHXa (NULL);
2491 if (NULL != perl_threads)
2492 return 0;
2494 log_info ("Initializing Perl interpreter...");
2495 #if COLLECT_DEBUG
2496 {
2497 for (int i = 0; i < argc; ++i)
2498 log_debug ("argv[%i] = \"%s\"", i, argv[i]);
2499 }
2500 #endif /* COLLECT_DEBUG */
2502 if (0 != pthread_key_create (&perl_thr_key, c_ithread_destructor)) {
2503 log_err ("init_pi: pthread_key_create failed");
2505 /* this must not happen - cowardly giving up if it does */
2506 return -1;
2507 }
2509 #ifdef __FreeBSD__
2510 /* On FreeBSD, PERL_SYS_INIT3 expands to some expression which
2511 * triggers a "value computed is not used" warning by gcc. */
2512 (void)
2513 #endif
2514 PERL_SYS_INIT3 (&argc, &argv, &environ);
2516 perl_threads = smalloc (sizeof (*perl_threads));
2517 memset (perl_threads, 0, sizeof (c_ithread_list_t));
2519 pthread_mutexattr_init(&perl_threads->mutexattr);
2520 pthread_mutexattr_settype(&perl_threads->mutexattr, PTHREAD_MUTEX_RECURSIVE);
2521 pthread_mutex_init (&perl_threads->mutex, &perl_threads->mutexattr);
2522 /* locking the mutex should not be necessary at this point
2523 * but let's just do it for the sake of completeness */
2524 pthread_mutex_lock (&perl_threads->mutex);
2526 perl_threads->head = c_ithread_create (NULL);
2527 perl_threads->tail = perl_threads->head;
2529 if (NULL == (perl_threads->head->interp = perl_alloc ())) {
2530 log_err ("init_pi: Not enough memory.");
2531 exit (3);
2532 }
2534 aTHX = perl_threads->head->interp;
2535 pthread_mutex_unlock (&perl_threads->mutex);
2537 perl_construct (aTHX);
2539 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
2541 if (0 != perl_parse (aTHX_ xs_init, argc, argv, NULL)) {
2542 SV *err = get_sv ("@", 1);
2543 log_err ("init_pi: Unable to bootstrap Collectd: %s",
2544 SvPV_nolen (err));
2546 perl_destruct (perl_threads->head->interp);
2547 perl_free (perl_threads->head->interp);
2548 sfree (perl_threads);
2550 pthread_key_delete (perl_thr_key);
2551 return -1;
2552 }
2554 /* Set $0 to "collectd" because perl_parse() has to set it to "-e". */
2555 sv_setpv (get_sv ("0", 0), "collectd");
2557 perl_run (aTHX);
2559 plugin_register_init ("perl", perl_init);
2560 plugin_register_shutdown ("perl", perl_shutdown);
2561 return 0;
2562 } /* static int init_pi (const char **, const int) */
2564 /*
2565 * LoadPlugin "<Plugin>"
2566 */
2567 static int perl_config_loadplugin (pTHX_ oconfig_item_t *ci)
2568 {
2569 char module_name[DATA_MAX_NAME_LEN];
2571 char *value = NULL;
2573 if ((0 != ci->children_num) || (1 != ci->values_num)
2574 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2575 log_err ("LoadPlugin expects a single string argument.");
2576 return 1;
2577 }
2579 value = ci->values[0].value.string;
2581 if (NULL == get_module_name (module_name, sizeof (module_name), value)) {
2582 log_err ("Invalid module name %s", value);
2583 return (1);
2584 }
2586 if (0 != init_pi (perl_argc, perl_argv))
2587 return -1;
2589 assert (NULL != perl_threads);
2590 assert (NULL != perl_threads->head);
2592 aTHX = perl_threads->head->interp;
2594 log_debug ("perl_config: Loading Perl plugin \"%s\"", value);
2595 load_module (PERL_LOADMOD_NOIMPORT,
2596 newSVpv (module_name, strlen (module_name)), Nullsv);
2597 return 0;
2598 } /* static int perl_config_loadplugin (oconfig_item_it *) */
2600 /*
2601 * BaseName "<Name>"
2602 */
2603 static int perl_config_basename (pTHX_ oconfig_item_t *ci)
2604 {
2605 char *value = NULL;
2607 if ((0 != ci->children_num) || (1 != ci->values_num)
2608 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2609 log_err ("BaseName expects a single string argument.");
2610 return 1;
2611 }
2613 value = ci->values[0].value.string;
2615 log_debug ("perl_config: Setting plugin basename to \"%s\"", value);
2616 sstrncpy (base_name, value, sizeof (base_name));
2617 return 0;
2618 } /* static int perl_config_basename (oconfig_item_it *) */
2620 /*
2621 * EnableDebugger "<Package>"|""
2622 */
2623 static int perl_config_enabledebugger (pTHX_ oconfig_item_t *ci)
2624 {
2625 char *value = NULL;
2627 if ((0 != ci->children_num) || (1 != ci->values_num)
2628 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2629 log_err ("EnableDebugger expects a single string argument.");
2630 return 1;
2631 }
2633 if (NULL != perl_threads) {
2634 log_warn ("EnableDebugger has no effects if used after LoadPlugin.");
2635 return 1;
2636 }
2638 value = ci->values[0].value.string;
2640 perl_argv = realloc (perl_argv,
2641 (++perl_argc + 1) * sizeof (char *));
2643 if (NULL == perl_argv) {
2644 log_err ("perl_config: Not enough memory.");
2645 exit (3);
2646 }
2648 if ('\0' == value[0]) {
2649 perl_argv[perl_argc - 1] = "-d";
2650 }
2651 else {
2652 perl_argv[perl_argc - 1] = smalloc (strlen (value) + 4);
2653 sstrncpy (perl_argv[perl_argc - 1], "-d:", 4);
2654 sstrncpy (perl_argv[perl_argc - 1] + 3, value, strlen (value) + 1);
2655 }
2657 perl_argv[perl_argc] = NULL;
2658 return 0;
2659 } /* static int perl_config_enabledebugger (oconfig_item_it *) */
2661 /*
2662 * IncludeDir "<Dir>"
2663 */
2664 static int perl_config_includedir (pTHX_ oconfig_item_t *ci)
2665 {
2666 char *value = NULL;
2668 if ((0 != ci->children_num) || (1 != ci->values_num)
2669 || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2670 log_err ("IncludeDir expects a single string argument.");
2671 return 1;
2672 }
2674 value = ci->values[0].value.string;
2676 if (NULL == aTHX) {
2677 perl_argv = realloc (perl_argv,
2678 (++perl_argc + 1) * sizeof (char *));
2680 if (NULL == perl_argv) {
2681 log_err ("perl_config: Not enough memory.");
2682 exit (3);
2683 }
2685 perl_argv[perl_argc - 1] = smalloc (strlen (value) + 3);
2686 sstrncpy(perl_argv[perl_argc - 1], "-I", 3);
2687 sstrncpy(perl_argv[perl_argc - 1] + 2, value, strlen (value) + 1);
2689 perl_argv[perl_argc] = NULL;
2690 }
2691 else {
2692 /* prepend the directory to @INC */
2693 av_unshift (GvAVn (PL_incgv), 1);
2694 av_store (GvAVn (PL_incgv), 0, newSVpv (value, strlen (value)));
2695 }
2696 return 0;
2697 } /* static int perl_config_includedir (oconfig_item_it *) */
2699 /*
2700 * <Plugin> block
2701 */
2702 static int perl_config_plugin (pTHX_ oconfig_item_t *ci)
2703 {
2704 int retvals = 0;
2705 int ret = 0;
2707 char *plugin;
2708 HV *config;
2710 dSP;
2712 if ((1 != ci->values_num) || (OCONFIG_TYPE_STRING != ci->values[0].type)) {
2713 log_err ("LoadPlugin expects a single string argument.");
2714 return 1;
2715 }
2717 plugin = ci->values[0].value.string;
2718 config = newHV ();
2720 if (0 != oconfig_item2hv (aTHX_ ci, config)) {
2721 hv_clear (config);
2722 hv_undef (config);
2724 log_err ("Unable to convert configuration to a Perl hash value.");
2725 config = (HV *)&PL_sv_undef;
2726 }
2728 ENTER;
2729 SAVETMPS;
2731 PUSHMARK (SP);
2733 XPUSHs (sv_2mortal (newSVpv (plugin, 0)));
2734 XPUSHs (sv_2mortal (newRV_noinc ((SV *)config)));
2736 PUTBACK;
2738 retvals = call_pv ("Collectd::_plugin_dispatch_config", G_SCALAR);
2740 SPAGAIN;
2741 if (0 < retvals) {
2742 SV *tmp = POPs;
2743 if (! SvTRUE (tmp))
2744 ret = 1;
2745 }
2746 else
2747 ret = 1;
2749 PUTBACK;
2750 FREETMPS;
2751 LEAVE;
2752 return ret;
2753 } /* static int perl_config_plugin (oconfig_item_it *) */
2755 static int perl_config (oconfig_item_t *ci)
2756 {
2757 int status = 0;
2759 dTHXa (NULL);
2761 for (int i = 0; i < ci->children_num; ++i) {
2762 oconfig_item_t *c = ci->children + i;
2763 int current_status = 0;
2765 if (NULL != perl_threads)
2766 {
2767 if ((aTHX = PERL_GET_CONTEXT) == NULL)
2768 return -1;
2769 }
2771 if (0 == strcasecmp (c->key, "LoadPlugin"))
2772 current_status = perl_config_loadplugin (aTHX_ c);
2773 else if (0 == strcasecmp (c->key, "BaseName"))
2774 current_status = perl_config_basename (aTHX_ c);
2775 else if (0 == strcasecmp (c->key, "EnableDebugger"))
2776 current_status = perl_config_enabledebugger (aTHX_ c);
2777 else if (0 == strcasecmp (c->key, "IncludeDir"))
2778 current_status = perl_config_includedir (aTHX_ c);
2779 else if (0 == strcasecmp (c->key, "Plugin"))
2780 current_status = perl_config_plugin (aTHX_ c);
2781 else
2782 {
2783 log_warn ("Ignoring unknown config key \"%s\".", c->key);
2784 current_status = 0;
2785 }
2787 /* fatal error - it's up to perl_config_* to clean up */
2788 if (0 > current_status) {
2789 log_err ("Configuration failed with a fatal error - "
2790 "plugin disabled!");
2791 return current_status;
2792 }
2794 status += current_status;
2795 }
2796 return status;
2797 } /* static int perl_config (oconfig_item_t *) */
2799 void module_register (void)
2800 {
2801 perl_argc = 4;
2802 perl_argv = smalloc ((perl_argc + 1) * sizeof (*perl_argv));
2804 /* default options for the Perl interpreter */
2805 perl_argv[0] = "";
2806 perl_argv[1] = "-MCollectd";
2807 perl_argv[2] = "-e";
2808 perl_argv[3] = "1";
2809 perl_argv[4] = NULL;
2811 plugin_register_complex_config ("perl", perl_config);
2812 return;
2813 } /* void module_register (void) */
2815 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */