[BACK]Return to update_trango.pl CVS log [TXT][DIR] Up to [local] / trango / Net-Telnet-Trango / scripts

Diff for /trango/Net-Telnet-Trango/scripts/update_trango.pl between version 1.11 and 1.33

version 1.11, 2005/12/21 02:03:30 version 1.33, 2007/02/07 22:07:35
Line 1 
Line 1 
 #!/usr/bin/perl  #!/usr/bin/perl
 # $RedRiver: update_trango.pl,v 1.10 2005/12/21 01:17:06 andrew Exp $  # $RedRiver: update_trango.pl,v 1.32 2007/02/07 19:25:05 andrew Exp $
 ########################################################################  ########################################################################
 # update_trango.pl *** Updates trango foxes with a new firmware  # update_trango.pl *** Updates trango hosts with a new firmware
 #  #
 # 2005.11.15 #*#*# andrew fresh <andrew@mad-techies.org>  # 2005.11.15 #*#*# andrew fresh <andrew@mad-techies.org>
 ########################################################################  ########################################################################
 use strict;  # Copyright (C) 2005, 2006, 2007 by Andrew Fresh
 use warnings;  #
   # This program is free software; you can redistribute it and/or modify
 use Net::TFTP;  # it under the same terms as Perl itself.
   ########################################################################
 my $config_file = shift || 'update_trango.conf';  use strict;
 my $max_tries = 3;  use warnings;
   
   use YAML qw/ LoadFile /;
   use Net::TFTP;
 my $l = Mylogger->new( { log_prefix => 'UT' } );  use Net::Telnet::Trango;
   
   my $config_file = shift || 'update_trango.yaml';
 $l->sp("Reading config file '$config_file'");  my $max_tries = 3;
 my $conf = read_conf($config_file);  
   my $l = Mylogger->new( { log_prefix => 'UT' } );
 $l->sp("  Hardware Type: $conf->{'type'}");  
 $l->sp("  File Name:     $conf->{'file_name'}");  $l->sp("Reading config file '$config_file'");
 $l->sp("  File Size:     $conf->{'file_size'}");  my $conf = LoadFile($config_file);
 $l->sp("  File Checksum: $conf->{'file_cksum'}");  
 $l->sp("  FW Version:    $conf->{'ver'}");  my $hosts;
 $l->sp("  FW Checksum:   $conf->{'cksum'}");  if (@ARGV) {
 $l->sp("");      @{$hosts} = map { { name => $_, group => 'Trango-Client' } } @ARGV;
   }
   else {
       $hosts = parse_hosts( $conf->{hosts} );
   }
   
   #@{ $hosts } = grep { $_->{name} eq '10.100.7.2' } @{ $hosts };
 foreach my $fox (@{ $conf->{'ips'} }) {  
   $l->sp("Updating: $fox");  my $global_tries = $max_tries * 2;
   while ( $global_tries > 0 ) {
   ## Connect and login.      $global_tries--;
   my $t = new Trango::Telnet ({      my $processed = 0;
     Host    => $fox,  
     Timeout => 5,      foreach my $host ( @{$hosts} ) {
   });  
           if ( !exists $host->{retry} ) {
   $l->p("Connecting to $fox");              $host->{tries} = 0;
   my ($type, $version) = $t->connect();              $host->{retry} = 1;
           }
   unless (defined $type && defined $version) {  
     $l->sp("Error connecting!");          if ( $host->{tries} >= $max_tries ) {
     next;              $host->{retry} = 0;
   }          }
   
   if ($type ne $conf->{'type'}) {          if ( $host->{retry} <= 0 ) {
     $l->sp("Wrong type of unit ('$type' should be '$conf->{'type'}')");              next;
     $t->close;          }
     next;  
   }          $host->{tries}++;
           $processed++;
   if ($version eq $conf->{'ver'}) {  
     $l->sp("Already up to date with firmware version '$version'");          $l->sp("");
     $t->close;          $l->sp("Checking: $host->{name} (try $host->{tries})");
     next;          my $needs_reboot = 0;
   }  
           ## Connect and login.
   $l->p("Logging in");          my $t = new Net::Telnet::Trango(
   $t->login($conf->{'password'}) || die "Couldn't login: $!";              Timeout => 5,
               Errmode => 'return',
   $l->p("Sending commands");          ) or die "Couldn't make new connection: $!";
   ## Send commands          $l->p("Connecting to $host->{name}");
   if ( upload($t, $conf->{'file_name'}) ) {          unless ( $t->open( $host->{name} ) ) {
     $l->p("Rebooting");              $l->sp("Error connecting: $!");
     $t->reboot;              next;
   } else {          }
     $l->p("Exiting");  
     $t->exit;          my $password = $host->{Telnet_Password} || $conf->{general}->{password};
   }  
   $t->close;          $l->p("Logging in");
   $l->sp("");          $t->login($password);
 }          unless ($t->logged_in) {
               $l->p('Failed!');
 sub upload              $t->close;
 {              next;
   my $t    = shift;          }
   my $file = shift;  
           $l->sp("Getting sudb");
   my $ver = $t->ver;          my $sudb = $t->sudb_view;
   $l->p("Current version '$ver->{'Firmware Version'}'");          if ($sudb) {
               foreach my $su (@{ $sudb }) {
   if (                  $l->p("Getting su info $su->{suid}");
     $ver->{'Firmware Version'}  eq $conf->{'ver'} &&                  my $su_info = $t->su_info( $su->{suid} );
     $ver->{'Firmware Checksum'} eq $conf->{'cksum'}                  if ($su_info->{ip}) {
   ) {                      if (grep { $_->{name} eq $su_info->{'ip'} } @{ $hosts }) {
     $l->sp("Already updated!");                          $l->p("Already have $su_info->{ip}");
     return 1;                          next;
   }                      }
                       $l->sp("Adding host $su_info->{ip}");
   my $try = 0;                      my $new_host = {
   while (1) {                          password => $host->{password},
     if ($try >= $max_tries) {                          name     => $su_info->{ip},
       $l->sp("Couldn't update in $max_tries tries!");                          remarks  => $su_info->{remarks},
       return undef;                      };
     }                      push @{ $hosts }, $new_host;
     $try++;                  } else {
                       $l->sp("Couldn't get su info for $su->{suid}");
     #sysinfo($self->{'_host'});                      $l->sp("ERR: " . $t->last_error);
                       }
     $l->p("Enabling TFTPd");              }
     $t->enable_tftpd || die "Couldn't enable tftpd";          }
   
     $l->p("Uploading file ($file)");          foreach my $firmware_type ( 'Firmware', 'FPGA' ) {
     # use tftp to push the file up  
     my $tftp = Net::TFTP->new($t->Host, Mode => 'octet');              if ( !exists $conf->{$firmware_type} ) {
                   $l->s("No configs for '$firmware_type'");
     $tftp->put($file, $file)                  next;
       or die "Error uploading: " . $tftp->error;              }
   
     # waitfor some sort of output              my $host_type = $t->host_type;
     # make sure it says 'Success.' otherwise error              if ( $firmware_type eq 'FPGA' ) {
     #print "LAST: " . $self->lastline;                  $host_type =~ s/\s.*$//;
     #my @lines = $self->getlines;              }
     #print Dump \@lines;  
                   if ( !exists $conf->{$firmware_type}->{$host_type} ) {
     $l->p("Checking upload ($conf->{'file_cksum'})");                  $l->sp("No '$firmware_type' config for type $host_type");
     my $results = $t->tftpd;                  next;
     # check the 'File Length' against ???              }
     if ( $results->{'File Checksum'} ne $conf->{'file_cksum'}) {  
       $l->sp(              if (   $firmware_type eq 'Firmware'
         "File checksum '" . $results->{'File Checksum'} .                  && $t->firmware_version eq
         "does not match config file '" . $conf->{'file_cksum'} . "'!"                  $conf->{$firmware_type}->{$host_type}->{ver} )
       );              {
       next;                  $l->sp("Firmware already up to date");
     }                  next;
     $l->p("File checksum matches . . . ");              }
   
     if ($results->{'File Length'}   !~ /^$conf->{'file_size'} bytes/) {              if ( !$t->logged_in ) {
       $l->sp(                  $l->p("Logging in");
         "File length '" . $results->{'File Length'} .                  $t->login($password);
         "does not match config file '" . $conf->{'file_size'} . " bytes'!"                  unless ($t->logged_in) {
       );                      $l->p('Failed!');
       next;                      $t->close;
     }                      last;
     $l->p("File length matches . . . ");                  }
               }
     if ( uc($results->{'File Name'}) ne uc($conf->{'file_name'}) ) {  
       $l->sp(              foreach my $k ( keys %{ $conf->{general} } ) {
         "File name '" . $results->{'File Name'} .                  $conf->{$firmware_type}->{$host_type}->{$k} ||=
         "' does not match config file '" . $conf->{'file_name'} . "'!"                    $conf->{general}->{$k};
       );              }
       next;              $conf->{$firmware_type}->{$host_type}->{firmware_type} ||=
     }                $firmware_type;
     $l->p("File name  matches . . . ");              $conf->{$firmware_type}->{$host_type}->{type} = $host_type;
   
     $l->p("Updating flash (new checksum '$conf->{'cksum'}')");              $l->sp("$host_type $firmware_type");
     unless ($results = $t->updateflash(              ## Send commands
       $ver->{'Firmware Checksum'}, $conf->{'cksum'}              my $rc = upload( $t, $conf->{$firmware_type}->{$host_type} );
     ) ) {              if ($rc) {
       $l->sp("Couldn't update flash: $!");                  $l->sp("Successfull!");
       next;                  $host->{retry}--;
     }                  $needs_reboot = 1;
               }
     unless (              elsif ( defined $rc ) {
       defined $results->{'Checksum'} &&                  $l->sp("Already up to date");
       $results->{'Checksum'} eq $conf->{'cksum'}                  $host->{retry}--;
     ) {              }
       $l->sp("Saved checksum does not match config file!");              else {
       next;                  $l->sp("Failed");
     }                  $t->bye;
     $l->p("Uploaded checksum ($results->{'Checksum'}) " .                  next;
           "matches ($conf->{'cksum'})");              }
       
     $l->sp("Successfully updated!");          }
     return 1;  
   }          if ($needs_reboot) {
 }              $l->sp("Rebooting $host->{name}");
               $t->reboot;
 sub read_conf          }
 {          else {
   my $file = shift;              $l->sp("Bye $host->{name}");
   my %conf;              $t->bye();
   my $in_ip_list = 0;          }
   open my $fh, $file or die "Couldn't open file $file: $!";      }
   while (<$fh>) {  
     chomp;      if ( !$processed ) {
     next if /^#/;          $l->sp("");
     next if /^$/;          $l->sp("Finished.  No more hosts.");
     if ($in_ip_list) {          last;
       s/\s+//g; # Whitespace is a no no      }
   }
       if (/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.)(\d{1,3})-(\d{1,3})/) {  
         push @{ $conf{'ips'} }, $1 . $_ for ($2..$3);  sub upload {
       } else {      my $t    = shift;
         push @{ $conf{'ips'} }, $_;      my $conf = shift;
       }  
     } else {      my $file = $conf->{firmware_path} . '/' . $conf->{file_name};
       my ($key, $val) = split /\s+/, $_, 2;  
       my $fw_type = $conf->{firmware_type};
       if (lc($key) eq 'ips') {  
         $in_ip_list = 1;      my $ver = $t->ver;
         next;  
       }      if (
           !(
       $key =~ s/^\s+//;              $ver->{ $fw_type . ' Version' } && $ver->{ $fw_type . ' Checksum' }
       $key =~ s/\s+$//;          )
       $val =~ s/^\s+//;        )
       $val =~ s/\s+$//;      {
           $l->sp("Error getting current version numbers");
       $conf{ lc($key) } = $val;          return;
     }      }
   }  
   close $fh;      if (   $ver->{ $fw_type . ' Version' } eq $conf->{'ver'}
           && $ver->{ $fw_type . ' Checksum' } eq $conf->{'cksum'} )
   #print Dump \%conf;      {
   foreach (          return 0;
     'password',      }
     'file_name', 'file_size', 'file_cksum',  
     'ver', 'cksum', 'ips',      $l->sp("Updating $fw_type");
   ) {      $l->sp("Config information:");
     die "No $_ specified in config file!"      $l->sp("  Hardware Type: $conf->{'type'}");
       if (not exists $conf{$_});      $l->sp("  File Name:     $conf->{'file_name'}");
   }      $l->sp("  File Size:     $conf->{'file_size'}");
       $l->sp("  File Checksum: $conf->{'file_cksum'}");
   #print Dump \%conf;      $l->sp("  Conf Version:  $conf->{'ver'}");
   #exit;      $l->sp("  Cur  Version:  $ver->{$fw_type . ' Version'}");
   return \%conf;      $l->sp("  Conf Checksum: $conf->{'cksum'}");
 }      $l->sp("  Cur  Checksum: $ver->{$fw_type . ' Checksum'}");
   
 package Trango::Telnet;      my $try = 0;
 use base 'Net::Telnet';      while (1) {
           if ( $try >= $max_tries ) {
 my %PRIVATE = (              $l->sp("Couldn't update in $max_tries tries!");
   connected => 0,              return;
   logged_in => 0,          }
 );          $try++;
   
 sub new {          $l->p("Enabling TFTPd");
   my $class = shift;          unless ( $t->enable_tftpd ) {
   my $args = shift || {};              $l->sp("Couldn't enable tftpd");
               next;
   $args->{'Timeout'} ||= 5;          }
   $args->{'Prompt'}  ||= '/#> *$/';  
           $l->p("Uploading file ($conf->{file_name})");
   foreach my $key (keys %{ $args }) {  
     $PRIVATE{$key} = $args->{$key};          # use tftp to push the file up
   }          my $tftp = Net::TFTP->new( $t->Host, Mode => 'octet' );
   
   my $self = $class->SUPER::new(%{ $args });          unless ( $tftp->put( $file, $file ) ) {
   bless $self;              $l->sp( "Error uploading: " . $tftp->error );
               next;
   #bless $self, $package;          }
   return $self;  
 }          $l->p("Checking upload ($conf->{'file_cksum'})");
           my $results = $t->tftpd;
 sub connect  
 {          # check the 'File Length' against ???
   my $self = shift;          if (
               !(
   unless ( $self->open(                     $results->{'File Checksum'}
       Host => $PRIVATE{'Host'},                  && $results->{'File Length'}
       Errmode => 'return',                  && $results->{'File Name'}
   ) ) {              )
     $! = "Couldn't connect to $self->{'Host'}.  Connection timed out.";            )
     return undef, undef;          {
   }              $l->sp("Unable to get results of upload");
   #$self->dump_log('dump.log');              next;
           }
   ## Login to remote host.          if ( $results->{'File Checksum'} ne $conf->{'file_cksum'} ) {
   unless ($self->waitfor(              $l->sp( "File checksum ("
     -match => '/password: ?$/i',                    . $results->{'File Checksum'}
     -errmode => "return",                    . ") does not match config file ("
   ) ) {                    . $conf->{'file_cksum'}
     $! = "problem connecting to host ($self->{'Host'}): " . $self->lastline;                    . ")!" );
     return undef;              next;
   }          }
           $l->p("File checksum matches . . . ");
   $self->login_banner($self->lastline);  
           if ( $results->{'File Length'} !~ /^$conf->{'file_size'} bytes/ ) {
   $PRIVATE{'connected'} = 1;              $l->sp( "File length ("
                     . $results->{'File Length'}
   return ($self->host_type, $self->firmware_version);                    . ") does not match config file ("
 }                    . $conf->{'file_size'}
                     . " bytes)!" );
 sub login              next;
 {          }
   my $self = shift;          $l->p("File length matches . . . ");
   
   my $password = shift;          if ( uc( $results->{'File Name'} ) ne uc($file) ) {
               $l->sp( "File name ("
   $self->print($password);                    . $results->{'File Name'}
   unless ($self->waitfor(                    . ") does not match config file ("
     -match => $self->prompt,                    . $file
     -errmode => "return",                    . ")!" );
   ) ) {              next;
     $! = "login ($self->{'Host'}) failed: " . $self->lastline;          }
     return undef;          $l->p("File name matches . . . ");
   }  
           my $image_type = 'mainimage';
   $PRIVATE{'logged_in'} = 1;          if ( $fw_type eq 'FPGA' ) {
               $image_type = 'fpgaimage';
   return 1;          }
 }          $l->p("Updating $image_type (new checksum '$conf->{'cksum'}')");
           unless (
 sub login_banner              $results = $t->updateflash(
 {                  args => $image_type . ' '
   my $self = shift;                    . $ver->{ $fw_type . ' Checksum' } . ' '
                     . $conf->{'cksum'},
   my $banner = shift || $PRIVATE{'login_banner'};                  Timeout => 90,
               )
   my ($type, $ver) = $banner =~            )
     /Welcome to Trango Broadband Wireless (\S+)[\s-]+(.+)$/i;          {
               $l->sp("Couldn't update flash: $!");
   $self->host_type($type);              next;
   $self->firmware_version($ver);          }
   
   return $banner;          unless ( defined $results->{'Checksum'}
 }              && $results->{'Checksum'} eq $conf->{'cksum'} )
           {
 sub host_type              $l->sp( "Saved checksum "
 {                    . $results->{'Checksum'}
   my $self = shift;                    . " does not match config file "
                     . $conf->{'cksum'}
   my $type = shift || $PRIVATE{'host_type'};                    . "!" );
   $PRIVATE{'host_type'} = $type;              next;
           }
   return $type;  
 }          $l->p("$fw_type saved checksum matches . . . ");
   
 sub firmware_version          return 1;
 {      }
   my $self = shift;  }
   
   my $ver = shift || $PRIVATE{'firmware_version'};  sub parse_hosts {
   $PRIVATE{'firmware_version'} = $ver;      my $src = shift;
     
   return $ver      my @hosts;
 }      foreach my $h ( @{$src} ) {
           if ( $h->{name} =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.)(\d{1,3})-(\d{1,3})/ )
 sub Host          {
 {              for ( $2 .. $3 ) {
   my $self = shift;                  my %cur_host;
                     foreach my $k ( keys %{$h} ) {
   my $host = shift || $PRIVATE{'Host'};                      $cur_host{$k} = $h->{$k};
   $PRIVATE{'HOST'} = $host;                  }
                   $cur_host{name} = $1 . $_;
   return $host;                  if ( !grep { $cur_host{name} eq $h->{name} } @hosts ) {
 }                      push @hosts, \%cur_host;
                   }
               }
 sub reboot          }
 {          else {
   my $self = shift;              push @hosts, $h;
           }
   $self->print("reboot\n");      }
   $self->getline;  
       return \@hosts;
   return 1;  }
 }  
   package Mylogger;
 sub exit  
 {  use Fcntl ':flock';    # import LOCK_* constants
   my $self = shift;  
   #use YAML;
   $self->print("exit\n");  use constant LOG_PRINT => 128;
   $self->getline;  use constant LOG_SAVE  => 64;
   
   return 1;  DESTROY {
 }      my $self = shift;
       if ( $self->{'MYLOG'} ) {
 sub ver          $self->p("Closing log ($self->{'log_path'}/$self->{'log_file'})");
 {          close $self->{'MYLOG'};
   my $self = shift;      }
   }
   return $self->cmd('ver');  
 }  sub new {
       my $package = shift;
 sub tftpd      my $self = shift || {};
 {  
   my $self = shift;      $self->{'base_path'}  ||= '.';
       $self->{'log_path'}   ||= $self->{'base_path'};
   return $self->cmd('tftpd', 'Success.');      $self->{'log_prefix'} ||= 'LOG';
 }      $self->{'log_file'} ||=
         GetLogName( $self->{'log_prefix'}, $self->{'log_path'} );
 sub sysinfo      bless $self, $package;
 {  }
   my $self = shift;  
   sub s {
   return $self->cmd('sysinfo', 'Success.');      my $self = shift;
 }      my $m    = shift;
       return $self->mylog( $m, LOG_SAVE );
 sub enable_tftpd  }
 {  
   my $self = shift;  sub p {
       my $self = shift;
   my $vals = $self->cmd('tftpd on', 'Success.');      my $m    = shift;
       return $self->mylog( $m, LOG_PRINT );
   if ($vals->{'Tftpd'} eq 'listen') {  }
     return $vals;  
   } else {  sub sp {
     return undef;      my $self = shift;
   }      my $m    = shift;
 }      return $self->mylog( $m, LOG_SAVE | LOG_PRINT );
   }
 sub updateflash  
 {  sub mylog {
   my $self = shift;      my $self = shift;
   
   my $old = shift;      my $thing = shift;
   my $new = shift;      chomp $thing;
   
   return undef unless $new;      my $which = shift;
   
   return $self->cmd("updateflash mainimage $old $new", 'Success.', 90);      my $MYLOG;
 }      if ( $which & LOG_PRINT ) {
           print $thing, "\n";
 sub cmd      }
 {  
   my $self = shift;      if ( $which & LOG_SAVE ) {
           if ( $self->{'MYLOG'} ) {
   my $string = shift;              $MYLOG = $self->{'MYLOG'};
   my $expect_last = shift;          }
   my $timeout = shift || $PRIVATE{'Timeout'};          else {
               unless ($MYLOG) {
   unless (defined $string) {                  open( $MYLOG, '>>',
     $! = "No command passed";                      $self->{'log_path'} . '/' . $self->{'log_file'} )
     return undef;                    or die "Couldn't open logfile!\n";
   }                  my $ofh = select $MYLOG;
                   $| = 1;
   unless ($PRIVATE{'connected'}) {                  select $ofh;
     $! = "Not connected";                  $self->{'MYLOG'} = $MYLOG;
     return undef;  
   }                  $self->p(
                       "Opened log ($self->{'log_path'}/$self->{'log_file'})");
   unless ($PRIVATE{'logged_in'}) {              }
     $! = "Not logged in";          }
     return undef;          flock( $MYLOG, LOCK_EX );
   }          print $MYLOG ( scalar gmtime ), "\t", $thing, "\n"
             or die "Couldn't print to MYLOG: $!";
   my @lines = $self->SUPER::cmd(String => $string, Timeout => $timeout);          flock( $MYLOG, LOCK_UN );
       }
   my $vals = _decode_lines(@lines);  }
   
   unless ($expect_last) {  sub GetLogName {
     return $vals;      my $prefix = shift || die "Invalid prefix passed for log";
   }  
       my $logdate = GetLogDate();
   my $last = $self->lastline;      my $logver  = 0;
       my $logname;
   if ($last =~ /$expect_last$/) {  
     return $vals;      do {
   } else {          $logname = $prefix . $logdate . sprintf( "%02d", $logver ) . '.log';
     warn "Error with command ($string): $last";          $logver++;
     return undef;      } until ( not -e $logname );
   }  
 }      return $logname;
   }
 sub _decode_lines  
 {  sub GetLogDate {
   my @lines = @_;      my ( $sec, $min, $hour, $mday, $mon, $year,,, ) = localtime();
   
   my %conf;      $mon++;
       $year += 1900;
   my $key = '';  
   my $val = '';      if ( $min  < 10 ) { $min  = "0$min"  }
   my $in_key = 0;      if ( $sec  < 10 ) { $sec  = "0$sec"  }
   my $in_val = 0;      if ( $hour < 10 ) { $hour = "0$hour" }
       if ( $mday < 10 ) { $mday = "0$mday" }
   foreach my $line (@lines) {      if ( $mon  < 10 ) { $mon  = "0$mon"  }
     my @chars = split //, $line;  
       my $time = $year . $mon . $mday;
     my $last_key = '';  
     foreach my $c (@chars) {      return $time;
   }
       if ($c eq '[' || $c eq "\r" || $c eq "\n") {  
         if ($c eq '[') {  
           $in_key = 1;  
           $in_val = 0;  
         } else {  
           $in_key = 0;  
           $in_val = 0;  
         }  
   
         if ($key) {  
           $key =~ s/^\s+//;  
           $key =~ s/\s+$//;  
   
           $val =~ s/^\s+//;  
           $val =~ s/\s+$//;  
   
           if ($key eq 'Checksum' && $last_key) {  
             # Special case for these bastids.  
             my $new = $last_key;  
             $new =~ s/\s+\S+$//;  
             $key = $new . " " . $key;  
           }  
   
           $last_key = $key;  
           $conf{$key} = $val;  
           $key = '';  
           $val = '';  
         }  
   
       } elsif ($c eq ']') {  
         $in_val = 1;  
         $in_key = 0;  
         $c = shift @chars;  
   
       } elsif ($in_key) {  
         $key .= $c;  
   
       } elsif ($in_val) {  
         $val .= $c;  
       }  
     }  
   }  
   #print Dump \%conf;  
   
   if (%conf) {  
     return \%conf;  
   } else {  
     return \@lines;  
   }  
 }  
   
   
   
 package Mylogger;  
   
 use Fcntl ':flock'; # import LOCK_* constants  
 #use YAML;  
 use constant LOG_PRINT => 128;  
 use constant LOG_SAVE  =>  64;  
   
 DESTROY {  
   my $self = shift;  
   if ($self->{'MYLOG'}) {  
     $self->p("Closing log ($self->{'log_path'}/$self->{'log_file'})");  
     close $self->{'MYLOG'};  
   }  
 }  
   
 sub new {  
   my $package = shift;  
   my $self = shift || {};  
   
   $self->{'base_path'}  ||= '.';  
   $self->{'log_path'}   ||= $self->{'base_path'};  
   $self->{'log_prefix'} ||= 'LOG';  
   $self->{'log_file'}   ||= GetLogName(  
     $self->{'log_prefix'},  
     $self->{'log_path'}  
   );  
   bless $self, $package;  
 }  
   
 sub s  
 {  
   my $self = shift;  
   my $m = shift;  
   return $self->mylog($m, LOG_SAVE);  
 }  
   
 sub p  
 {  
   my $self = shift;  
   my $m = shift;  
   return $self->mylog($m, LOG_PRINT);  
 }  
   
 sub sp  
 {  
   my $self = shift;  
   my $m = shift;  
   return $self->mylog($m, LOG_SAVE | LOG_PRINT);  
 }  
   
 sub mylog  
 {  
   my $self = shift;  
   
   my $thing = shift;  
   chomp $thing;  
   
   my $which = shift;  
   
   my $MYLOG;  
   if ($which & LOG_PRINT) {  
     print $thing, "\n";  
   }  
   
   if ($which & LOG_SAVE) {  
     if ($self->{'MYLOG'}) {  
       $MYLOG = $self->{'MYLOG'};  
     } else {  
       unless ($MYLOG) {  
                 open ($MYLOG, '>>', $self->{'log_path'} . '/' . $self->{'log_file'})  
           or die "Couldn't open logfile!\n";  
         my $ofh = select $MYLOG;  
         $|=1;  
         select $ofh;  
         $self->{'MYLOG'} = $MYLOG;  
   
         $self->p("Opened log ($self->{'log_path'}/$self->{'log_file'})");  
       }  
     }  
     flock($MYLOG, LOCK_EX);  
     print $MYLOG (scalar gmtime), "\t", $thing, "\n"  
       or die "Couldn't print to MYLOG: $!";  
     flock($MYLOG, LOCK_UN);  
   }  
 }  
   
 sub GetLogName  
 {  
   my $prefix  = shift || die "Invalid prefix passed for log";  
   
   my $logdate = GetLogDate();  
   my $logver  = 0;  
   my $logname;  
   
   do {  
     $logname = $prefix . $logdate . sprintf("%02d", $logver) . '.log';  
     $logver++;  
   } until (not -e $logname);  
   
   return $logname;  
 }  
   
 sub GetLogDate  
 {  
   my ($sec,$min,$hour,$mday,$mon,$year,,,) = localtime();  
   
   $mon++;  
   $year += 1900;  
   
   if ($min  < 10) { $min  = "0$min"  }  
   if ($sec  < 10) { $sec  = "0$sec"  }  
   if ($hour < 10) { $hour = "0$hour" }  
   if ($mday < 10) { $mday = "0$mday" }  
   if ($mon  < 10) { $mon  = "0$mon"  }  
   
   my $time = $year . $mon . $mday;  
   
   return $time;  
 }  

Legend:
Removed from v.1.11  
changed lines
  Added in v.1.33

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>