#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2008 RoyaltyShare, Inc.      All Rights Reserved
#---------------------------------------------------------------
package Job::Scheduler::Linux;

use strict;
use warnings;

use Date::Calc;

use lib '/app/tools/common/lib';
use lib '/app/tools/job/lib/';
use Common::Log;
use Common::Util;
use Common::Assert;
use Job::Scheduler;

use base 'Job::Scheduler';

sub wrapperPath {
    Common::RSApp::GetConfig( job => 'job_wrapper_path' );
}

# This process queries the DB for jobs that are running on this box and need to
# be aborted.
#
# Find them and kill 'em all!
sub _killAbortedJobs {
    my $self     = shift;
    my %args     = @_;
    my $hostname = $args{hostname};

    my $collection = Job::DB::Item::Job->GetRunningAbortedJobs($hostname);

    while ( my $job = $collection->next() ) {
        my $pid = $job->pid();
        if ( kill 15 => $pid ) {
            $self->report( "Killed aborted job, job id: " . $job->job_id . " pid: " . $job->pid(), 1 );
        } else {
            $self->report( "Failed to kill job, job id: " . $job->job_id . " pid: " . $job->pid(), 1 );
            $self->report( "$!",                                                                   1 );
        }
    }
}

sub _launchJob {
    my ( $self, $jobID ) = @_;

    die "CONFIG ERROR - Missing wrapperPath" unless defined $self->wrapperPath();

    my $execString = $self->wrapperPath . " -j $jobID";
    $self->report( "execing $execString", 2 );

    # Fork off a child, then exec the job_wrapper.
    # We want to fork, because we don't want the job_scheduler script to have to
    # sit around waiting for the process to finish.
    #
    # We set SIG_CHLD to 'IGNORE', because we don't want to be notified when the
    # child process exits (fire and forget), and we don't want zombies to pile up
    # in the process table.
    #

    $SIG{CHLD} = 'IGNORE';
    my $childPID = fork();
    if ( 0 == $childPID ) {
        exec($execString);
    } else {
        $self->report( "  fork returned child pid: $childPID", 2 );
    }
}

1;
