#!/usr/bin/perl

## Script to notify if the alert queue backs up.  
## Alerts using the gritch subsystem.

use strict;
use NOCpulse::Config;
use NOCpulse::Gritch;
use NOCpulse::NOCpulseini;
use Pod::Usage;

pod2usage(0) unless $ARGV[0];

my $CFG=NOCpulse::Config->new;

if (not $CFG) {
        print "Error: /etc/NOCpulse.ini do not exist. Enable monitoring first.\n";
        exit(1);
}

my $recipient=$CFG->get('notification','notif_emergency_email');

my $queue_name=$ARGV[0];
my $WARNING_QUEUE_SIZE  = $ARGV[1];
my $CRITICAL_QUEUE_SIZE = $ARGV[2];

use constant TIME_INTERVAL => 600; #notify every ten minutes or
use constant COUNT_INTERVAL => 5;  #notify every 5 occurrences

#configure gritching
my $tmpdir=$CFG->get('notification','tmp_dir');
my $gritchdb  = "$tmpdir/gritch.db";
my $soapbox = new NOCpulse::Gritch($gritchdb);
$soapbox->recipient($recipient);
$soapbox->timeinterval(TIME_INTERVAL);
$soapbox->countinterval(COUNT_INTERVAL);
$NOCpulse::Gritch::USE_SENDMAIL = 1;

my $queue = { ALERTS   => 'alert_queue_dir',
              ACKS     => 'ack_queue_dir',
              REQUESTS => 'request_queue_dir' };

# Locate queue directory
my $QUEUE_DIR = $CFG->get('notification', $queue->{$queue_name});
chdir $QUEUE_DIR || NOCpulse::NOCpulseini->bailout("unable to find queue directory $QUEUE_DIR\n");
my @files=glob("*");

my $queue_size=scalar(@files);

if ($queue_size >= $CRITICAL_QUEUE_SIZE) {

  my $body="$queue_name queue size is $queue_size at "  
     . scalar(localtime(time));
  print "$body\n";
  $soapbox->gritch('Possible Notification Meltdown!!!',$body);
}

=pod

=head1 NAME

monitor-queue - monitor the queues from Spacewalk monitoring.

=head1 SYNOPSIS

monitor-queue QUEUE WARNING_QUEUE_SIZE CRITICAL_QUEUE_SIZE

=head1 DESCRIPTION

This script is called by cron to monitor the alert, acknowledgement, and request queues. 
You should not execute it manually unless you know what are you doing. For standalone usage is intended
executable queue_remote_check.pl

This works independent from the notification system and uses SMTP to deliver warning messages.

=head1 OPTIONS

QUEUE
        Name of notification queue. Should be ALERTS, ACKS or REQUESTS.

WARNING_QUEUE_SIZE
        Size of queue, which should produce warning. In cron we use 50.
        Currently nothing happen, if queue reach this limit.

CRITICAL_QUEUE_SIZE
        Size of queue, which is critical. In cron we use 100.
        If queue reach this limit, email is sent with subject
        'Possible Notification Meltdown!!!'
        Email address is taken from NOCpulse.ini, from section notification, variable notif_emergency_email.

=head1 SEE ALSO

queue_remote_check.pl(3)

=head1 COPYRIGHT AND LICENSE

Copyright (c) 2010 Red Hat, Inc.
Released under GNU General Public License, version 2 (GPLv2).

=cut

