added reset and dump control files
[dell-switch] / syslog-count-link.pl
index de1266d..9be2522 100755 (executable)
@@ -2,15 +2,64 @@
 use warnings;
 use strict;
 
+# count Dell and Microtik syslog for port and stp events
+
+## report all logs:
+# sudo cat /var/log/switch/sw-[a-z][0-9]*.log | ./syslog-count-link.pl | less -S
+#
+## tail logs and report status on kill -HUP
+# sudo tail -f /var/log/switch/sw-[a-z][0-9]*.log | ./syslog-count-link.pl &
+
 use Data::Dump qw(dump);
+use POSIX qw(strftime);
+
+my $name = $0;
+$name =~ s/.*\/([^\/]+)$/$1/;
+$name =~ s/\.pl$//;
+my $dir = "/dev/shm/$name";
+mkdir $dir unless -e $dir;
 
 my $stat;
 
+sub print_stats {
+       open(my $fh, '>', "$dir/stats");
+
+       foreach my $host ( sort keys %$stat ) {
+               foreach my $port ( sort {
+                       my $a1 = $a; $a1 =~ s/\D+//g;
+                       my $b1 = $b; $b1 =~ s/\D+//g;
+                       no warnings;
+                       $a1 <=> $b1;
+               } keys %{ $stat->{$host} } ) {
+                       next if $port =~ m/^_/;
+                       my $out = sprintf "%s %s:%s %d\n", $host, $port, $stat->{$host}->{$port}, $stat->{$host}->{_count}->{$port};
+                       print $out;
+                       print $fh $out;
+               }
+       }
+
+       close($fh);
+}
+
+$SIG{HUP} = sub {
+       print_stats();
+};
+
+warn "kill -HUP $$  # to dump stats\n";
+{
+       open(my $fh, '>', "$dir/pid");
+       print $fh $$;
+       close($fh);
+}
+
+
 my $host_re = '[\w-]+';
 my $port_re = '[\w/]+';
 
 while(<>) {
        chomp;
+       s/[\r\n]+//;
+       next if m/^$/;
 
        ## Dell
        if ( m/(\S+)\s%LINK-[IW]-(\w+):\s*(\w+)/ ) {
@@ -34,20 +83,24 @@ while(<>) {
                $stat->{$host}->{_count}->{$port} += $state =~ m/F/ ? 1 : -1;
 
 
+       } elsif ( m'==> /var/log/' ) {
+               # ignore tail output
        } else {
                warn "IGNORE: [$_]\n";
        }
+
+       if ( -e "$dir/reset" && unlink "$dir/reset" ) {
+               $stat = {};
+               warn "# reset stats\n";
+       } elsif ( -e "$dir/dump" ) {
+               print "### ",strftime("%Y-%m-%d %H:%M:%S",localtime(time)), "\n";
+               print_stats;
+       }
 }
 
+
+
 warn "# stat = ", dump($stat);
+print_stats;
+
 
-foreach my $host ( sort keys %$stat ) {
-       foreach my $port ( sort {
-               my $a1 = $a; $a1 =~ s/\D+//g;
-               my $b1 = $b; $b1 =~ s/\D+//g;
-               $a1 <=> $b1;
-       } keys %{ $stat->{$host} } ) {
-               next if $port =~ m/^_/;
-               printf "%s %s:%s %d\n", $host, $port, $stat->{$host}->{$port}, $stat->{$host}->{_count}->{$port};
-       }
-}