# Perl module to send reports to the Xymon system monitor
# (formerly known as Hobbit)
#
# Copyright (C) 2008-2012  Christoph Berg <myon@debian.org>
# Copyright (C) 2011-2012  Axel Beckert <abe@debian.org>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

package Hobbit;

use Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(file_to_list_of_regexps file_to_list_of_globs);

use strict;
use warnings;

=head1 NAME

Hobbit.pm -- Perl module to easily write Hobbit/Xymon tests

=head1 SYNOPSIS

 use Hobbit;
 my $bb = new Hobbit('testname');

 if (somethings_is_not_so_good) {
    $bb->color_line('yellow', 'Something is not so good');
 }

 if (somethings_is_really_bad) {
    $bb->color_line('red', 'Something is really bad');
 }

 $bb->send();

=head1 DESCRIPTION

Hobbit.pm is part of the Debian package hobbit-plugins and was written
to gather common tasks needed when writing tests for the Xymon
monitoring system (formerly known as Hobbit).

=cut

# Declare the severity order of the known Hobbit colors
my %color = (
	clear => 0,
	green => 1,
	purple => 2,
	yellow => 3,
	red => 4,
);

# Initialize the Hobbit object
my $gself = {
	hostname => 'hobbit.pm',
	test => 'uninitialized',
};
bless $gself;

=head1 EXPORTABLE HELPER FUNCTIONS

=head2 @regexps = file_to_list_of_regexps($file)

=cut
sub file_to_list_of_regexps($) {
  my @regexps = ();
  my $filename = shift;
  open(my $fh, '<', $filename) or return @regexps;
  while(<$fh>) {
    unless (/^#/) {
      chomp;
      s/\s+$//;
      push(@regexps, qr/^$_$/);
    }
  }
  return @regexps;
}

=head2 @globs = file_to_list_of_globs($file)

=cut
sub file_to_list_of_globs($) {
  my @globlist = ();
  my $filename = shift;
  open(my $fh, '<', $filename) or return @globlist;
  while(<$fh>) {
    unless (/^#/) {
      chomp;
      s/\s+$//;
      push(@globlist, $_);
    }
  }
  return @globlist;
}

=head1 INTERNAL FUNCTIONS

=head2 $max_color = max_color($color1, $color)

Out of two colors, returns the color with the highest severity.

=cut
sub max_color ($$)
{
	my ($a, $b) = @_;
	die "Hobbit::max_color(): No colors given as argument"
	    unless defined($a);
	die "Hobbit::max_color(): Only one color given as argument"
	    unless defined($b);
	die "color $a unknown" unless exists $color{$a};
	die "color $b unknown" unless exists $color{$b};
	return $color{$b} > $color{$a} ? $b : $a;
}

=head1 METHODS

=head2 Constructor: new Hobbit('testname');

=head2 Constructor: new Hobbit({ test => 'testname', ttl => 60, ...});

Creates a new Hobbit object.

=head3 Common use cases

  my $bb = new Hobbit('sometest');
  my $bb = new Hobbit({ test      => 'testname',
                        color     => 'green',
                        hostname  => 'host.example.com',
                        text      => 'Test successful',
                        title     => 'Some Test',
                        ttl       => 60,
                        type      => 'status',
                        dont_moan => 1 });

=head3 Available parameters

=over 3

=item color

The initial color of the test. (Default: "clear")

=item dont_moan

Disable moan() and croak() (see below). Needed if e.g. another used
Perl module throws a lot of warnings but works fine otherwise, etc.

=item hostname

The hostname for which the test should report. (Default:
$ENV{CLIENTHOSTNAME} || $ENV{MACHINEDOTS} || $ENV{MACHINE} ||
'unknown')

=item test

The name of the test, i.e. the name of the column on the hobbit status
web pages. (Mandatory)

=item text

Text which is prepended to generated report. (Default: the empty
string)

=item title

The summary of the test. (Default: "$test OK" respectively "$test NOT ok")

=item ttl

How long the test result is valid before the test state is changed to
purple by the xymon daemon if no newer test results have been received.

The default value is set on the xymon server and is 300 seconds by
default.

Values without unit are interpreted as minutes. Valid units are h for
hours, d for days, and w for weeks. No space between value and unit
allowed.

=item type

Allows one to send messages of other types than "status", e.g. data,
notify, disable, enable, etc.

May not yet work with all of these types properly. Please report bugs
via the Debian Bug Tracking system.

=back

