#!/usr/bin/perl -w # Watchdog daemon, made for watching and restarting of all system elements. use warnings; use POSIX; use File::Pid; use Proc::Background; use POSIX qw(setsid); use lib '/etc/squid/repeater/lib/HTTP'; my $daemonName = "sentinel"; my $dieNow = 0; my $SleepMainLoop = 5; my $logging = 1; my $logFilePath = "/var/log/"; my $logFile = $logFilePath . $daemonName . ".log"; my $pidFilePath = "/var/run/"; my $pidFile = $pidFilePath . $daemonName . ".pid"; my $greylister = Proc::Background->new('/etc/squid/all_ban.pl'); my $repeater = Proc::Background->new('/etc/squid/repeater/lib/repeater.pl'); chdir '/'; umask 0; open STDIN, '/dev/null' or die "Can't read /dev/null: $!"; open STDOUT, '>>/dev/null' or die "Can't write to /dev/null: $!"; open STDERR, '>>/dev/null' or die "Can't write to /dev/null: $!"; defined( my $pid = fork ) or die "Can't fork: $!"; exit if $pid; POSIX::setsid() or die "Can't start a new session."; $SIG{INT} = $SIG{TERM} = $SIG{HUP} = \&signalHandler; $SIG{PIPE} = 'ignore'; my $pidfile = File::Pid->new( { file => $pidFile, } ); $pidfile->write or die "Can't write PID file, /dev/null: $!"; if ($logging) { open LOG, ">>$logFile"; print LOG "Sentinel started.\n"; select((select(LOG), $|=1)[0]); } until ($dieNow) { sleep($SleepMainLoop); if (!$repeater->alive()) { logEntry ("Repeater isn't running, attempting to restart"); $repeater = Proc::Background->new('/etc/squid/repeater/lib/repeater.pl'); } if (!$greylister->alive()) { logEntry ("Greyliter isn't running, attempting to restart"); $greylister = Proc::Background->new('/etc/squid/all_ban.pl'); } } sub logEntry { my ($logText) = @_; my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = localtime(time); my $dateTime = sprintf "%4d-%02d-%02d %02d:%02d:%02d", $year + 1900, $mon + 1, $mday, $hour, $min, $sec; if ($logging) { print LOG "$dateTime $logText\n"; } } sub signalHandler { $dieNow = 1; } END { if ($logging) { close LOG } $pidfile->remove if defined $pidfile; }