#!/usr/bin/perl -w
#
# for jobs in queue, show ps on each node
# Copyright 2001 Ohio Supercomputer Center
#
open(QSTAT, "qstat -rn |");

# perl version of uniq(1) for array
sub uniq {
#    print "uniq entry: ", map { $_ . " " } @_, "\n";
    if (scalar(@_) < 2) {
	return @_;
    }
    my $i = shift;
    my $j = shift;
    while ($i eq $j) {
#	print "uniq equal ate $j, scalar thingie is ", scalar(@_), "\n";
	if (scalar(@_) == 0) {
	    return $i;
	}
	$j = shift;
    }
#    print "uniq non-equal: $i + ", map { $_ . " " } ($j, @_), "\n";
    return ($i,uniq($j,@_));
}

# rsh to nodes to get ps
sub qps {
    my ($job, $user, $numproc, @nodes) = (shift, shift, shift, @_);
    print "*** Job $job, User $user, Procs $numproc\n";
    for $node (@nodes) {
	my $rsh = "ssh $node env COLUMNS=70 ps -o time,stat,command -u $user | sed 1d";
	if (! $show_all) {
	    $rsh .= " | egrep -v '^00:00:00'";
	}
	$lines = `$rsh`;
	if (length($lines) > 0) {
	    $lines =~ s/^/"$node "/emg;
	    print $lines;
	}
    }
}

sub usage {
    print STDERR "Usage: $0 [-a] [<jobid>...]\n";
    print STDERR "  -a : show all processes, default ignores zero time ones\n";
    print STDERR "  <jobid> : just one particular job, or list of jobs\n";
    exit(1);
}

while (scalar(@ARGV) >= 1) {
    my $arg = shift @ARGV;
    if ($arg eq "-a") {
	$show_all = 1;
    } elsif ($arg =~ /\d+/) {
	push @show_one, $arg;
    } else {
	usage;
    }
}

while (<QSTAT>) {
    if (/^\d/) {
  line:
	($job,$user) = split;
	($job) = split /\./,$job;
	if (defined(@show_one)) {
	    for ($i=0; $i<scalar(@show_one); $i++) {
		if ($show_one[$i] == $job) {
		    last;
		}
	    }
	    if ($i == scalar(@show_one)) {
		next;
	    }
	}
	$nodeline = "";
	while (<QSTAT>) {
	    if (/^\d/) {
		last;
	    }
	    chomp;
	    s/\s*(.*)/$1/;
	    $nodeline .= $_;
	}
	$nodeline =~ s#/\d##g;
	$nodeline =~ tr/+/ /;
	@nodes = sort(split / /,$nodeline);
	$numnodes = scalar(@nodes);
	@nodes = uniq(@nodes);
#	print "uniq nodes are ", map { $_ . " " } @nodes, "\n";
#	exit 1;
	qps($job, $user, $numnodes, @nodes);
	if (defined && /^\d/) {
	    goto line;
	}
    }
}
close(QSTAT);
exit;
