#  $Header: emrepresp.pl 18-may-2007.09:58:42 tsubrama Exp $
#
# Copyright (c) 2001, 2007, Oracle. All rights reserved.  
#
#    NAME
#      emrepresp.pl - <one-line expansion of the name>
#
#    DESCRIPTION
#      It connects to a database, executes a user-defined SQL
#      and reports success/failure and response time.
#
#    NOTES
#      <other useful comments, qualifications, etc.>
#
#    MODIFIED   (MM/DD/YY)
#      tsubrama 05/17/07 - fix for referring emrepdown.pl path and remvoing double quotes in subject,msg
#      aholser  10/21/03 - remove tracing pwd 
#      aholser  10/18/03 - 
#      aholser  08/20/03 - add metric eval job check
#      aholser  04/15/03 - 
#      aholser  03/13/03 - use perl script for mail
#      aholser  11/23/02 - use connectdescriptor
#      aholser  07/15/02 - oob notification
#      aholser  07/12/02 - aholser_bug-2445264_main
#      aholser  07/11/02 - Creation
#

use strict;
use Oraperl;
use Time::HiRes;

require "emd_common.pl";
require "semd_common.pl";

my $targetname = "";
my $db_connect = "";
EMD_PERL_DEBUG("Connectdescriptor $ENV{CONNECTDESCRIPTOR}");
if ( $ENV{CONNECTDESCRIPTOR} ne "" )
{
  $db_connect = $ENV{EM_REPOS_USER} . "/" . $ENV{EM_REPOS_PWD} . "@" . $ENV{CONNECTDESCRIPTOR};
  $targetname = $ENV{EM_REPOS_USER}."test";
}
else
{
  $db_connect = $ENV{EM_REPOS_USER} . "/" . $ENV{EM_REPOS_PWD} . "@" . $ENV{EM_TARGET_ADDRESS};
  $targetname = $ENV{SID}.$ENV{PORT};
}

my $start_time = Time::HiRes::time;

my $lda;

my $targetname = $ENV{SID}.$ENV{PORT};
my $fn = get_tmp_filename ($targetname, "emrepresp");
EMD_PERL_DEBUG("$targetname, $fn");

unless ( $lda = &ora_login ('', $db_connect, '') )
{
   EMD_PERL_DEBUG("ora_login");
   print "em_result=0|Enterprise Manager Repository database is down. Error: $ora_errno\n$db_connect";
   processfailure("Could not connect to Enterprise Manager Repository database: $ora_errno");
   exit 0;
}

register_metric_call($lda);

my $sql = "select count(distinct host_url) from mgmt_failover_table where sysdate-last_time_stamp < 300";
my $sql1 = "SELECT
           (SELECT count(broken) FROM user_jobs
              WHERE what LIKE('EMD_COLLECTION.%')
              AND broken = 'Y'),
           (SELECT MIN(SYSDATE-next_date) FROM user_jobs
              WHERE what LIKE('EMD_COLLECTION.%')) FROM DUAL";

EMD_PERL_DEBUG("sql is: $sql");
EMD_PERL_DEBUG("sql1 is: $sql1");

my $cur;
my $cur1;

unless ($cur = &ora_open ($lda, $sql))
{
   EMD_PERL_DEBUG("ora_open");
   print "em_result=0|Enterprise Manager Repository database is down. Could not open cursor. Error: $ora_errno\n";
   processfailure("Could not open cursor: $ora_errno");
   exit 0;
}

my @fetch_row;
my @fetch_row1;

unless (@fetch_row = &ora_fetch($cur))
{
   EMD_PERL_DEBUG("ora_fetch");
   print "em_result=0|Enterprise Manager Repository database is down. Could not retrieve data. Error: $ora_errno\n";
   processfailure("Could not retrieve data: $ora_errno");
   cleanup();
   exit 0;
}

my $oms_count = 0;
$oms_count = $fetch_row[0];

if($oms_count == 0)
{
   EMD_PERL_DEBUG("No active OMSs ");
   print ("em_result=$oms_count|No active Management Services were found\n");
   processfailure("No active Management Services were found");
   cleanup();
   exit 0;
}
EMD_PERL_DEBUG("Active OMSs=$oms_count");

