#!@@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 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";
	while ($content =~ /\n([^,]+),([^,]+),[^,]+,[^,]+,[^,]+,[^,]+,[^,]*,([^,]+),[^,]+,[^,]+,[^,]*,[^,]+,/g) {
		next if $2 eq "BACKEND";
		my $field_name = clean_fieldname($2);
		next if defined $backends{$field_name};
		$backends{$field_name} = 1;
		print "s$field_name.label ", $2, "\n";
		print "s$field_name.type DERIVE\n";
		print "s$field_name.min 0\n";
		print "s$field_name.draw AREASTACK\n";
	}
	exit 0;
}

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

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