remove debugging
[freeside.git] / bin / monitor
1 #!/usr/bin/perl -w
2
3 use strict;
4 use vars qw( $DEBUG );
5 use Getopt::Std;
6 use FS::Daemon qw(daemonize1 daemonize2 logfile sigint sigterm);
7 use FS::Yori qw(report);
8 use Email::Send;
9
10 $DEBUG = 0;
11
12 &untaint_argv;  #what it sounds like  (eww)
13
14 use vars qw(%opt);
15 getopts('m:p:', \%opt );
16
17 my ($machine, @emails) = @ARGV;
18 die &usage unless @emails;
19
20 warn "starting daemonization (forking)\n" if $DEBUG;
21 daemonize1('freeside-monitor');
22 #logfile( "%%%FREESIDE_LOG%%%/monitorlog.$machine" );
23 logfile( "/usr/local/etc/freeside/monitorlog.$machine" );
24
25 warn "completing daemonization (detaching))\n" if $DEBUG;
26 daemonize2();
27
28 my $wantfree = $opt{m} || 1048576;
29 my $wantload = $opt{p} || 5;
30
31 die 'bogus memory requirement: $wantfree'
32    unless $wantfree && $wantfree =~ /^\d+$/;
33
34 die 'bogus load requirement: $wantload'
35    unless $wantload && $wantload =~ /^[\d.]+$/;
36
37 my $alerts = 0;
38 my $last = time();
39 while (1) {
40
41   my(undef, $load, undef) = report('load');
42   my($free) = report('freememory');
43   
44   unless( defined($load) && $load < $wantload
45        && defined($free) && $free > $wantfree
46        || ( time() < $last + 1800 && $alerts > 2 ) )
47   {
48     warn localtime(). ": $machine has load of $load and $free kB free memory\n";
49     $alerts++;
50     $alerts = 0 if time() > $last + 1800;
51     $last = time();
52     foreach my $email ( @emails ) {
53
54       my $message = <<"__MESSAGE__";
55 From: support\@freeside.biz
56 To: $email
57 Subject: ALERT - $machine
58
59 ALERT: $machine has a load of $load and only $free kB free..
60
61 __MESSAGE__
62
63     my $sender = Email::Send->new({mailer => 'SMTP'});
64     $sender->mailer_args([Host => 'mail.freeside.biz']);
65     $sender->send($message);
66
67     }
68
69   }
70
71
72
73   if ( sigterm() ) {
74     warn "received TERM signal; exiting\n";
75     exit;
76   }
77   if ( sigint() ) {
78     warn "received INT signal; exiting\n";
79     exit;
80   }
81
82   sleep 30; #too long?  too short?
83
84 }
85
86 sub untaint_argv {
87   foreach $_ ( $[ .. $#ARGV ) { #untaint @ARGV
88     $ARGV[$_] =~ /^([\w\-\/\@\.]*)$/ || die "Illegal arguement \"$ARGV[$_]\"";
89     $ARGV[$_]=$1;
90   }
91 }
92
93 sub usage {
94   die "Usage:\n\n  freeside-monitor [ -pm ] machine email\n";
95 }
96
97 =head1 NAME
98
99 freeside-monitor - Perform some basic load monitoring
100
101 =head1 SYNOPSIS
102
103   freeside-monitor [ -p MAXLOAD ] [ -m REQUIRED_FRERMEM ] machine email [ ... ]
104
105 =head1 DESCRIPTION
106
107 Load monitoring daemon.  Should be running at all times.
108
109 -p: maximum permitted 5 minute load
110
111 -m: minimum free vmem in kB
112
113 machine: a unique name to be used in alert messages
114 email: address(es) to which alerts should be sent
115
116 =head1 VERSION
117
118 =head1 BUGS
119
120 =head1 SEE ALSO
121
122 =cut
123