#!/usr/bin/env perl
#
# atimeout -- alternative to coreutils timeout
#
# Run a command with a timeout.  Optionally send a signal and/or run a
# command on timeout.  Exits with the exit status of the command, or
# 254 if timeout happened first.
#
# Copyright (c) 2010 Adam Spiers <adam@spiers.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

use strict;
use warnings;

use Config;
use Getopt::Long qw(:config require_order no_ignore_case);
use POSIX qw(:sys_wait_h setsid);

my %opts = ( zero => 0 );

sub debug {
  if ($opts{verbose}) {
    warn @_, "\n" ;
  }
  if ($opts{log}) {
    if (my $logfile = $opts{log}) {
      open(LOG, ">>$logfile")
        or die "Couldn't open(>$logfile): $!\n";
      print LOG @_, "\n";
      close(LOG);
    }
  }
}

(my $ME = $0) =~ s,.*/,,;

my @signals = split ' ', $Config{sig_name};
die "$ME: BUG reading signal names" unless $signals[9] eq 'KILL';
my %num2sig = map { $_ => $signals[$_] } 0 .. $#signals;
# Getopt::Long is case-insensitive by default.
my @signal_opts = map "$_|$num2sig{$_}", 0..$#signals;

GetOptions(
  \%opts,
  'help|h', 'verbose|v', 'log|l=s',
  @signal_opts, 'no-signals|n',
  'zero|z',
  'command|c=s',
) or usage();
usage() if @ARGV == 0 or $opts{help};
my $signum = get_signal();

sub usage {
  warn @_, "\n" if @_;

  die <<EOUSAGE;
Usage: $ME [options] TIMEOUT COMMAND ARGS
Timeout is in seconds, or can be a time parseable by the -d option of date(1).

Options:
  -h, --help             Show this help
  -N, -SIG               On timeout, send signal SIG (e.g. 9 or KILL)
  -c, --command=CMD      On timeout, run command
  -l, --log=LOGFILE      Log to LOGFILE
  -n, --no-signals       Disable default graceful killing
  -v, --verbose          Show progress in more detail
  -z, --zero             Zero exit code even on timeout 

If no signal is specified, by default it will send a TERM signal, and then a
KILL signal if needed.  --no-signals disables this default;
this is useful with the --command option.

The signal gets sent to the child's process group, not just the child.
That's to deal with the case where the child is a shell process.  So?
Signal handlers in bash are ineffectual while bash is blocking on a
waitpid(-1), and I can't see how to avoid this waitpid, because the script
needs to wake up and do other stuff once its child has completed.

The exit code returned will be that of the child COMMAND, or if there
was a timeout 254 (or 0 if -z or --zero are specified).

Termination signals received by this program will result in the child
COMMAND being gracefully terminated.
EOUSAGE
}

usage() unless @ARGV >= 2;
my ($timeout, $command, @args) = @ARGV;
if ($timeout !~ /^\d+$/) {
  my $date_cmd = qq{date -d "$timeout" +%s};
  my $timeout_at = `$date_cmd`;
  if ($? >> 8) {
    usage("Failed to parse timeout time via: $date_cmd\n");
  }
  $timeout = $timeout_at - time();
  usage("Timeout time was in the past!\n") if $timeout < 0;
  
  debug("Timeout at epoch $timeout_at ($timeout seconds from now)");
}

my $pid = fork();
if (! $pid) {
  # child
  setsid; # run as daemon
  exec $command, @args;
}

# parent
debug("child pid is $pid");

$SIG{INT} = $SIG{QUIT} = sub {
  if ($pid) {
    $opts{verbose}++;
    send_signal(15, $pid);
    murder_if_necessary($pid);
  }
};

$SIG{ALRM} = sub {
  debug("pid $pid timed out after $timeout seconds");
  if (defined $signum) {
    send_signal($signum, $pid);
    murder_if_necessary($pid) if $opts{graceful};
  }
  system($opts{command}) if defined $opts{command};
  exit ($opts{zero} ? 0 : 254);
};
alarm $timeout;
debug("alarm set");

wait;
if ($? == -1) {
  # -1 means no children were found to wait for.
  exit 0;
}

my $child_exit_code = $? >> 8;
debug("wait finished with code $child_exit_code");
exit $child_exit_code;

# Which signal to send on timeout?
sub get_signal {
  my $count = 0;
  my $signum;
  foreach my $opt (keys %opts) {
    debug("Got option: -$opt");
    if ($opt =~ /^\d+$/) {
      $count++;
      $signum = $opt;
    }
  }
  usage("Cannot specify more than one signal via -N / -SIG\n")
    if $count > 1;

  usage("Cannot specify a signal and --no-signals\n")
    if $count and $opts{'no-signals'};

  if ($count == 0 and ! $opts{'no-signals'}) {
    $signum = 15;
    $opts{graceful} = 1;
  }

  return $signum;
}

sub send_signal {
  my ($signum, $pid) = @_;

  if (my $pgrp = getpgrp($pid)) {
    debug("\nSending signal $signum to pgrp $pgrp ...");
    kill -$signum, $pgrp;
  }
  elsif (defined $pid) {
    warn "WTF? pid $pid exists but getpgrp($pid) failed"; 
    debug("Sending signal $signum to pid $pid");
    kill $signum, $pid;
  }
}

sub murder_if_necessary {
  my ($pid) = @_;
  my $pgrp;
  my $tries = 0;
  do {
    waitpid($pid, WNOHANG);     # reap zombie
    $pgrp = getpgrp($pid);
    if (getpgrp($pid) > 0) {
      debug("pid $pid still exists; sleeping a second ...");
      sleep 1;
      $tries++;
    }
  } while $pgrp > 0 and $tries < 3;
  if ($pgrp > 0) {
    debug("pid $pid STILL exists; sending KILL to pgrp $pgrp");
    kill, $pid;
  }
}
