#!/afs/athena/contrib/perl/perl
# whydrop
# $Header: /afs/sipb/user/jhawk/src/cisco/RCS/whydrop,v 1.1 1995/11/05 19:25:06 jhawk Exp jhawk $

$router="192.52.71.1";
$iface="e0/1";

require('chat2.pl');

sub send { &chat'print($conn, @_) }
sub waitsend {  &chat'expect($conn, 3, ">$cr", ';',
                                       "TIMEOUT", 'print "Timeout.\n"');
                &chat'print($conn, @_);
}

sub getdrops {
     &send("sh int $iface\n");
     $odrops=$drops;
     &chat'expect($conn, 3,
      "Output queue.*$cr",          '$drops=$&',
      'buffer failuers.*$cr',       ';',
      TIMEOUT,                      '"Timeout1.\n"');
     $drops =~ s/Output queue \d*\/\d*, (\d*) drops;.*/$1/;
}

sub getcpu {
    local ($done) = 0;
    local($trash,$pid,$runtime,$invoked,$usecs,$x,$y,$z,$tty,$name);

    %oldprocs=%procs;
    %procs=();

    &send("sh proc cpu\n");
    &chat'expect($conn, 3, ' PID.*\n', ';');
    until ($done) { &chat'expect($conn, 3,
      '>',             '$done=1;',
      '^\s.*\n',         '$proc=$&');
    chop($proc);  chop($proc);
    ($pid,$runtime,$invoked,$usecs,$x,$y,$z,$tty,$name) =
      split(' ', $proc, 9);
    $procs{$pid}="$pid $runtime $invoked $usecs $tty $name";
    }
}

sub numerically { $a <=> $b; }

sub diffcpu {
    local ($format) = "%-5s %-10s %-10s %-10s %-5s %-15s\n";
    local($Npid,$Nruntime,$Ninvoked,$Nusecs,$Ntty,$Nname);
    local($Opid,$Oruntime,$Oinvoked,$Ousecs,$Otty,$Oname);
    local($runtime, $invoked, $usecs);
    printf $format, "PID", "Runtime", "Invoked", "uSecs", "Name";

    foreach $i (sort numerically keys(%procs)) {
	($Npid,$Nruntime,$Ninvoked,$Nusecs,$Ntty,$Nname)=
	    split(' ', $procs{$i}, 6);
	($Opid,$Oruntime,$Oinvoked,$Ousecs,$Otty,$Oname)=
	    split(' ', $oldprocs{$i}, 6);

	$runtime=($Nruntime-$Oruntime);
	$invoked=($Ninvoked-$Oinvoked);
	$usecs=($Nusecs-$Ousecs);
	
	if (($usecs > 0)  || ($runtime > 0) || ($usecs > 0)) {
	    printf ($format, $Npid,$runtime,$invoked, $usecs, $Ntty,$Nname);
	}
    }
}

	

$conn = &chat'open_port($router, 23) || die;

until ($done) { &chat'expect($conn, 3,
	"Password: $cr",     '&sendpass',
	">$cr",		     '$done=1'); }

&send("ter len 0\n"); &chat'expect($conn, 1, ">$cr", ';');

&getcpu; &getdrops; &getdrops;
while ($drops <= $odrops) {
  &getdrops; &getcpu;
  printf "Tick!\n"; sleep 1;
}

print "Drops before $odrops. Drops after $drops. Difference ",
($drops-$odrops), "\n";

&diffcpu;

&chat'close($conn);