=cut
sub new ($)
{
	my $class = shift;
	my $arg = shift;
	unless (ref $arg) {
		$arg = {
			test => $arg,
		};
	}
	unless ($arg->{test}) {
		print STDERR "$0: test name undefined\n";
		exit 1;
	}
	my $self = {
		type => ($arg->{type} || 'status'),
		color => $arg->{color} || 'clear',
		text => $arg->{text} || '',
		hostname => ($arg->{hostname} || $ENV{CLIENTHOSTNAME} ||
			$ENV{MACHINEDOTS} || $ENV{MACHINE} || "unknown"),
		test => $arg->{test},
		title => $arg->{title},
		ttl => $arg->{ttl},
		dont_moan => $arg->{dont_moan},
	};

	if ($self->{dont_moan}) {
	    $SIG{__WARN__} = \&warn;
	    $SIG{__DIE__}  = \&die;
	}

	$gself = $self;
	bless $self;
}

=head2 Constructor: Hobbit::trends;

=head2 Constructor: Hobbit::trends ('hostname');

Creates a new Hobbit trends object. This is a shorthand for new Hobbit({ type =
'data', test = 'trends', hostname = $hostname, dont_moan => 1 });

=head3 Common use case

  my $trends = Hobbit::trends;
  $trends->print ("[$bb->{test},extralabel.rrd]\n");
  $trends->print ("DS:lambda:GAUGE:600:U:U $value\n");
  $trends->send;

=cut
sub trends
{
	return new Hobbit ({
			hostname => shift,
			test => 'trends',
			type => 'data',
			dont_moan => 1,
		});
}

=head2 add_color('somecolor')

Minutes that a sub test caused the given color state. Adjusts the
overall resulting color accordingly.

=cut
sub add_color ($)
{
	my ($self, $color) = @_;
	$self->{color} = max_color ($self->{color}, $color);
}

=head2 print('some text')

Adds the given text to the end of the current report without changing
the current color.

=cut
sub print ($)
{
	my ($self, $text) = @_;
	$self->{text} .= $text;
}

=head2 sprintf('format', args ...)

Like the print() method, but using sprintf() with format string and arguments.

=cut
sub sprintf ()
{
	my ($self, $format, @args) = @_;
	$self->{text} .= sprintf ($format, @args);
}

=head2 color_print('somecolor', 'some text')

Adds the given text to the end of the current report and minutes that
a sub test caused the given color state. Adjusts the overall resulting
color accordingly.

=cut
sub color_print ($$)
{
	my ($self, $color, $text) = @_;
	$self->add_color ($color);
	$self->print ($text);
}

=head2 color_line('somecolor', 'some text')

Adds the given text to the end of the current report and minutes that
a sub test caused the given color state. Prepends that text with an
accordingly colored Xymon icon and adjusts the overall resulting
color accordingly.

=cut
sub color_line ($$)
{
	my ($self, $color, $text) = @_;
	$self->color_print ($color, "&$color $text");
}

=head2 graph('graphname')

Adds HTML for showing a graph. Xymon itself can only show a single graph per
test (others can be added to the "trends" column). This method works around
that limitation by manually linking to the graph CGI.

=cut
sub graph ($)
{
	my ($self, $graph) = @_;
	my $host = $self->{hostname} || '';
	my $end = time;
	my $start = $end - 172800; # 2 days
	my ($graph_sh, $title, $skin);
	if ($ENV{XYMON} or not $ENV{BB}) { # xymon mode
		$graph_sh = 'showgraph.sh';
		$title = 'xymongraph';
		$skin = $ENV{XYMONSKIN} || '/xymon/gifs/static';
		#my $cgi = $ENV{BBSERVERCGIURL} || $ENV{CGIBINURL} || "/hobbit-cgi";
	} else { # hobbit mode
		$graph_sh = 'hobbitgraph.sh';
		$title = 'hobbitgraph';
		$skin = $ENV{BBSKIN} || '/hobbit/gifs/static';
	}

	$self->print ("<p><table summary=\"$graph Graph\"><tr><td>");
	$self->print ("<a href=\"$graph_sh?host=$host&amp;service=$graph&amp;graph_width=576&amp;graph_height=120&amp;disp=$host&amp;nostale&amp;color=green&amp;graph_start=$start&amp;graph_end=$end&amp;action=menu\">");
	$self->print ("<img border=\"0\" src=\"$graph_sh?host=$host&amp;service=$graph&amp;graph_width=576&amp;graph_height=120&amp;disp=$host&amp;nostale&amp;color=green&amp;graph_start=$start&amp;graph_end=$end&amp;graph=hourly&amp;action=view\" ALT=\"$title $graph\">");
	$self->print ("</a></td><td> ");
	$self->print ("<td align=\"left\" valign=\"top\"> ");
	$self->print ("<a href=\"$graph_sh?host=$host&amp;service=$graph&amp;graph_width=576&amp;graph_height=120&amp;disp=$host&amp;nostale&amp;color=green&amp;graph_start=$start&amp;graph_end=$end&amp;graph=custom&amp;action=selzoom\">");
	$self->print ("<img src=\"$skin/zoom.gif\" alt=\"Zoom graph\" style=\"padding: 3px\" border=\"0\">");
	$self->print ("</a> </td></tr></table></p>\n");
}

