#!/usr/bin/perl

=head1 NAME

    apache-monitoring - вывод данных server-status в формате graphite

=cut

use strict;
use warnings;

use Pid::File::Flock qw/:auto/;
use Yandex::Hostname qw//;
use LWP::UserAgent qw//;

if (@ARGV != 2 || $ARGV[0] !~ /^\w+$/ || $ARGV[1] !~ /^\d+$/ || $ARGV[1] > 65535) {
    die "Usage: $0 apache-name local-port\n"
}
my ($NAME, $PORT) = @ARGV;

my $resp = LWP::UserAgent->new(timeout => 10)->get("http://localhost:$PORT/server-status?auto");
if (!$resp->is_success) {
    die "HTTP error: ".$resp->status_line;
}

my $data = $resp->decoded_content;
my %metrics = map {/^([\w ]+): (\d[\d\.]*)$/ ? (norm($1) => $2) : ()}
            split /\n/, $data;
my $time = 60 * int(time() / 60);
my $host = Yandex::Hostname::hostfqdn() =~ s/[^a-z0-9]/_/gr;
print "one_min.$host.apache.$NAME.server_status_$_ $metrics{$_} $time\n" for sort keys %metrics;


sub norm {
    my $name = shift;
    $name =~ s/([a-z])([A-Z])/${1}_$2/g;
    $name =~ s/\s+/_/g;
    return lc($name);
}

