#!/usr/bin/perl -Tw # These prevent taint checking failures $ENV{PATH} = '/bin:/usr/bin'; delete @ENV{qw(IFS CDPATH ENV BASH_ENV)}; use strict; use diagnostics; use vars qw($VERSION $ua); $VERSION = '0.01'; require LWP::UserAgent; ###### Config ######## my $test_script_url = 'http://www.example.com:81/perl/test.pl'; my $monitor_email = 'root@localhost'; my $restart_command = '/home/httpd/httpd_perl/bin/apachectl restart'; my $mail_program = '/usr/lib/sendmail -t -n'; ###################### $ua = LWP::UserAgent->new; $ua->agent("$0/watchdog " . $ua->agent); # Uncomment the following two lines if running behind a firewall # my $proxy = "http://www-proxy"; # $ua->proxy('http', $proxy) if $proxy; # If it returns '1' it means that the service is alive, no need to # continue exit if checkurl($test_script_url); # Houston, we have a problem. # The server seems to be down, try to restart it. my $status = system $restart_command; my $message = ($status == 0) ? "Server was down and successfully restarted!" : "Server is down. Can't restart."; my $subject = ($status == 0) ? "Attention! Webserver restarted" : "Attention! Webserver is down. can't restart"; # email the monitoring person my $to = $monitor_email; my $from = $monitor_email; send_mail($from, $to, $subject, $message); # input: URL to check # output: 1 for success, 0 for failure ####################### sub checkurl { my($url) = @_; # Fetch document my $res = $ua->request(HTTP::Request->new(GET => $url)); # Check the result status return 1 if $res->is_success; # failed return 0; } # send email about the problem ####################### sub send_mail { my($from, $to, $subject, $messagebody) = @_; open MAIL, "|$mail_program" or die "Can't open a pipe to a $mail_program :$!\n"; print MAIL <<__END_OF_MAIL__; To: $to From: $from Subject: $subject $messagebody Your faithful watchdog __END_OF_MAIL__ close MAIL or die "failed to close |$mail_program: $!"; }