=head2 send()

Sends the report to the xymon server.

=cut
sub send ()
{
	my $self = shift;
	if ($self->{ttl} and
	    $self->{ttl} =~ /^\d+/ and # there might be an h/d/w suffix
	    $self->{type} eq 'status') {
	    $self->{type} = "$self->{type}+$self->{ttl}";
	}
	my $report = "$self->{type} $self->{hostname}.$self->{test}";
	if ($self->{type} =~ m/^status/) {
		my $date = scalar localtime;
		my $title = '';
		if ($self->{color} eq 'green') {
			$title = "$self->{test} OK";
		} elsif ($self->{color} eq 'yellow' or $self->{color} eq 'red') {
			$title = "$self->{test} NOT ok";
		}
		$title = ' - ' . ($self->{title} ? $self->{title} : $title)
			if ($self->{title} or $title);
		$report .= " $self->{color} $date$title";
	}
	$report .= "\n$self->{text}";
	$report .= "\n" unless ($report =~ /\n\n$/);
	if ($ENV{XYMON} and $ENV{XYMSRV}) {
		open F, '|-', "$ENV{XYMON} $ENV{XYMSRV} @";
		print F $report;
		close F;
	} elsif ($ENV{BB} and $ENV{BBDISP}) {
		open F, '|-', "$ENV{BB} $ENV{BBDISP} @";
		print F $report;
		close F;
	} else {
		print $report;
	}
}

=head1 FUNCTIONS

=head2 grep(I<tag>)

Run a xymongrep (bbhostgrep) query and return an array reference of hashes with
keys B<ip> (string), B<hostname> (string), and B<tags> (array reference).

  my $list = Hobbit::grep('foobar');
  foreach my $host (@$list) {
    print "$host->{ip} $host->{hostname}\n";
  }

=cut
sub grep ($)
{
	my ($tag) = @_;
	my @greps = qw(/usr/lib/xymon/client/bin/xymongrep /usr/lib/hobbit/client/bin/bbhostgrep);
	my $grep = (grep { -x $_ } @greps)[0];
	my $list;
	open GREP, '-|', "$grep $tag";
	while (<GREP>) {
		if (/^(\S+) (\S+) # (.*)/) {
			my ($ip, $hostname, $tags) = ($1, $2, $3);
			my @tags = split / /, $tags;
			push @$list, { ip => $1, hostname => $2, tags => \@tags };
		}
	}
	close GREP;
	return $list;
}

=head1 INTERNAL METHODS

=head2 moan()

If the check issues a Perl warning, this warning is added to the
report with color state "yellow".

Set dont_moan to 1 to disable this feature.

=cut
sub moan ($)
{
	my $msg = shift;
	if (ref($msg) eq 'SCALAR') { $msg = $$msg; }
	my $date = scalar localtime;
	print STDERR "$date $0 $gself->{hostname}.$gself->{test}: $msg\n";
	$gself->color_line ('yellow', "Warning: $msg\n");
}

=head2 croak()

If the check issues a Perl error, this error is added to the
report with color state "red".

Set dont_moan to 1 to disable this feature.

=cut
sub croak ($)
{
	my $msg = shift;
	if (ref($msg) eq 'SCALAR') { $msg = $$msg; }
	my $date = scalar localtime;
	print STDERR "$date $0 $gself->{hostname}.$gself->{test}: $msg\n";
	$gself->color_line ('red', "Error: $msg\n");
	$gself->send();
	exit 1;
}

$SIG{__WARN__} = \&moan;
$SIG{__DIE__} = \&croak;

1;

=head1 AUTHORS AND COPYRIGHT

 Copyright (C) 2008-2011  Christoph Berg <myon@debian.org>
 Copyright (C) 2011       Axel Beckert <abe@debian.org>

=head1 SEE ALSO

L<http://www.xymon.org/> L<bb(5)>, L<xymon(1)>
