#!/usr/bin/env perl
#
# 2014/05/15 Gabriel Moreau <Gabriel.Moreau@univ-grenoble-alpes.fr>
# 2017/06/22 Gabriel Moreau - big update
#
# velvice.cgi
# Copyright (C) 2014-2018, LEGI UMR 5519 / CNRS UGA G-INP, Grenoble, France
#
# Need NagiosStatus http://exchange.nagios.org/directory/Addons/APIs/Perl/NagiosStatus-2Epm/details
# Possible command http://old.nagios.org/developerinfo/externalcommands/commandlist.php
#
# apt-get install libnagios-object-perl libhtml-parser-perl perl-modules liburi-encode-perl libcolor-calc-perl libyaml-syck-perl

use strict;
use warnings;
use version; our $VERSION = version->declare('0.5.1');

use CGI;
use HTML::Entities ();
use Nagios::StatusLog;
use URI::Encode qw(uri_encode uri_decode);
use Color::Calc ();
use YAML::Syck;

my $config = {};
$config = YAML::Syck::LoadFile('/etc/nagios3/velvice.yml') if -e '/etc/nagios3/velvice.yml';
$config->{'status-file'}         ||= '/var/cache/nagios3/status.dat';
$config->{'nagios-cmd'}          ||= '/var/lib/nagios3/rw/nagios.cmd';
$config->{'portal-url'}          ||= 'http://localhost/nagios3/';
$config->{'status-cgi'}          ||= 'http://localhost/cgi-bin/nagios3/status.cgi';
$config->{'mapping'}             ||= {};
$config->{'downtime'}            ||= {};
$config->{'downtime'}{'min'}     ||= 3;
$config->{'downtime'}{'max'}     ||= 50;
$config->{'downtime'}{'factor'}  ||= 0.7;
$config->{'service'}             ||= {};

my $query = CGI->new();

my $log = Nagios::StatusLog->new(
   Filename => $config->{'status-file'},
   Version  => 3.0
   );

my $check = uri_decode($query->param('check'));

sub hostmapping {
   my $host = shift;

   return exists $config->{'mapping'}{$host} ? $config->{'mapping'}{$host} : $host;
   }

sub downtime {
   my ($time_change) = @_;

   my $now = time;
   return sprintf '%.1f', ($now - $time_change) / (60 * 3600);
   }

sub alertcolor {
   my ($color, $downtime) = @_;

   $downtime = $downtime - $config->{'downtime'}{'min'}; # same color first days
   $downtime = $config->{'downtime'}{'max'} if $downtime > $config->{'downtime'}{'max'}; # max 50 days for color
   $downtime =  0 if $downtime <  0;

   my $factor = ($downtime * $config->{'downtime'}{'factor'}) / $config->{'downtime'}{'max'};
   return Color::Calc::color_light_html($color, $factor);
   }

my %hostdown;
my @serviceproblems;
my %hostcount;
my @futurecheck;
HOST:
for my $host (sort $log->list_hosts()) {
   my $host_stat = $log->host($host);

   if ($host_stat->status eq 'DOWN') {TESTIF:{
      for my $srv ($log->list_services_on_host($host)) {
         last TESTIF if $log->service($host, $srv)->status eq 'OK' or $log->service($host, $srv)->status eq 'PENDING';
         }

      $hostdown{$host} = $host_stat;
      next HOST;
      }}

   for my $srv ($log->list_services_on_host($host)) {
      if ($log->service($host, $srv)->status ne 'OK') {
         push @serviceproblems, $log->service($host, $srv);
         $hostcount{$host}++;
         }
      }
   }

my $now = time;
my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime $now;
$year += 1900;
$mon++;
my $date = sprintf '%04i-%02i-%02i %02i:%02i', $year, $mon, $mday, $hour, $min;

my $htmlpage = <<"ENDH";
Content-Type: text/html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>Nagios  Velvice</title>
</head>
<style type="text/css">
/* https://stackoverflow.com/questions/14920401/how-to-simulate-hfill-with-html-and-css */
h1 ul {
   display: flex;
   justify-content: space-between;
   }
h1 li {
   display: inline;
   }
td.bold {
   font-weight: bold;
   }
</style>
<body>
<h1>
 <ul>
   <li>Nagios Velvice Alert Panel : <a href="$config->{'portal-url'}">Core Server</a></li>
   <li><small>(<a href='velvice.cgi'>UPDATE</a> - $date)</small></li>
 </ul>
</h1>
ENDH

my %service_name  = ();
my %service_level = ();
for my $srv (@serviceproblems) {
   $service_name{$srv->service_description}++;
   $service_level{$srv->status}++;
   }

if (scalar @serviceproblems == 0) {
   $htmlpage .= "<p>No alert to recheck.</p>\n";
   }
