package Health::Switch;
#<copyright>
# ----------------------------------------------------------
# Sun Proprietary/Confidential Code
# Copyright 2001, Sun Microsystems, Inc. All rights reserved.
# ----------------------------------------------------------
#</copyright>

#  $Name:  $ 
#  $Id: Switch.pm,v 1.24 2002/07/31 21:52:34 ccadieux Exp $


use base 'Health';
use NWS::Switch;
use Ilist;
use Message;
use Report;
use Catalog;
use Events;
use strict;
use Debug;

sub revision {'$Revision: 1.24 $'}

sub new {
  my($hm, $pdm) = @_;

  my($self) = {pdm => $pdm};
  bless ($self, 'Health::Switch');

# Specify each callback
#                            HM  Callback,  Filters
  $pdm->reportRequest($self, 'all_logic' , {category => Report::CAT_SWITCH});
  return $self;
}

#####################################################

sub all_logic {
  my($hm, $report) = @_;
  my($pdm) = $hm->{pdm};
  my($ev, $ed, $pertains, $x ,$y, $contain, $sd);
  my($orep, $key);
  my($rep)     = $report->content;
  my($oreport) = PDM->getOldReport($report->fileKey);
  my($ip)      = $report->id('ip');
  my($name)    = $report->name;
  my $wwn      = $report->id('deviceName');
  my($id)      = $report->id('display');
  my($log)     = $report->log();
  my $mgmtLevel = $report->value('id.mgmtLevel') || 'D';
  if (!$wwn) {
     Debug->err(ERROR => "This Switch \"$name\" ($ip) cannot be identified");
     return;
  }

  CIM->version("1.1");
  $DB::single = 1;

  return if ($hm->connectionEvent($wwn, $report, {method => 2} ));
  my($audit); 
  my($freq) = System->get_renv()->{audit_freq} || 7;
  if (!$oreport || ($audit = Timer->isXdays("Audit$wwn", $freq)) eq "YES" ) {  # new t300 or audit time.
     my($etype) = $audit ? "switch.AuditEvent" : "switch.DiscoveryEvent";
     my($title) = $audit ? "Auditing a":"Discovered a new";
     my($dt)    = "A" if (!$audit);
     $ev = CIM::Instance->new('NWS_Event', [
                  [ EventType   => $etype ],
                  [ EventId     => $pdm->getEventSequence  ],
                  [ Target      => $wwn ],
                  [ TargetName  => $id],
                  [ SourceIP    => $ip  ],
                  [ MgmtLevel   => $mgmtLevel],
                  [ Description => "$title Switch called $id"],
                         ]);

     $sd = Events->sourceDetector({ event => $ev , host => 1, rep => $rep});
      
     my($p) = NWS::Switch->newSystem($rep);

     $pertains = CIM::Instance->new('NWS_EventPertainsToSystem', [
                  [ Event       => $ev  ],
                  [ Element     => $p->[0] ],
                  [ DiscoveryType => $dt],
                    ]);

     my($monitors) = CIM::Instance->new('NWS_AgentMonitors', [
                  [ Agent       => $sd->[0]  ],
                  [ Element     => $p->[0] ],
                    ]);

     $ed = Message->new( { id        => $report->id,
                            instances => [$ev, @$sd,  @$p, $monitors, $pertains ],
                            severity  => Message::SEVERITY_NORMAL });

     $pdm->saveMessage($ed);
     if ($audit) {  # dump stats.

        $ev = CIM::Instance->new('NWS_Event', [
                  [ EventType   => 'switch.Statistics'  ],
                  [ EventId     => $pdm->getEventSequence  ],
                  [ Target      => $wwn ],
                  [ TargetName  => $id  ],
                  [ SourceIP    => $ip  ],
                  [ MgmtLevel   => $mgmtLevel],
                  [ Description => "Statistics about Switch $id :"],
                  [ Data        => Util->nnl($rep->toStringP('port.\d+.stats'))],
                         ]);

        $sd = Events->sourceDetector({ event => $ev });

        my($system_key) = CIM::Key->new( ['NWS_System', 
                    'Name'            =>$rep->get('id.wwn'), 
                    CreationClassName => 'NWS_System']);

        $pertains = CIM::Instance->new('NWS_EventPertainsToSystem', [
                  [ Event       => $ev  ],
                  [ Element     => $system_key ],
                    ]);

        $ed = Message->new( { id        => $report->id,
                            instances => [$ev, @$sd, $pertains ],
                            severity  => Message::SEVERITY_NORMAL});

        $pdm->saveMessage($ed);

     }
  }
  $orep = $oreport->content() if ($oreport);


  foreach my $el ('fan.1', 'fan.2', 'power', 'temp') {
      $hm->alarm($report, $orep, "SWITCH", "chassis.$el", "status", $id, $id, $wwn, "$el.status");
      #my $s2 = $orep? $orep->get("chassis.$el.status") : "";
      #my $s1 = $rep->get("chassis.$el.status");

  }

  return if (!$oreport);

  my $uptime = $rep->get("chassis.uptime");
  my $ouptime = $orep->get("chassis.uptime");
  if ($uptime < $ouptime) {
       $hm->alarmEvent( "", $report, $wwn, "Switch uptime decreased on $id from $ouptime to $uptime", 0, "system_reboot");
  }

  $hm->locationChangeEvent($report, $rep, $orep, $wwn);

  my($physicalFrame) = CIM::Key->new( ['CIM_PhysicalFrame',   # key of the frame
                        Tag               => $rep->get("id.wwn") ,
                        CreationClassName => 'CIM_PhysicalFrame' ]);

  my($PORTS) = $rep->get('version.ports');


# check if port state has changed

  my($comp);

  for ($x=1; $x <= $PORTS; $x++) {
     $comp = "port.$x"; # . sprintf("%3.3d", $x);
     $hm->stateEvent($comp, $report, $rep, $orep, 'CIM_Card', $comp, $wwn);
  }
#
#  generate events for the important counters 
#
  my($data);
  my($rep1) = $rep->subset("ASIC");
  foreach my $k (keys %$rep1) {
    if (defined($orep->{"ASIC.$k"})) {
       my $diff =  $rep->{"ASIC.$k"}  - $orep->{"ASIC.$k"};
       if ($diff > 0) {
          $data .= "ASIC.$k increments by $diff\n";
       }
    }
  }

  my($port);
  for ($x=1; $x <= $PORTS; $x++) {
     $port = "port.$x"; # . sprintf("%3.3d", $x);
     my($rep1) = $rep->subset("$port.error");
     foreach my $val (keys %$rep1) {
         my($old) = $orep->get("$port.error.$val");
         my($new) = $rep->get("$port.error.$val");
         if ($new > $old) {
           my($level, $cnt, $desc, $mins) = Thresholds->test('switch',$val, $x, $new-$old);
           my($tx)  = "Port-$x: Received $cnt '$desc' in $mins mins (value=$new)";

           if ($level eq "W" || $level eq "E") {
             $data .= "$tx\n";
           }
         }
     }
  }
  if ($data) {
      chop($data);
      $hm->logEvent($data, $report,  $wwn, "Change in Port Statistics on switch $id:", Message::SEVERITY_WARNING, "port.statistics");
  }
  my($ozone, $nzone) ;
  my($oZ) = $orep->subset("zone");
  my($nZ) = $rep->subset("zone");

  foreach my $x (keys %$oZ) {
    next if ($x eq "total");
    my $v = $oZ->{$x}; 
    chop($v) if (substr($v,-1) eq " ");
    $v =~ s/ /,/g;
    $ozone .= substr($x,0,-8) . "=($v) ";
  }
  foreach my $x (keys %$nZ) {
    next if ($x eq "total");
    my $v = $nZ->{$x}; 
    chop($v) if (substr($v,-1) eq " ");
    $v =~ s/ /,/g;
    $nzone .= substr($x,0,-8) . "=($v) ";
  }

  chop($ozone) if ($ozone);
  chop($nzone) if ($nzone);

  if ($ozone && $nzone && ($ozone ne $nzone)) {
       my($desc) = "Switch $id was rezoned: [$nzone] ";
       $hm->alarmEvent( "", $report, $wwn, $desc, 0);

     if (0) {  # ned to be turned on
       my($eid, $ev, $sd);
       $eid  =  $pdm->getEventSequence;
       $ev = CIM::Instance->new('NWS_Event', [
             [ EventType   => "switch.TopologyEvent"  ],
             [ Caption     => "zone-new"],
             [ MgmtLevel   => $mgmtLevel],
             [ Description => $desc ],
             [ EventId     => $eid ]]);

       $sd = Events->sourceDetector({ event => $ev });

       my($switch) = CIM::Key->new( ['NWS_System', 
                    'Name'            =>$rep->get('id.wwn'), 
                    CreationClassName => 'NWS_System']);

       my($zones) = NWS::Switch->zones($rep, $switch);

       $pertains = CIM::Instance->new('NWS_EventPertainsToSystem', [
                  [ Event       => $ev  ],
                  [ Element     => $switch],
                    ]);

       $ed = Message->new( { id        => $report->id,
                            instances => [$ev, @$sd, @$zones, $pertains ],
                            severity  => Message::SEVERITY_NORMAL});

       $pdm->saveMessage($ed);
    }

  }
}

  
sub status {
   my($hm, $rep, $orep, $comp) = @_;
   my($pdm) = $hm->{pdm};
   my($map) = $pdm->getDeviceStateMap("switch.availability");
   my($status, $ostatus, $old, $new);

   if (substr($comp, 0, 7) eq "chassis") {
      $ostatus = $orep->getState("$comp.status");
      $status  = $rep->getState("$comp.status");

      $old = $map->get("status.$ostatus"); # . $map->get("operational.$ostate");
      $new = $map->get("status.$status");  # . $map->get("operational.$state");

   } else {
      $ostatus = $orep->getState("$comp.mode");

      if (!$rep->{"$comp.mode"}) {
         $rep->{"$comp.mode"} = $orep->{"$comp.mode"};
         $rep->{"$comp.undefined_count"}++;
         $rep->{"$comp.undefined_start"} = time 
              if ($rep->{"$comp.undefined_count"} == 1);
      } else {
         delete $rep->{"$comp.undefined_count"};
      }
      $status  = $rep->getState("$comp.mode");

      $old = $map->get("mode.$ostatus"); # . $map->get("operational.$ostate");
      $new = $map->get("mode.$status");  # . $map->get("operational.$state");
   }


   return ($ostatus, $status, $old, $new );

}

# statiuc method
# return status-state and 0/1
# port.001
# port.002
# ...
# port.016

sub compStatus {
   my($hm, $rep, $orep, $comp) = @_;

   my($map) = PDM->getDeviceStateMap("switch.availability");

   my($status) = $rep->get("$comp.mode");

   my($new) = $map->get("mode.$status");

   $status  = "UNKNOWN" if (!$status);

   return ( $status, $new );

}




1;

