#!/usr/bin/perl
use strict;
use warnings;

my $rsyslog_stats = "/var/log/rsyslog-stats.log";

my $action_re = qr((?:main Q|action \d+ queue));
my $error_re = qr((?:full|discarded));
my $start_re = qr(main Q:);

my $command=$ARGV[0];
if (!$command) {
  print "Usage: $0 {get_queues_status|get_hamster_metrics}\n";
  exit 1;
}
open(my $file, '-|', "tac $rsyslog_stats");

my $started = 0;
my %actions;
while (<$file>) {
  chomp;
  last if $started && $_ =~ $start_re;
  $started = 1 if !$started && $_ =~ $start_re;
  next if !$started;
  
  my ($action, $metrics) = ($_ =~ /: ([^:]+): (.*)$/);
  next if !$action || !$metrics;
  my %metrics_hash;
  map { my @lst = split /=/; $metrics_hash{$lst[0]} = $lst[1]; } split(/ /, $metrics);
  $actions{$action} = \%metrics_hash;
}

#Tue Sep 24 20:06:08 2013: action 1 queue[DA]: size=0 enqueued=0 full=0 discarded.full=0 discarded.nf=0 maxqsize=0 
#Tue Sep 24 20:06:08 2013: action 1 queue: size=0 enqueued=56826254 full=0 discarded.full=0 discarded.nf=0 maxqsize=2037 
#Tue Sep 24 20:06:08 2013: action 2 queue[DA]: size=0 enqueued=0 full=0 discarded.full=0 discarded.nf=0 maxqsize=0 
#Tue Sep 24 20:06:08 2013: action 2 queue: size=0 enqueued=56826254 full=0 discarded.full=0 discarded.nf=0 maxqsize=1909 
#Tue Sep 24 20:06:08 2013: main Q[DA]: size=0 enqueued=0 full=0 discarded.full=0 discarded.nf=0 maxqsize=0 
#Tue Sep 24 20:06:08 2013: main Q: size=0 enqueued=56826254 full=0 discarded.full=0 discarded.nf=0 maxqsize=1024

if ($command eq "get_queues_status") {
  my %err;
  while (my ($k,$v) = each %actions) {
    next if $k !~ $action_re;
    while (my ($kk, $vv) = each %$v) {
      next if !($kk =~ $error_re && $vv > 0);
      $err{$k} = 1;
    }
  }
  my $out = (scalar(keys(%err))) ? "2; rsyslog queues full: ".join('//',keys(%err)) : "0;OK";
  print "$out\n";
}
elsif ($command eq "get_hamster_metrics") {
  # {[graph_name_1=param11:val11 param12:val12][graph_name_2=param21:val21 param22:val22]}
  print '{';
  while (my ($k,$v) = each %actions) {
    next if ($k !~ $action_re);
    print '[';
    $k =~ s/[^\w]/_/g; $k =~ s/_$//; $k = lc $k;
    print "rsyslog_$k=";
    my $str=""; while (my ($kk, $vv) = each %$v) { $str .= "$kk:$vv "; } $str =~ s/ $//; print "$str";
    print ']';
  }
  print '}';
}
