WebSVN - scripts - Blame - Rev 10 - /perl/trunk/v1.0/check_memory.pl

thorko Repositories scripts

Rev

Rev 11 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
10 guest 1
#!/usr/bin/perl
2
# check memory consumption of process
3
# author: thorko 2012
4
 
5
use strict;
6
use warnings;
7
use Getopt::Long;
8
use Fcntl qw(:flock);
9
 
10
my $debug = 0;
11
my $help = 0;
12
my $warning = "";
13
my $critical = "";
14
my $processname = "";
15
my $memory;
16
 
17
my $line;
18
my @pids;
19
my $pid;
20
 
21
## help function ###
22
sub help () {
23
        print << 'HELP';
24
check_memory.pl [-d] [-h] -w <warning> -c <crtical> -p <processname>
25
 
26
-p, --pname     process name to check for memory consumption
27
-w, --warning   warning threshold in KB
28
-c, --critical  critical threshold in KB
29
-d, --debug     enable debug mode
30
-h, --help      show help message
31
HELP
32
}
33
 
34
## memusage ##
35
sub memusage {
36
        my $mem;
37
        my ($process) = @_;
38
        open CMD, "ps -o size --no-header $process |" or die("couldn't run ps -o size $process");
39
        $mem = <CMD>;
40
        chomp $mem;
41
        close CMD;
42
        return $mem;
43
}
44
 
45
# get options
46
Getopt::Long::Configure('bundling');
47
GetOptions(
48
        "h|help" => \$help,
49
        "d|debug" => \$debug,
50
        "w|warning=f" => \$warning,
51
        "c|critical=f" => \$critical,
52
        "p|pname=s" => \$processname);
53
 
54
if ( $help ) {
55
        help();
56
        exit(0);
57
}
58
 
59
if ( $processname eq "" || $warning eq "" || $critical eq "" ) {
60
        help();
61
        exit(1);
62
}
63
 
64
flock(DATA, LOCK_EX|LOCK_NB) or die "Program already running.";
65
 
66
# get pid of process
67
open CMD, "pgrep $processname|" or die ("Couldn't run pgrep");
68
while ( $pid = <CMD> ) {
69
        chomp $pid;
70
        push @pids, $pid;
71
        print "pid of $processname: $pid\n" if ($debug);
72
}
73
close CMD;
74
 
75
if ( scalar @pids ) {
76
        # calculate overall memory
77
        foreach (@pids) {
78
                $memory += memusage($_);
79
                print "$_ memory:".memusage($_)."\n" if ( $debug );
80
        }
81
}
82
 
83
# check thresholds
84
if ( $memory > $critical ) {
85
        print "CRITICAL: $processname, memory: $memory KB | memory: $memory KB\n";
86
        exit(2);
87
} elsif ( $memory > $warning ) {
88
        print "WARNING: $processname, memory: $memory KB | memory: $memory KB\n";
89
        exit(1);
90
} else {
91
        print "OK: $processname, memory: $memory KB | memory: $memory KB\n";
92
        exit(0);
93
}
94
 
95
__DATA__