collectd/collectd — Issue #9: Race condition in perl module.
Author: octo
Created: 2012-02-19 20:30:48+00:00
State: open

From: Rrpv (Mantis #47)

I'm started to write my 'new cool plugin' for gathering php-fpm stats using collectd perl module. During my tests I noted what collectd with perl is very unstable. I launch collectd in foreground with simple config (!), and see segfaults too often.

After debugging, I have localized the problem. The problem is due race condition while doing perl_clone() from "base thread".

After initialization and before do_loop() , collectd has INFO ("Initialization complete, entering read-loop."); output. Base thread perl instance gets this log message at perl_log() as plugin has registered appropriate callback. But in the same moment we have Read Threads running, as do_init() is called before this INFO(). Oops, we get race and segfaults.

Some environments can be less affected by this. If configuration have much modules, the read from perl plugin will be slightly later. The logging will be completed at that moment, so perl_clone() will be completed successfully too.

Right now I have no idea how to solve this problem.

The perl plugin needs to be rewriten completely, as I think (because it should register callbacks by modules, not by single bulk as it is done now), but this is hard and long way.

If anybody has ideas, I will work on this (on both simple solve and full module rewrite).

This tested on Debian squeeze 32/64 bit (both), collectd 4.10.1. My config and my perl module are attached to reproduce this.

**Proposed patch:**

```patch
--- perl.c.orig 2010-07-09 17:01:59.000000000 +0700
+++ perl.c 2011-12-11 01:22:09.000000000 +0700
@@ -1968,8 +1968,15 @@

aTHX = t->interp;
}
+
+ if (aTHX == perl_threads->head->interp)
+ pthread_mutex_lock (&perl_threads->mutex);

pplugin_call_all (aTHX_ PLUGIN_LOG, level, msg);
+
+ if (aTHX == perl_threads->head->interp)
+ pthread_mutex_unlock (&perl_threads->mutex);
+
return;
} /* static void perl_log (int, const char *) */

```