ASNMTAP

 view release on metacpan or  search on metacpan

applications/collector-test.pl  view on Meta::CPAN

                    $suspentionTimeslotPersistentFalse = ($suspentionTimeslotPersistentFalse > int($TsuspentionTimeslot)) ? $suspentionTimeslotPersistentFalse : int($TsuspentionTimeslot);
                  }
                }
              }

              $sth->finish() or $rv = errorTrapDBIdowntime($collectorlist, "Cannot sth->finish: $sql", \$logger, $debug) if $rv;
            }

            $dbh->disconnect or $rv = errorTrapDBIdowntime($collectorlist, "Sorry, the database was unable to add your entry.", \$logger, $debug);
          } else {
            $logger->info("     DBI_connect - Cannot connect to the database - alarm: $alarm - alarmMessage: $alarmMessage") if ( defined $logger and $logger->is_info() );
          }

          unless ( $firstRecordPersistentTrue and $firstRecordPersistentFalse ) {
            my $currentDowntimeTimeslot = timelocal (0, (localtime)[1,2,3,4,5]);
            print "$catalogID_uniqueKey\ncurrentTimeslot                  : $currentDowntimeTimeslot\n" if ($debug eq 'T');

            unless ( $firstRecordPersistentTrue ) {
              if ($debug eq 'T') {
                print "activationTimeslotPersistentTrue : $activationTimeslotPersistentTrue\n";
                print "suspentionTimeslotPersistentTrue : $suspentionTimeslotPersistentTrue\n";
              }

              if ( $activationTimeslotPersistentTrue <= $currentDowntimeTimeslot and $currentDowntimeTimeslot <= $suspentionTimeslotPersistentTrue ) {
                $persistent = $downtime = 1;
              }
            }

            if ( (! $downtime) and (! $firstRecordPersistentFalse) ) {
              if ($debug eq 'T') {
                print "activationTimeslotPersistentFalse: $activationTimeslotPersistentFalse\n";
                print "suspentionTimeslotPersistentFalse: $suspentionTimeslotPersistentFalse\n";
              }

              if ( $activationTimeslotPersistentFalse <= $currentDowntimeTimeslot and $currentDowntimeTimeslot <= $suspentionTimeslotPersistentFalse ) {
                $downtime = 1;
              }
            }

            print "instability: $instability, persistent: $persistent, downtime: $downtime\n" if ($debug eq 'T');
          }

          # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

          unless ( $downtime ) {
            if ($noOFFLINE) {
              if ($noOFFLINE eq 'multiOFFLINE') {
                $queryMySQL = 1;
                printDebugAll ("multi OFFLINE: call_system <$catalogID_uniqueKey><$command>") if ($debug eq 'T');
              } elsif ($noOFFLINE eq 'noTEST') {
                $queryMySQL = 1;
                printDebugAll ("no TEST: call_system <$catalogID_uniqueKey><$command>") if ($debug eq 'T');
              }
            }

            $action = call_system ($asnmtapEnv, $currentDate, $catalogID_uniqueKey, $catalogID, $uniqueKey, $resultsdir, $title, $command, $status, int($tinterval), $instability, $persistent, $downtime, $debug, $logging, $tlogging, $httpdump, $dumpht...
          }
        }

        if ($doOffline or $downtime) {
          print "Write 'Offline/No Test' status to mysql databases on: ", get_csvfiletime(), "\n" if ($debug eq 'T');

          my ($startDate, $startTime, $endDate, $endTime, $msgCommand);
          $startDate = get_csvfiledate();
          $startTime = get_csvfiletime();
          $endDate   = $startDate;
          $endTime   = $startTime;
          ($msgCommand, undef) = split(/\.pl/, $command);

          my $insertData = 1;
          my $status = 'OFFLINE';

          if ($noOFFLINE) {
  		    if ($noOFFLINE eq 'noOFFLINE') {
              if ($downtime) {
                $queryMySQL = 1;
              } else {
                $insertData = 0;
              }

              printDebugAll ("no OFFLINE: $msgCommand") if ($debug eq 'T');
  		    } elsif ($noOFFLINE eq 'multiOFFLINE') {
		      $queryMySQL = 1;
              printDebugAll ("multi OFFLINE: $msgCommand") if ($debug eq 'T');
  		    } elsif ($noOFFLINE eq 'noTEST') {
              $queryMySQL = 1;
              $status = 'NO TEST' unless ( $downtime );
              printDebugAll ("no TEST: $msgCommand") if ($debug eq 'T');
  		    }
          }

          if ($insertData) {
            my $rvOpen = open(CSV,">>$tlogging-$msgCommand-$catalogID_uniqueKey-csv.txt");

            if ($rvOpen) {
              print CSV '"', $catalogID, '","","', $uniqueKey, '","I","', $command, '","', $title, '","', $status, '","', $startDate, '","', $startTime, '","', $endDate, '","', $endTime, '","0","', $status, ' - Deze applicatie is niet toegankelijk","...
              close(CSV);
            } else {
              print "Cannot open $tlogging-$msgCommand-$catalogID_uniqueKey-csv.txt to print debug information\n";
            }

            insertEntryDBI ($currentDate, $catalogID_uniqueKey, $catalogID, $uniqueKey, $title, $logging.$msgCommand.'-'.$catalogID_uniqueKey.'-sql', $command, int($tinterval), $status, $tlogging, $debug, $startDate, $startTime, $endDate, $endTime, 0...
          }
        }

        # Update access and modify epoch time from the PID time
        utime (time(), time(), $pidfile) if (-e $pidfile);
      }

      printDebugAll ("Einde CollectorCT - : <$PROGNAME v$version -C $collectorlist> pid: <$pidfile>") if ($debug eq 'T');
    } else {
      print "Nothing to do at: ", get_csvfiletime(), "\n" if ($debug eq 'T');
    }
  }

  my ($prevSecs, $currSecs);
  $currSecs = int((localtime)[0]);

  do {
    sleep 5;
    $prevSecs = $currSecs;

applications/collector-test.pl  view on Meta::CPAN

    'endTime'           => $endTime,
    'duration'          => $duration,
    'statusMessage'     => $statusMessage,
    'perfdata'          => $perfdata,
    'step'              => $interval * 60,
    'timeslot'          => get_timeslot ($currentDate),
    'instability'       => $instability,
    'persistent'        => $persistent,
    'downtime'          => $downtime,
    'filename'          => $filename
  );

  my $_debug = ( ( $debug eq 'T' ) ? 1 : 0);
  my $dbh = CSV_prepare_table ($logging, get_logfiledate() . "-$msgCommand-$catalogID_uniqueKey", '.sql', $SERVERTABLEVENTS, \@EVENTS, \%EVENTS, \$logger, $_debug);
  my $rv = CSV_insert_into_table (1, $dbh, $SERVERTABLEVENTS, \@EVENTS, \%VALUES, 'id', \$logger, $_debug);
  CSV_cleanup_table ($dbh, \$logger, $_debug);

  my $rvOpen = open(DEBUG,">>$tlogging-$msgCommand-$catalogID_uniqueKey-sql-error.txt");

  if ($rvOpen) {
    print DEBUG $error_message, "\n--> ERROR: $DBI::err ($DBI::errstr)\n";
    print DEBUG $CATALOGID, " --> ", $catalogID, " <-> ", $uniqueKey, " <-> ", $title, " <-> ", $status, "\n--> ", $startDate, " <-> ", $startTime, " <-> ", $endDate, " <-> ", $endTime, " <-> ", $duration, " <-> ", $interval*60, " <-> ", get_timeslot...
    close(DEBUG);
  } else {
    print "Cannot open $tlogging-$msgCommand-$catalogID_uniqueKey-sql-error.txt to print debug information\n";
  }

  unless ( -e "$RESULTSPATH/$collectorlist-MySQL-sql-error.txt" ) {
    my $tDebug = ($debug eq 'T') ? 2 : 0;
    my $subject = "$prgtext / Current status for $collectorlist: " . get_datetimeSignal();
    my $message = get_datetimeSignal() . " $error_message\n--> ERROR: $DBI::err ($DBI::errstr)\n";
    my $returnCode = sending_mail ( $SERVERLISTSMTP, $SENDEMAILTO, $SENDMAILFROM, $subject, $message, $tDebug );
    print "Problem sending email to the '$APPLICATION' server administrators\n" unless ( $returnCode );
  }

  $rvOpen = open(DEBUG,">>$RESULTSPATH/$collectorlist-MySQL-sql-error.txt");

  if ($rvOpen) {
    print DEBUG get_datetimeSignal, " ", $error_message, "\n--> ERROR: $DBI::err ($DBI::errstr)\n";
    close(DEBUG);
  } else {
    print "Cannot open $RESULTSPATH/$collectorlist-MySQL-sql-error.txt to print debug information\n";
  }

  return 0;
}

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

