#!/usr/bin/perl
# -*- cperl -*-

=head1 NAME

php_fpm_processes - Munin plugin to show number of number of use processes on php-fpm.


Inspirated by php5-fpm_status plugin by Daniel Caillibaud

=head1 APPLICABLE SYSTEMS

Any php-fpm host 
You will need the perl fastcgi::client on your host 

=head1 CONFIGURATION

You have to put this in your plugin.conf.d folder 

[php_fpm_process]
   env.serveraddr 127.0.0.1
   env.port 9000
   env.path /status 

=head1 MAGIC MARKERS

  #%# family=auto
  #%# capabilities=autoconf

=head1 VERSION

  v1.0 

=head1 AUTHOR

Minitux 

=head1 LICENSE

GNU General Public License, version 3

=cut


use IO::Socket::INET;
use FCGI::Client;

my $ish = 1;
my $header = "";
my $body = "";
my $IDLE = 0;
my $ACTIVE = 0;
my $TOTAL = 0;

my $SERVERADDR = $ENV{'serveraddr'} || "127.0.0.1";
my $PORT = $ENV{'port'} || "9000";
my $PATH = $ENV{'path'} || "/status";

my $sock = IO::Socket::INET->new(
        PeerAddr =>  $SERVERADDR,
        PeerPort =>  $PORT,
);

if (!$sock) { 
	print "Server maybe down, unabled to connect to $SERVERADDR:$PORT";
	exit 2;
}

	my $client = FCGI::Client::Connection->new( sock => $sock );
	my ( $stdout, $stderr, $appstatus )  = $client->request( 
		+{
	            REQUEST_METHOD => 'GET',
		    SCRIPT_FILENAME => '',
		    QUERY_STRING => '',
		    SCRIPT_NAME    => $PATH,
		},
	        ''
	);


if ( defined $ARGV[0] and $ARGV[0] eq "config" )
{

  print "graph_title php5-fpm status $pool";
  print "graph_args --base 1000 -l 0";
  print "graph_vlabel Processes";
  print "graph_scale yes";
  print "graph_category php";
  print "graph_info This graph shows the php5-fpm process manager status from pool: $pool";
  print "active.label Active processes";
  print "active.type GAUGE";
  print "active.draw AREA";
  print "active.info The number of active processes";
  print "idle.label Idle processes";
  print "idle.type GAUGE";
  print "idle.draw STACK";
  print "idle.info The number of idle processes";
  print "total.label Total processes";
  print "total.type GAUGE";
  print "total.draw LINE2";
  print "total.info The number of idle + active processes";
  exit 0
}

$stdout =~ s/\r//g;

while($stdout =~ /([^\n]*)\n?/g) {
	if(!$1) {
		$ish = 0;
		next;
	}
	if($ish == 1) {
		$header .= $1."\n";
	} else {
		$body .= $1."\n";
	}
}	

if($body =~ m/idle processes: (.*?)\n/) {
        $IDLE = $1;
	print "idle.value ".$IDLE."\n";
}
if($body =~ m/active processes: (.*?)\n/) {
        $ACTIVE = $1;
	print "active.value ".$ACTIVE."\n";
}
if($body =~ m/total processes: (.*?)\n/) {
        $TOTAL = $1;
	print "total.value ".$TOTAL."\n";
}