unless ($cur1 = &ora_open ($lda, $sql1))
{
   EMD_PERL_DEBUG("ora_open");
   print "em_result=0|Enterprise Manager Repository database is down. Could not open cursor. Error: $ora_errno\n";
   processfailure("Could not open cursor: $ora_errno");
   cleanup();
   exit 0;
}
unless (@fetch_row1 = &ora_fetch($cur1))
{
   EMD_PERL_DEBUG("ora_fetch");
   print "em_result=0|Enterprise Manager Repository database is down. Could not retrieve data. Error: $ora_errno\n";
   processfailure("Could not retrieve data: $ora_errno");
   cleanup1();
   exit 0;
}

my $jobUpDown;
my $schedule;
$jobUpDown = $fetch_row1[0];
$schedule = $fetch_row1[1];

if($jobUpDown > 0)
{
   EMD_PERL_DEBUG("No active OMSs ");
   print ("em_result=0|Management System metrics gathering job is broken.\n");
   processfailure("Management System metrics gathering job is broken");
   cleanup1();
   exit 0;
}

if(($schedule > 1/12) || ($schedule < -365))
{
   EMD_PERL_DEBUG("No active OMSs ");
   print ("em_result=0|Management System metrics gathering job s broken - schedule is invalid.\n");
   processfailure("Management System metrics gathering job is broken - schedule is invalid");
   cleanup1();
   exit 0;
}

# remove the old fail file if it exists
# unlink("emrepfail.lk");
unlink($fn);
print ("em_result=$oms_count|$oms_count Management Services are active\n");

cleanup1();

exit 0;

sub cleanup1
{
   &ora_close($cur) || warn "ora_close($cur): $ora_errno: $ora_errstr\n";
   cleanup();
}

sub cleanup
{
   &ora_logoff($lda) || warn "ora_logoff($lda): $ora_errno: $ora_errstr\n";

   my $end_time = Time::HiRes::time;
   my $logon_time = ($end_time - $start_time) * 1000;
   EMD_PERL_DEBUG("emrepresp: Time in emrepresp: $logon_time" );
}

sub processfailure
{
   my $mailscript = "emrepdown.pl";
   my $exists = -e $fn;
   my $mailscriptexists = -e $mailscript;
   my $accesstime = -M $fn;
   my $interval = 1/24;
   my $home = $ENV{ORACLE_HOME};
   EMD_PERL_DEBUG("exists=$exists, accesstime=$accesstime, interval=$interval mailscriptexists=$mailscriptexists" );

   # Email is sent if the error is new ($fn doesn't exist) or more than one hour has elapsed.
   if(($exists < 1) || ($accesstime > $interval))
   {
      if($exists > 0)
      {
         unlink($fn);
      }

      open(FILE, ">".$fn);
      print FILE scalar localtime;
      close(FILE);
      # if emrepdown.pl is not in our path, try to locate it at install and development locations
      # with oracle_home.  if we can't find it, log an error and exit
      if($mailscriptexists < 1)
      {
         if( $home ne "" )
         {
            $mailscript =  "$home/bin/emrepdown.pl";
            $mailscriptexists = -e $mailscript;
            if($mailscriptexists < 1)
            {
               $mailscript =  "$home/emagent/sysman/admin/scripts/emrepdown.pl";
               $mailscriptexists = -e $mailscript;
               if($mailscriptexists < 1)
               {
                  EMD_PERL_DEBUG("Can't locate emrepdown.pl script: ORACLE_HOME=$home - exiting");
                  return;
               }
            }
         }
      }

      {
         local @ARGV;

         my ($message) = @_;

         $ARGV[0] = $message;
         $ARGV[1] = "Severe Enterprise Manager problem";

         EMD_PERL_ERROR("emrepresp: processfailure $mailscript, Message:$ARGV[0], Subject:$ARGV[1]");

         #since ARGV is local variable,it's values are directly accessible in the mailscript.
         #The do() method executes the contents of the file as a Perl script.
         do($mailscript);

      }

      close(FH);
      return;
  }
  EMD_PERL_DEBUG("processfailure $fn already exists");
}

