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

=head1 NAME

php_fpm_process - 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,
		},
	        ''
	);

$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 ( defined $ARGV[0] and $ARGV[0] eq "config" )
{
 
  if($body =~ m/pool:\s+(.*?)\n/) {
    $pool = $1;
  }

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

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";
}
