#!/usr/pkg/bin/perl
#
# Plugin to monitor the number of apache-processes running on the
# machine, and (in addition to a simple process count), separate then
# into "busy" or "idle" servers.
#
# Requirements:
# 	- Needs access to http://localhost/server-status?auto (or modify the
# 	  address for another host). See your apache documentation on how to
# 	  set up this url in your httpd.conf.
#
# Tip: To see if it's already set up correctly, just run this plugin
# with the parameter "autoconf". If you get a "yes", everything should
# work like a charm already.
#
# Parameters supported:
#
# 	config
# 	autoconf
#
# Configurable variables
#
# 	url      - Override default status-url
#
# Magic markers:
#%# family=auto
#%# capabilities=autoconf

my $ret = undef;
if (! eval "require LWP::UserAgent;")
{
	$ret = "LWP::UserAgent not found";
}

my $URL = exists $ENV{'url'} ? $ENV{'url'} : "http://127.0.0.1:%d/server-status?auto";
my @PORTS = exists $ENV{'ports'} ? split(' ', $ENV{'ports'}) : (80);

if ( exists $ARGV[0] and $ARGV[0] eq "autoconf" )
{
	if ($ret)
	{
		print "no ($ret)\n";
		exit 1;
	}
	my $ua = LWP::UserAgent->new(timeout => 30);
	my @badports;

        foreach my $port (@PORTS) {
                my $url = sprintf $URL, $port;
                my $response = $ua->request(HTTP::Request->new('GET',$url));
                push @badports, $port unless $response->is_success and $response->content =~ /Idle(?:Servers|Workers)/im;
        }

	if (@badports)
	{
		print "no (no apache server-status on ports @badports)\n";
		exit 1;
	}
	else
	{
		print "yes\n";
		exit 0;
	}
}

if ( exists $ARGV[0] and $ARGV[0] eq "config" )
{
        print "graph_title Apache processes\n";
        print "graph_args --base 1000 -l 0\n";
		print "graph_category apache\n";
	print "graph_order ";
	foreach my $port (@PORTS) {
	    print "busy$port idle$port ";
	}
	print "\n";
        print "graph_vlabel processes\n";
        print "graph_total total\n";
	foreach my $port (@PORTS) {
	    print "busy$port.label busy servers $port\n";
	    if (@PORTS == 1) {
		print "busy$port.draw AREA\n";
	    }
	    else
	    {
		print "busy$port.draw LINE2\n";
	    }
	    print "idle$port.label idle servers $port\n";
	    print "idle$port.draw STACK\n";
	}
	exit 0;
}

foreach my $port (@PORTS)
{
    my $ua = LWP::UserAgent->new(timeout => 30);
    my $url = sprintf $URL, $port;
    my $response = $ua->request(HTTP::Request->new('GET',$url));
    if ($response->content =~ /^Busy(?:Servers|Workers):\s+(.+)$/im) {
	    print "busy$port.value $1\n";
    } else {
	    print "busy$port.value U\n";
    }
    if ($response->content =~ /^Idle(?:Servers|Workers):\s+(.+)$/im) {
	    print "idle$port.value $1\n";
    } else {
	    print "idle$port.value U\n";
    }
}

# vim:syntax=perl
