#!@@PERL@@ -w
# -*- cperl -*-

=head1 NAME

haproxy_ - Graph stats from the haproxy daemon

=head1 APPLICABLE SYSTEMS

Any haproxy host

=head1 CONFIGURATION

This is a wildcard plugin to support fetching status from multiple
instances of haproxy that each need a distinct configurations, e.g.:

   haproxy_backend

and

   haproxy_frontend

Each with a separate configuration.  The following example shows the
default URL used by the plugin for the imaginary backend:

   [haproxy_backend]
	env.url http://localhost/haproxy-status;csv;norefresh

If you need authenticated access to the URL you can specify the
username and password in the URL.  For example:

   [haproxy_backend]
	env.url http://munin:spamalot@localhost/haproxy-status;csv;norefresh

This will provide for HTTP basic authentication.

=head1 MAGIC MARKERS

  #%# family=contrib

=head1 VERSION

  $Id$

=head1 AUTHOR

Jimmy Olsen (based on some Apache plugin).  Documented by Nicolai Langfeldt.

=head1 LICENSE

GPLv2

=cut

use Munin::Plugin;

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

my $URL = exists $ENV{'url'} ? $ENV{'url'} : "http://localhost/haproxy-status;csv;norefresh";

my $ua = LWP::UserAgent->new(timeout => 30,
		agent => sprintf("munin/%s (libwww-perl/%s)", $Munin::Common::Defaults::MUNIN_VERSION, $LWP::VERSION));

my $url = $URL;
my $response = $ua->request(HTTP::Request->new('GET',$url));
my $content = $response->content;
my %backends = ();

if ( exists $ARGV[0] and $ARGV[0] eq "config" )
{
	my $clusterid = "unknown cluster";
	if ($content =~ /\n([^,]+),FRONTEND/) {
		$clusterid = $1;
	}
	print "graph_title HAProxy statistics for $clusterid\n";
	print "graph_args --base 1000 -l 0\n";
	print "graph_vlabel connections per \${graph_period}\n";
	print "graph_category haproxy\n";
	my $fieldnum = 0;
	while ($content =~ /\n([^,]+),([^,]+),[^,]+,[^,]+,[^,]+,[^,]+,[^,]*,([^,]+),[^,]+,[^,]+,[^,]*,[^,]+,/g) {
		next if $2 eq "BACKEND";
		next if defined $backends{$2};
		$backends{$2} = 1;
		print "s$2.label ", $2, "\n";
		print "s$2.type DERIVE\n";
		print "s$2.min 0\n";
		if ($fieldnum++) {
			print "s$2.draw STACK\n";
		} else {
			print "s$2.draw AREA\n";
		}
	}
	exit 0;
}

while ($content =~ /\n([^,]+),([^,]+),[^,]+,[^,]+,[^,]+,[^,]+,[^,]*,([^,]+),[^,]+,[^,]+,[^,]*,[^,]+,/g) {
	next if $2 eq "BACKEND";
	if (defined ($2)) {
		$backends{$2} += $3;
	} else {
		$backends{$2} = $3;
	}
}

foreach my $be (keys %backends) {
	print "s$be.value ", $backends{$be}, "\n";
}
# vim:syntax=perl
