#!/usr/bin/perl
use strict;
use warnings;
use Config;
use POSIX qw<setsid>;
use FindBin qw<$RealBin>;
use IO::Handle;
use Fcntl;
use File::Spec::Functions;

delete $ENV{$_} for qw<HUDSON_SERVER_COOKIE BUILD_TAG JENKINS_HOME
  JENKINS_SERVER_COOKIE HUDSON_HOME HUDSON_COOKIE>;
$ENV{JENKINS_PROCGUARD_MONITOR_PID} = $$;

my ( $p_read, my $p_write );
pipe $p_read, $p_write
  or die "Failed to open pipe: $!";
$p_read->autoflush(1);
$p_write->autoflush(1);

my $child = fork();
die "Failed to fork: $!"
  unless defined $child;
if ( !$child ) {
    close $p_read;

    # do a fork+setsid to detach from the guard process and exec the
    # command that was given.
    if (fork) {
        # detach from the parent.
        exit 0;
    }
    my $sid = POSIX::setsid();
    if ( $sid == -1 ) {
        warn "jenkins-procguard: @ARGV: Failed to setsid: $!";
    }

    my $flags = fcntl $p_write, F_GETFD, 0;
    fcntl $p_write, F_SETFD, $flags & ~FD_CLOEXEC;

    # re-exec self in order to clean /proc/$$/environ
    my $m = catfile( $RealBin, 'jenkins-procguard-monitor' );
    exec $m, fileno($p_write), @ARGV
      or die "jenkins-procguard: @ARGV: Failed to exec $m: $!";
} else {
    close $p_write;
    waitpid $child, 0;    # make sure we got the detached process.

    my $grandchild = <$p_read>;
    if ( !$grandchild ) {
        die "jenkins-procguard: @ARGV: Failed to monitor process.\n";
    }
    chomp $grandchild;
    warn "jenkins-procguard: @ARGV: real process is $grandchild\n";

    my $sig_handler = sub {
        my $signame = shift;
        kill $signame, $grandchild;
    };

    # install all process handlers to the forwarder.
    foreach my $s ( split /\s+/, $Config{sig_name} ) {
        next if $s eq 'ZERO';
        $SIG{$s} = $sig_handler;
    }

    while ( kill 0, $grandchild ) {
        sleep 1;
    }

    my $exitcode = <$p_read>;
    if (defined $exitcode) {
        chomp $exitcode;
        if ($exitcode eq 'N/A') {
            warn "jenkins-procguard: @ARGV: process disappeared\n";
            exit 98;
        } else {
            my $code   = $exitcode >> 8;
            my $signal = $exitcode & 127;
            if ($signal) {
                warn "jenkins-procguard: @ARGV: Signal $signal\n";
            }
            exit $code;
        }
    } else {
        warn "jenkins-procguard: @ARGV: failed to catpure exit code\n";
        exit 99;
    }
}

__END__

=head1 NAME

jenkins-procguard - run a process that jenkins won't try to kill

=head1 SYNOPSIS

  jenkins-procguard command arg1 arg2 ...

=head1 DESCRIPTION

Runs a subprocess in a separate process tree and without the Jenkins
environment variables that it uses to find processes.

It will detach the subprocess from the process tree by using setsid,
but it will monitor that process and send whatever signals are sent to
this process to the process being monitored, and will only exit once
the other process has exitted.

=head1 ENVIRONMENT

This will remove any of the documented jenkins job variables from the
process before the fork and exec. It will also set
JENKINS_PROCGUARD_MONITOR_PID with the pid of the process that is
monitoring it.

=head1 EXIT CODE

The guard will open a pipe between the two sides to send back the exit
status when the monitored process exits.

=head1 COPYRIGHT

Copyright 2016 Bloomberg Finance L.P.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