sub errorTrapDBIdowntime {
  my ($collectorlist, $error_message, $logger, $debug) = @_;

  print $collectorlist, "\n", $error_message, "\nERROR: $DBI::err ($DBI::errstr)\n";
  $$logger->error("$collectorlist:\n" .$error_message. "\nERROR: $DBI::err ($DBI::errstr)") if ( defined $$logger and $$logger->is_error() );
  return 0;
}

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

sub graphEntryDBI {
  my ($catalogID, $uniqueKey, $title, $environment, $dbiFilename, $interval, $limitTest, $xLabelStep, $withBorder, $markOrZone, $yMarkValue, $xRealtime, $debug) = @_;

  $title .= ' ('. $ENVIRONMENT{$environment} .')' if (defined $environment);
  $title .= ' from '. $catalogID;

  # $limitTest -> 241: (120*2.0)+1, x = 2.0 -> $xLabelStep = 6 * x -> 12
  #               181: (120*1.5)+1, x = 1.5 -> $xLabelStep = 6 * x ->  9
  #               121: (120*1.0)+1, x = 1.0 -> $xLabelStep = 6 * x ->  6

  my $width      = 893;
  my $hight      = 558;
  my $xOffset    = 74;
  my $yOffset    = 28;
  my $yMarkColor = 0xFFFFDC;
  my $background = 0xF7F7F7;

  print "Generating RRD alike graph\n" if ($debug eq 'T');

  my (@dataOK, @dataCritical, @dataWarning, @dataUnknown, @dataNoTest, @dataOffline, @RRDlabels);
  my ($step, $lastTimeslot, $firstTimeslot, $duration, $startTime, $status, $timeslot, $findString);

  $step          = $interval * 60;
  $lastTimeslot  = timelocal (0, (localtime)[1,2,3,4,5]);
  $firstTimeslot = $lastTimeslot - ($step * ($limitTest));
  $findString    = "select SQL_NO_CACHE duration, startTime, status, timeslot from $SERVERTABLEVENTS force index (uKey) where catalogID = '$catalogID' and uKey = '$uniqueKey' and step <> '0' and (timeslot between '$firstTimeslot' and '$lastTimeslot')...
  print "$findString\n" if ($debug eq 'T');

  # data en labels in array zetten
  my ($counter, $seconden, $ttimeslot);

  for ( $counter = 0; $counter < $limitTest; $counter++) {
    push (@dataOK,       "0");
    push (@dataWarning,  "0");
    push (@dataCritical, "0");
    push (@dataUnknown,  "0");
    push (@dataNoTest,   "0");
    push (@dataOffline,  "0");
    push (@RRDlabels,    " ");
  }

  # db connect & sql query
  my ($dbh, $rv, $alarmMessage) = DBI_connect ( $DATABASE, $serverName, $SERVERPORTREADWRITE, $SERVERUSERREADWRITE, $SERVERPASSREADWRITE, $alarm, \&errorTrapDBIgraphEntry, ["Cannot connect to the database"], \$logger, $debug, $boolean_debug_all );

  if ($dbh and $rv) {
    my $sth = $dbh->prepare( $findString ) or $rv = errorTrapDBIgraphEntry("Cannot dbh->prepare: $findString", \$logger, $debug);
    ($rv, $alarmMessage) = DBI_execute ($rv, \$sth, $alarm, \&errorTrapDBIgraphEntry, ["Cannot sth->execute: $findString"], \$logger, $debug);

    unless ( $rv ) {
      $title .= " - DBI_execute - alarm: $alarm - $alarmMessage";
    } else {
      $sth->bind_columns( \$duration, \$startTime, \$status, \$timeslot ) or $rv = errorTrapDBIgraphEntry("Cannot sth->bind_columns: $findString", \$logger, $debug);

      unless ( $rv ) {
        $title .= " - Cannot sth->bind_columns";
      } else {
        $counter = 0;
        my $limitTrendline = ($yMarkValue) ? $yMarkValue * 2.5 : 9000;

        while( $sth->fetch() ) {
          $seconden  = int(substr($duration, 6, 2)) + int(substr($duration, 3, 2)*60) + int(substr($duration, 0, 2)*3600);
          $seconden += 0.5 if ($seconden == 0); # correction for to fast testresults
          $ttimeslot = abs((($lastTimeslot - $timeslot) / $step) - $limitTest);

          if ($ttimeslot >= 0) {
            $status = 'UNKNOWN' if ($status eq '<NIHIL>');

      	    if ($status eq 'OK') {
              $dataOK[$ttimeslot] = ($seconden < $limitTrendline) ? $seconden : $limitTrendline;
            } elsif ($status eq 'CRITICAL') {
              $dataCritical[$ttimeslot] = '-5';
            } elsif ($status eq 'WARNING'){
              $dataWarning[$ttimeslot]  = '-5';
            } elsif ($status eq 'UNKNOWN'){
              $dataUnknown[$ttimeslot]  = '-5';
            } elsif ($status eq 'NO TEST') {
              $dataNoTest[$ttimeslot]   = '-5';
            } elsif ($status eq 'OFFLINE') {
              $dataOffline[$ttimeslot]  = '-5';
            }
          }

  	      $RRDlabels[int($limitTest - $counter - 1)] = substr($startTime, 0, 5) unless ( $counter % $xLabelStep );
          $counter++;
        }
      }

      $sth->finish() or $rv = errorTrapDBIgraphEntry("Cannot sth->finish: $findString", \$logger, $debug);
	}

    $dbh->disconnect or $rv = errorTrapDBIgraphEntry("Sorry, the database was unable to add your entry.", \$logger, $debug);
  } else {
    $title .= " - DBI_connect - Cannot connect to the database - alarm: $alarm - alarmMessage: $alarmMessage";
    $logger->info("     DBI_connect - Cannot connect to the database - alarm: $alarm - alarmMessage: $alarmMessage") if ( defined $logger and $logger->is_info() );
  }

  # Create a XYChart object of size $width x $hight pixels, using 0xf0e090 as background color, with a black border, and 0 pixel 3D border effect
  my $c = new XYChart($width, $hight, $background, 0x0, 0);

  # Set the plotarea at (xOffset, yOffset) and of size $width - 95 x $hight - 78 pixels, with white background. Set border and grid line colors.
  $c->setPlotArea($xOffset, $yOffset, $width - 95, $hight - 78, 0xffffff, -1, 0xa08040, $c->dashLineColor(0x0, 0x0101), $c->dashLineColor(0x0, 0x0101))->setGridWidth(1);

  # Add a title box to the chart using 10 pts Arial Bold Italic font. The text is white (0x000000)
  $c->addText($width/2, 14, "$title", "arialbi.ttf", 10, 0x000000, 5, 0);

  # Set labels on the x axis
  unless ( $xRealtime ) {
    for ($counter = 0; $counter < $limitTest; $counter += $xLabelStep) {
      $RRDlabels[int($limitTest - $counter - 1)] = substr(scalar(localtime(($lastTimeslot - ($step * ($counter))))), 11, 5); 
    }
  }

  $c->xAxis()->setLabels(\@RRDlabels);

  for ($counter = 0; $counter < $limitTest - $xLabelStep; $counter += $xLabelStep) {
    my $labelStep = $xLabelStep / 3;
    $c->xAxis()->addMark($counter + $labelStep, $c->dashLineColor(0x0, 0x103))->setDrawOnTop(0);
    $c->xAxis()->addMark($counter + ($labelStep * 2), $c->dashLineColor(0x0, 0x103))->setDrawOnTop(0);
  }

  # Set labels on the y axis
  $c->yAxis()->setLabelFormat("{value|2,.}");

  # Add a stacked bar layer to the chart
  my $layer = $c->addBarLayer2($perlchartdir::Stack);

  # Set the axes width to 1 pixels
  $c->yAxis()->setWidth(1);
  $c->xAxis()->setWidth(1);

  # Add a title to the y axis
  $c->yAxis()->setTitle("Response time", "arial.ttf", 9);

  # Set the margins at the two ends of the axis during auto-scaling, and whether to start the axis from zero
  $c->yAxis()->setAutoScale(0, 0, 0);

  # Add a mark line ore zone to the chart and add the first two data sets to the chart as a stacked bar group
  if ($yMarkValue) {
	if ($markOrZone) {
	  $c->yAxis()->addMark($yMarkValue, $yMarkColor);
  	} else {
	  $c->yAxis()->addZone($yMarkValue, 3600, $yMarkColor);
	  $c->yAxis()->addZone(0, -6, $yMarkColor);
    }

    $layer->addDataSet(\@dataOK, $layer->yZoneColor($yMarkValue, $COLORSRRD {OK}, $COLORSRRD {TRENDLINE}), " Duration");
  } else {
	$c->yAxis()->addZone(0, -6, $yMarkColor) unless ( $markOrZone );
    $layer->addDataSet(\@dataOK, $COLORSRRD {OK}, " Duration");
  }

  $layer->addDataSet(\@dataWarning,  $COLORSRRD {WARNING},   " Warning");
  $layer->addDataSet(\@dataCritical, $COLORSRRD {CRITICAL},  " Critical");
  $layer->addDataSet(\@dataUnknown,  $COLORSRRD {UNKNOWN},   " Unknown");
  $layer->addDataSet(\@dataNoTest,   $COLORSRRD {"NO TEST"}, " No test");
  $layer->addDataSet(\@dataOffline,  $COLORSRRD {OFFLINE},   " Offline");

  # Set the sub-bar gap to 0, so there is no gap between stacked bars with a group
  $layer->setBarGap(-1.7E-100, 0);

  # Set the bar border to transparent
  if ($withBorder) {
    $layer->setBorderColor(0xF0F0F0);
  } else {
    $layer->setBorderColor($perlchartdir::Transparent);
  }

  # Add a legend box
  $c->addLegend(2, $hight - 34, 0, "arial.ttf", 8)->setBackground($perlchartdir::Transparent);

  # Add a custom CDML text at the bottom right of the plot area as the logo
  $c->addText($width - 3, 92, $APPLICATION . " @ " . $BUSINESS, "arial.ttf", 8, 0x999999, 6, 270);
  $c->addText($width - 18, $hight - 21, "Interval: " . $interval . " min, " . $DEPARTMENT . " @ " . $BUSINESS . ", created on: " . scalar(localtime()) . ".", "arial.ttf", 8, 0x000000, 6, 0);

  #output the chart
  $c->makeChart("$dbiFilename.png");
	
  return $rv;
}

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

