#!/local/bin/perl
#
# cfload.pl
#
# A GNU/Cfengine module to determine the system load on the current
# box, and define the following classes:
#
# CLASSES DEFINED BY THIS MODULE:
# -------------------------------
# CPUmax CPUhigh CPUmedium CPUlow
# MEMmax MEMhigh MEMmedium MEMlow
#
# In order for the correct classes to be defined, these are all mutually
# exclusive in their own family. (E.g. you cannot have both CPUhigh and
# CPUmedium.) Because of this, cfload.pl also undefines the other
# classes when defining a class.
#
# Copyright (C) 1998 Thomas Aardal Hanssen
# Copyright (C) 1998 Oslo College of Engineering
#

$TotalCPU = 0;
$TotalMEM = 0;

&GetPS;
&DefineLoadCPU;
&DefineLoadMEM;

sub GetPS {

    open (FH, "ps wwaux |") or die "Could not open ps pipe!\n";
    while($Line = <FH>) {
	chomp $Line;
	
	# Skip the title line.
	next if ($Line =~ m/\s*USER/);

	($Owner,$Pid,$CPU,$MEM,$VSZ,$RSS,$TT,$STAT,$START,$TIME,$CMD) =
	    split(" ", $Line, 11);

	$TotalCPU += $CPU;
	$TotalMEM += $MEM;
    }
    close (FH);

}

sub DefineLoadCPU {

    # Low load defined to < 30 % cpu usage
    if ($TotalCPU < 30) {
	print "-CPUmax\n";
	print "-CPUhigh\n";
	print "-CPUmedium\n";
	print "+CPUlow\n";
    }
    # Medium load defined to > 30 % < 60 % cpu usage
    elsif ($TotalCPU < 60) {
	print "-CPUmax\n";
	print "-CPUhigh\n";
	print "-CPUlow\n";
	print "+CPUmedium\n";
    }
    # High load defined to > 60 % < 90 % cpu usage
    elsif ($TotalCPU < 90) {
	print "-CPUmax\n";
	print "-CPUmedium\n";
	print "-CPUlow\n";
	print "+CPUhigh\n";
    }
    # Max load defined to > 90 % cpu usage
    else {
	print "-CPUhigh\n";
	print "-CPUmedium\n";
	print "-CPUlow\n";
	print "+CPUmax\n";
    }
}

sub DefineLoadMEM {

    # Low memory consumtion defined to < 30 % usage
    if ($TotalMEM < 30) {
	print "-MEMmax\n";
	print "-MEMhigh\n";
	print "-MEMmedium\n";
	print "+MEMlow\n";
    }
    # Medium memory consumption defined to > 30 % < 60 % usage
    elsif ($TotalMEM < 60) {
	print "-MEMmax\n";
	print "-MEMhigh\n";
	print "-MEMlow\n";
	print "+MEMmedium\n";
    }
    # High memory consumption defined to > 60 % < 90 % usage
    elsif ($TotalMEM < 90) {
	print "-MEMmax\n";
	print "-MEMmedium\n";
	print "-MEMlow\n";
	print "+MEMhigh\n";
    }
    # Max memory consumption defined to > 90 % usage
    else {
	print "-MEMhigh\n";
	print "-MEMmedium\n";
	print "-MEMlow\n";
	print "+MEMmax\n";
    }
}

