https://bitbucket.org/cmungall/galaxy-obo
Tip revision: 3e0af213ccd1388ef0107156903a309bf423b0bd authored by Chris Mungall on 31 May 2013, 17:50:52 UTC
add amelias scripts
add amelias scripts
Tip revision: 3e0af21
staying-alive.pl
#!/usr/bin/perl
my $pidfile;
my $logfile;
my $init;
my $kill;
my $killsig = 9;
my $restart;
while ($ARGV[0] =~ /^\-/) {
my $opt = shift @ARGV;
print STDERR "opt='$opt'\n";
if ($opt eq '-f' || $opt eq '--pidfile') {
$pidfile = shift @ARGV;
}
elsif ($opt eq '-l' || $opt eq '--logfile') {
$logfile = shift @ARGV;
}
elsif ($opt eq '-i' || $opt eq '--initfile') {
$init = shift @ARGV;
}
elsif ($opt eq '-r' || $opt eq '--restart') {
$restart = 1;
}
elsif ($opt eq '-k' || $opt eq '--kill') {
$kill = 1;
}
elsif ($opt eq '-s' || $opt eq '--kill-sig') {
$killsig = shift @ARGV;
}
elsif ($opt eq '-h' || '--help') {
print usage();
exit 0;
}
}
if (!$pidfile) {
$pidfile = $ARGV[0].".pid";
}
my $pid;
if (-f $pidfile) {
open(F,$pidfile);
$pid = <F>;
chomp $pid;
close(F);
}
if ($kill || $restart) {
my $ok = 1;
if ($pid) {
# -ve PID kills process group
# http://stackoverflow.com/questions/2618403/how-to-kill-all-subprocesses-of-shell
if (system("kill -$killsig -$pid")) {
# failed to kill
if (is_running($pid)) {
print STDERR "Cannot kill $pid\n";
die;
}
else {
if ($kill) {
print STDERR "Cannot kill $pid, as it is not running\n";
}
}
}
else {
if (is_running($pid)) {
print STDERR "attempt to kill -s $killsig $pid failed\n";
die;
}
else {
print STDERR "Killed $pid\n";
if ($restart) {
sleep(3);
}
}
}
}
else {
print STDERR "No process running\n";
if ($kill) {
die;
}
}
if ($kill) {
exit 0;
}
}
if ($pid) {
if (is_running($pid)) {
print STDERR "process running: $pid\n";
exit 0;
}
print STDERR "process not found: $pid -- will start a new process\n";
}
else {
print STDERR "No existing process\n";
}
open(F,">$pidfile") || die $pidfile;
print F "$$\n";
close(F);
my $cmd = "@ARGV";
if ($init) {
$cmd = ". $init; $cmd";
}
if ($logfile) {
print STDERR "Logging to $logfile\n";
print STDERR "running command $cmd\n";
system("$cmd > $logfile 2>&1");
system("tail -f $logfile");
}
else {
print "running command $cmd\n";
system($cmd);
}
exit 0;
sub scriptname {
my @p = split(/\//,$0);
pop @p;
}
sub is_running {
my $pid = shift;
my @procs = split(/\n/,`ps ax`);
my $is_running = 0;
foreach (@procs) {
my ($x) = split(' ',$_);
#print STDERR "$foo // $x ps: $_\n";
if ($x eq $pid) {
$is_running = 1;
break;
}
}
return $is_running;
}
sub usage {
my $sn = scriptname();
<<EOM;
$sn [--pidfile PIDFILE] [--logfile LOGFILE] CMD [ARGS]
Example crontab:
* * * * 45 staying-alive.pl "my-server"
EOM
}