sub errorTrapDBIgraphEntry {
  my ($error_message, $logger, $debug) = @_;

  print 'errorTrapDBIgraphEntry', "\n", $error_message, "\nERROR: $DBI::err ($DBI::errstr)\n";
  $$logger->error("errorTrapDBIgraphEntry:\n" .$error_message. "\nERROR: $DBI::err ($DBI::errstr)") if ( defined $$logger and $$logger->is_error() );
  return 0;
}

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

sub print_usage () {
  print "Usage: $PROGNAME -H <MySQL hostname> [-M <mode>] [-C <collectorlist>] [-W <screenDebug>] [-A <allDebug>] [-N <nokDebug>] [-s <dumphttp>] [-S <status>] [-D <debug>] [-V version] [-h help]\n";
}

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

sub print_help () {
  print_revision($PROGNAME, $version);
  print "ASNMTAP Collector for the '$APPLICATION'

-H, --hostname=<HOSTNAME>
   HOSTNAME   : hostname/address from the MySQL server
-M, --mode=O|L|C
   O(nce)     : run the program once
   L(oop)     : run the program as a loop
   C(rontab)  : run the program crontab based
-C, --collectorlist=<FILENAME>
   FILENAME   : filename from the collectorlist for the loop of crontab
-W, --screenDebug=F|T
   F(alse)    : all screendebugging off (default)
   T(true)    : all screendebugging on
-A, --allDebug=F|T
   F(alse)    : all file debugging off (default)



( run in 2.262 seconds using v1.01-cache-2.11-cpan-39bf76dae61 )