Date: 2011may5
OS: Linux
Warning: Obsolete since /sbin/service
Q. Linux: How can I make sure all my services are running?
I want to restart a service it crashes.
A. I run the following script every 5 minutes and it does the trick.
Will only work on RedHat/Fedora/CentOS.
cron entry:
# minute hour mday month wday command
# 0-59 0-23 0-31 0-12 0-6 (0=Sun)
#
*/5 * * * * /usr/local/bin/service_check_all_cron
Here is /usr/local/bin/service_check_all_cron:
#!/usr/bin/perl
# This is intended to be run from cron
use strict;
sub getServices() {
local(*FILE);
my($line, @services, $service, $status);
open(FILE, '/sbin/chkconfig --list 2>/dev/null |');
while ($line = <FILE>) {
chomp($line);
if ($line =~ m/^(\w+).+5:(\w+)/) {
$service = $1;
$status = $2;
if ($status eq 'on') {
push(@services, $service);
}
}
}
close(FILE);
return @services;
}
sub getStatus($) {
my($service) = @_;
local(*FILE);
my($line, $status);
# Not all services support "status"
$status = 'unknown';
open(FILE, "/sbin/service $service status 2>&1 |");
while ($line = <FILE>) {
chomp($line);
if ($line =~ m/\sis\s+(.+)/) {
$status = $1;
$status =~ s/\.+//g;
}
elsif ($line =~ m/dead/) {
$status = 'dead';
}
elsif ($line =~ m/Active:\s(.+)/) {
my $active = $1;
if ($active =~ m/\((.*)\)/) {
$status = $1;
}
}
}
close(FILE);
return $status;
}
sub uptime() {
local(*FILE);
my($line);
open(FILE, "uptime 2>&1 |");
while ($line = <FILE>) {
chomp($line);
print "UPTIME: $line\n";
}
close(FILE);
}
sub restart($) {
local(*FILE);
my($service) = @_;
my($line);
open(FILE, "/sbin/service $service restart 2>&1 |");
while ($line = <FILE>) {
chomp($line);
print "RESTART: $line\n";
}
close(FILE);
}
my(%g_no_restart) =
(
cpuspeed => 1,
mdmonitor => 1,
portreserve => 1,
ip6tables => 1,
irqbalance => 1,
iptables => 1,
netfs => 1,
mcstrans => 1,
);
sub checkServices(@) {
my(@services) = @_;
my($service, $status);
my($restarted) = 0;
for $service (@services) {
if ($g_no_restart{$service}) { next; }
$status = getStatus($service);
## print "$service is $status\n";
sleep(1);
if ($status eq 'unknown') { next; }
if (!($status eq 'running' || $status eq 'active')) {
if ($restarted == 0) {
uptime();
}
print "Restarting $service because it is $status\n";
restart($service);
$restarted++;
}
}
## print "Restarted $restarted services\n";
}
sub main() {
my(@s);
@s = getServices();
my $n = scalar @s;
## print "There are $n services\n";
sleep(1);
checkServices(@s);
}
main();