else {

   $htmlpage .= "<p>Alert to recheck - Level:\n";
   $htmlpage .= join ",\n",
      ' <a href="velvice.cgi?check=all">ALL</a><small>(' . scalar(@serviceproblems) . ')</small>',
      map(" <a href='velvice.cgi?check=" . lc(uri_encode($_)) . "'>$_</a>($service_level{$_})", sort keys %service_level);
   $htmlpage .= ".\n";
   $htmlpage .= " <br />\n";
   $htmlpage .= " Service:\n";
   $htmlpage .= join ",\n", map(" <a href='velvice.cgi?check=" . lc(uri_encode($_)) . "'>$_</a><small>($service_name{$_})</small>", sort keys %service_name);
   $htmlpage .= ".\n";
   $htmlpage .= "</p>\n";

   my $nagios_cmd;
   open $nagios_cmd, '>>', $config->{'nagios-cmd'} or die "Can't open file filename: $!";

#   my @oomkiller     = ();
   my %sshdown       = ();
#   my @aptuptodate   = ();
   my %cmdafter      = ();
   my $after;

   my $current_host  = '';
   $htmlpage .= "<table border=\"1\">\n";
   for my $srv (@serviceproblems) {
      my $hostname = $srv->host_name;
      my $service  = $srv->service_description;
      my $status   = $srv->status;
      my $downtime = downtime($srv->last_state_change);
      my $output   = HTML::Entities::encode($srv->plugin_output);
      $output =~ s/^[A-Z_\s]+?[:-]//;

      my $color = $status eq 'CRITICAL' ? '#F88888' : '#FFFF00';
      $color = alertcolor($color, $downtime);
      $htmlpage .= " <tr style='background:$color;'>\n";
      if ($hostname ne $current_host) {
         $current_host = $hostname;
         $htmlpage .= "  <td rowspan='$hostcount{$hostname}' style='vertical-align:middle;'><a href=\"$config->{'status-cgi'}?host=$hostname\">$hostname</a></td>\n";
         }

      my $bold;
      for my $srv_name (keys %{$config->{'service'}}) {
         my $srv_regex = $config->{'service'}{$srv_name}{'regex'};
         $bold++ if $service =~ m/$srv_regex/ and $config->{'service'}{$srv_name}{'style'} eq 'bold';
         }
      $htmlpage .= $bold ? '  <td class="bold">' : '  <td>';
      $htmlpage .= "$service</td>\n";

      $htmlpage .= "  <td>$status</td>\n";
      $htmlpage .= "  <td style='max-width:60%;'><small>$output";

      $sshdown{$hostname}++ if $service eq 'SSH';

      if (($check =~ m/all/i)
            or ($check =~ m/^$service$/i)
            or ($check =~ m/critical/i and $status eq 'CRITICAL')
            or ($check =~ m/warning/i  and $status eq 'WARNING')
            or ($check =~ m/pending/i  and $status eq 'PENDING')
            ) {
         $now++;
         my $interval = $srv->next_check() - $srv->last_check() || 300;
         $interval =  240 if $interval <  240;
         $interval = 3000 if $interval > 3000;
         my $future = $now + 20 + int(rand($interval - 20)); # 5 * 60 = 300

         $htmlpage .= " -- <b>CHECK</b> [$now/" . ($future - $now) . "]";
         printf $nagios_cmd "[%lu] SCHEDULE_FORCED_SVC_CHECK;%s;%s;%lu\n", $now, $hostname, $service, $now;
         # delay future command
         push @futurecheck, sprintf "[%lu] SCHEDULE_FORCED_SVC_CHECK;%s;%s;%lu", $future, $hostname, $service, $future;
         }

#      push @aptuptodate, $hostname if $service eq 'APT UPTODATE';
#      push @oomkiller,   $hostname if $service eq 'OOM Killer' and $status ne 'PENDING';
      for my $srv_name (keys %{$config->{'service'}}) {
         my $srv_regex  = $config->{'service'}{$srv_name}{'regex'};
         my $srv_status = $config->{'service'}{$srv_name}{'status'};
         if ($service =~ m/$srv_regex/ and ($srv_status eq 'ALL' or $status =~ m/$srv_status/)) {
            $cmdafter{$srv_name} ||= [];
            push @{$cmdafter{$srv_name}}, $hostname;
            $after++;
            }
         }

      $htmlpage .= "</small></td>\n";
      $htmlpage .= "  <td style='text-align:right;'>$downtime days</td>\n";
      $htmlpage .= " </tr>\n";
      }

   $htmlpage .= "</table>\n";
   close $nagios_cmd;

   if (%hostdown) {
      $htmlpage .= "<br />\n";
      $htmlpage .= "<table border='1'>\n";
      for my $host (sort keys %hostdown) {
         my $host_stat = $hostdown{$host};
         my $hostname = $host_stat->host_name;
         my $downtime = downtime($host_stat->last_state_change);
         my $color = alertcolor('#F88888', $downtime);
         $htmlpage .= " <tr style='background:$color'>\n";
         $htmlpage .= "  <td><a href=\"$config->{'status-cgi'}?host=$hostname\">$hostname</a></td>\n";
         my @host_service;
         for my $srv ($log->list_services_on_host($host)) {
            push @host_service, $log->service($host, $srv)->service_description;
            }
         $htmlpage .= "  <td><small>" . join(', ', @host_service) . "</small></td>\n";
         $htmlpage .= "  <td style='text-align:right;'>$downtime days</td>\n";
         $htmlpage .= " </tr>\n";
         }
      $htmlpage .= "</table>\n";
      }

#   if (@oomkiller or @aptuptodate or $after) {
   if ($after) {
      require Nagios::Object::Config;
      my $parser = Nagios::Object::Config->new();
      $parser->parse("/var/cache/nagios3/objects.cache");

      for my $srv_name (keys %cmdafter) {
         my @action = grep !exists $sshdown{$_}, @{$cmdafter{$srv_name}};
         if (@action) {
            my $srv_title = $config->{'service'}{$srv_name}{'title'} || "Action: $srv_name";
            $htmlpage .= "<h2>$srv_title</h2>\n";
            $htmlpage .= "<pre>\n";
            my $remote_action = $config->{'service'}{$srv_name}{'command'};
            $remote_action = $config->{'service'}{$srv_name}{'command-one'} if @action == 1;
            my @hosts;
            for my $host (@action) {
               my $object = $parser->find_object("$host", "Nagios::Host");
               push @hosts, hostmapping($object->address =~ s/\..*$//r);
               }
            my $hosts_list = join ' ', @hosts;
            $htmlpage .= ' ' . $remote_action =~ s{\%m}{$hosts_list}r;
            $htmlpage .= "</pre>\n";
            }
         }

#      @oomkiller = grep !exists $sshdown{$_}, @oomkiller;
#      if (@oomkiller) {
#         $htmlpage .= "<h2>OOM Killer</h2>\n";
#         $htmlpage .= "<pre>\n";
#         if (@oomkiller == 1) {
#            $htmlpage .= " ssh";
#            }
#         else {
#            $htmlpage .= " tssh -c 'sudo rm /var/lib/nagios3/nagios_oom_killer.log'";
#            }
#         for my $host (@oomkiller) {
#            my $object = $parser->find_object("$host", "Nagios::Host");
#            $htmlpage .= ' ' . hostmapping($object->address =~ s/\..*$//r);
#            }
#         $htmlpage .= " 'sudo rm /var/lib/nagios3/nagios_oom_killer.log'" if (@oomkiller == 1);
#         $htmlpage .= "</pre>\n";
#         }
#
#      @aptuptodate = grep !exists $sshdown{$_}, @aptuptodate;
#      if (@aptuptodate) {
#         $htmlpage .= "<h2>APT UPTODATE</h2>\n";
#         $htmlpage .= "<pre>\n";
#         if (@aptuptodate == 1) {
#            $htmlpage .= " ssh";
#            }
#         else {
#            $htmlpage .= " tssh";
#            }
#         for my $host (@aptuptodate) {
#            my $object = $parser->find_object("$host", "Nagios::Host");
#            $htmlpage .= ' ' . hostmapping($object->address =~ s/\..*$//r);
#            }
#         $htmlpage .= "</pre>\n";
#         }
      }
   }

$htmlpage .= <<'ENDH';
</body>
</html>
ENDH

print $htmlpage;

# delay future check
if (@futurecheck) {
   sleep 2;
   my $nagios_cmd;
   open $nagios_cmd, '>>', $config->{'nagios-cmd'} or die "Can't open file filename: $!";
   print $nagios_cmd "$_\n" for @futurecheck;
   close $nagios_cmd;
   }

__END__


=head1 NAME

velvice.cgi - nagios velvice alert panel


=head1 DESCRIPTION

Nagios VELVICE is an acronym for "Nagios leVEL serVICE status".
Homepage: http://servforge.legi.grenoble-inp.fr/projects/soft-trokata/wiki/SoftWare/NagiosVelvice

=head1 AUTHORS

Written by Gabriel Moreau - Grenoble - France


=head1 LICENSE AND COPYRIGHT

Licence GNU GPL version 2 or later and Perl equivalent

Copyright (C) 2014-2018 Gabriel Moreau <Gabriel.Moreau(A)univ-grenoble-alpes.fr>.
