#!/usr/bin/perl
# output process list from a logfile written by procname event handler
# Copyright (C) HITACHI,LTD. 2005
# WRITTEN BY HITACHI SYSTEMS DEVELOPMENT LABORATORY,
# Created by H.Kawai <h-kawai@sdl.hitachi.co.jp>

use Getopt::Long;

sub usage {
    print "Extract process list from LKST log file which includes \n";
    print "PROCESS_NAME events.\n";
    print "Usage: lkst_proc_list [-t] <log_file>\n";
    print "  -t  display times in the format of YYYY-MM-DD hh:mm:ss\n"
}

sub proc_list_time {
    %month = ('Jan', 1, 'Feb', 2, 'Mar', 3, 'Apr', 4, 'May', 5, 'Jun', 6,
	      'Jul', 7, 'Aug', 8, 'Sep', 9, 'Oct', 10, 'Nov', 11, 'Dec', 12);

    open(IFH, "/usr/sbin/lkstbuf print -E $tmpfile -rCf $ARGV[0] |")
	or die "Error: failed to run lkstbuf";

    printf("%5s %5s %5s %-20s %-20s\n", "PID", "PPID", "TGID", "COMM", "TIME");
    while (<IFH>) {
	($etype, $cpu, $pid, $wday, $mon, $day, $time, $year,
	 $dm, $ppid, $dm, $dm, $tgid, $dm, $dm,
	 $comm1, $comm2, $dm, $comm3, $comm4) = split(/,/);
	
	if ($etype ne "\"process name\"") {
	    next;
	}
	
	$ppid = hex($ppid);
	$tgid = hex($tgid);
	$comm1 = hex($comm1);
	$comm2 = hex($comm2);
	$comm3 = hex($comm3);
	$comm4 = hex($comm4);
	$comm = pack("l*", $comm1);
	$comm .= pack("l*", $comm2);
	$comm .= pack("l*", $comm3);
	$comm .= pack("l*", $comm4);
	($comm) = split(/\0/, $comm);
	$mon = $month{$mon};
	printf("%5d %5d %5d %-20s %4d-%02d-%02d %-20s\n",
	       $pid, $ppid, $tgid, $comm, $year, $mon, $day, $time);
    }

    close(IFH);
}

sub proc_list_seconds {
    open(IFH, "/usr/sbin/lkstbuf print -E $tmpfile -rSf $ARGV[0] |")
	or die "Error: failed to run lkstbuf";

    printf("%5s %5s %5s %-20s %-20s\n", "PID", "PPID", "TGID", "COMM", "TIME");
    while (<IFH>) {
	($etype, $cpu, $pid, $sec, $nsec,
	 $dm, $ppid, $dm, $dm, $tgid, $dm, $dm,
	 $comm1, $comm2, $dm, $comm3, $comm4) = split(/,/);
	
	if ($etype ne "\"process name\"") {
	    next;
	}
	
	$ppid = hex($ppid);
	$tgid = hex($tgid);
	$comm1 = hex($comm1);
	$comm2 = hex($comm2);
	$comm3 = hex($comm3);
	$comm4 = hex($comm4);
	$comm = pack("l*", $comm1);
	$comm .= pack("l*", $comm2);
	$comm .= pack("l*", $comm3);
	$comm .= pack("l*", $comm4);
	($comm) = split(/\0/, $comm);
	$mon = $month{$mon};
	printf("%5d %5d %5d %-20s %10d.%09d\n",
	       $pid, $ppid, $tgid, $comm, $sec, $nsec);
    }

    close(IFH);
}

$show_in_time = 0;
my $ret;

$ret = GetOptions('t' => \$show_in_time);
if (!$ret) {
    &usage;
    exit(1);
}

if ($#ARGV != 0) {
    &usage;
    exit(1);
}

if (! -f $ARGV[0]) {
    print "file not found: $ARGV[0]\n";
    exit(1);
}

$tmpfile=`mktemp /tmp/tmpetypes.XXXXXX` or die "cannot create temporary file";
chop($tmpfile);
open(TMP, ">$tmpfile") or die "cannot open temporary file";
print TMP << 'EOF';
0xefc,PROCESS_NAME,0x0003,"process name","ppid","tgid","comm1","comm2"
EOF
close(TMP);

if ($show_in_time) {
    &proc_list_time;
} else {
    &proc_list_seconds;
}

system(rm, $tmpfile);
exit 0;
