#!/usr/bin/perl
#
# Program: Apache Request Viewer <viewreqs.pl>
#
# Author: Matty <matty91 at gmail dot com>
#
# Current Version: 0.1a
#
# Revision History:
#  Version 0.1a
#
# Last Updated: 11-25-2005
#
# Purpose: Prints the number of requests processed by an
#          Apache web server
#
# Installation:
#   Copy the shell script to a suitable location
#
# CDDL HEADER START
#  The contents of this file are subject to the terms of the
#  Common Development and Distribution License, Version 1.0 only
#  (the "License").  You may not use this file except in compliance
#  with the License.
#
#  You can obtain a copy of the license at Docs/cddl1.txt
#  or http://www.opensolaris.org/os/licensing.
#  See the License for the specific language governing permissions
#  and limitations under the License.
# CDDL HEADER END
#
# Example:
#  $ viewreqs.pl
#  Timestamp GETs POSTs HEADs TRACEs
#  19:40:21  39   0     0     0
#  19:40:31  61   0     0     0
#  19:40:41  147  0     0     0


### Standard includes
use Getopt::Std;
use POSIX;

# Process the command line arguments
%options=();
getopts("d:",\%options);

my $delay = $options{d} || 60;

### Global variables
my $heading = 40;
my %methods = ( GET   => 0,
                POST  => 0,
                HEAD  => 0,
                TRACE => 0);

$dtrace = <<END;
/usr/sbin/dtrace -Z -32 -q -n'
::apache_log_request:log-request
{
    /* The method (r->method) is offset 72-bytes in 32-bit Apache */
    this->method =  method = copyinstr(*(uintptr_t *)copyin(arg0 + 72,sizeof(uintptr_t)));
    \@methods[this->method] = count();
}

profile:::tick-${delay}sec
{
   printa("%s %\@d",\@methods);
   printf("\\n");
   trunc(\@methods);
}'
END

open(DTRACE,"$dtrace |") || die "cannot open dtrace $@\n";

while (<DTRACE>) {
    chomp();
    @chunked = split(' ', $_);

    while (@chunked > 0) {
        $methods{shift(@chunked)} += shift(@chunked);
    }

    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
    
    if ($heading == 40) {
        printf("%-9s %-4s %-5s %-5s %-6s\n",Timestamp,GETs,POSTs,HEADs,TRACEs);
        $heading = 0;
    }

    printf("%02d:%02d:%02d  %-4s %-5s %-5s %-6s\n", $hour, $min, $sec,
                              $methods{"GET"}   ? $methods{"GET"} : 0,
                              $methods{"POST"}  ? $methods{"POST"} : 0,
                              $methods{"HEAD"}  ? $methods{"HEAD"} : 0,
                              $methods{"TRACE"} ? $methods{"TRACE"} : 0);
    undef %methods;
}
