#! /usr/bin/env perl
##**************************************************************
##
## Copyright (C) 1990-2012, Condor Team, Computer Sciences Department,
## University of Wisconsin-Madison, WI.
## 
## 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.
##
##**************************************************************

use CondorTest;
use CondorUtils;
use Check::SimpleJob;

my $testname = "job_partitionable_basic_van";

# personal condor, with 5 partitionable slots, 4 cpus each (total 20 cpus)
# set the negotiator interval down to so test runs faster.
# also set CLAIM_PARTITIONABLE_LEFTOVERS to false - with it
# set to true (which is the default), there is no guarantee that
# the dynamic slots will be evenly divided across the partitionable
# slots like this test expects.
#testreq: personal
my $config = <<CONDOR_TESTREQ_CONFIG;
  DAEMON_LIST = MASTER,SCHEDD,COLLECTOR,NEGOTIATOR,STARTD
  NEGOTIATOR_INTERVAL = 5
  NUM_CPUS = 20
  SLOT_TYPE_1 = cpus=20
  SLOT_TYPE_1_PARTITIONABLE = TRUE
  NUM_SLOTS_TYPE_1 = 1
  CLAIM_PARTITIONABLE_LEFTOVERS = true
CONDOR_TESTREQ_CONFIG
#endtestreq

my $test_passed = 0;
my $callbacks = 1;
my $callback_limit = 10;


sub timed_callback {
    my %args = @_;
    my $cluster = $args{"cluster"};
	my @resarray = ();

	my $stat;
	if(is_windows()) {	
    	$stat = runCondorTool('condor_status -af ifThenElse(PartitionableSlot=?=TRUE,\"P\",ifThenElse(DynamicSlot=?=TRUE,\"D\",\"S\")) -af State -af Activity -af Cpus',\@resarray,2);
	} else {
    	$stat = runCondorTool("condor_status -format \"%s\" \'ifThenElse(PartitionableSlot =?= TRUE, \"P\", ifThenElse(DynamicSlot =?= TRUE, \"D\", \"S\"))' -format \" %s\" State -format \" %s\" Activity -format \" %s\n\" Cpus",\@resarray,2);
	}

    my $expected_pslots = 0;
    my $expected_dslots = 0;
    my $unexpected = 0;

    my @slines = split /\n/, $stat;
    foreach my $line (@resarray) {
		chomp($line);
        my @f = split ' ', $line;
        if ($f[0]=="P"  &&  $f[1]=="Unclaimed"  &&  $f[2]=="Idle"  &&  $f[3]=="10") {
            $expected_pslots += 1;
        } elsif ($f[0]=="D"  &&  $f[1]=="Claimed"  &&  $f[2]=="Busy"  &&  $f[3]=="1") {
            $expected_dslots += 1;
        } else {
            $unexpected += 1;
        }
    }

    # I'm looking for this slot pattern to show up if things are working correctly:
    # 5 partitionable slots unclaimed/idle with 2 slots left
    # 10 dynamic slots claimed/busy with 1 slot
    # and there should be no other slots
	print "expected_pslots(1) <$expected_pslots> expected_dslots(10) <$expected_dslots> unexpected(0) <$unexpected>\n";
    if ($expected_pslots==1  &&  $expected_dslots==10  &&  $unexpected==0) {
        $test_passed = 1;
		print "SUCCESS!  Saw the correct breakdown of slots.\n";
		print "Will now condor_rm job.\n";

		# Now remove 
		my @adarray;
		my $cmd = "condor_rm $cluster";
		my $status = runToolNTimes($cmd,1,0);
		if(!$status) {
	    	print "bad, runToolNTimes failed\n";
	    	CondorTest::debug("Test failure due to Condor Tool Failure<$cmd>\n", 1);
	    	exit(1)
		}
    } else {
		print "Haven't seen expected condor_status output (yet).  What I saw was...\n";
		print $stat;
		print "condor_status shows\n";
		runToolNTimes("condor_status",1);
		# Timed call backs only fire once now.
		CondorTest::debug("Registering another callback to recheck in 15 seconds\n",1);
		$callbacks += 1;
		if($callbacks < $callback_limit) {
			CondorTest::RegisterTimed($testname, \&timed_callback, 15);
		} else {
			print "Callback limet exceeded:$callback_limit Failure\n";
			exit(1);
		}
    }
}


sub exit_success_callback {
    # by this time we had better have seen the slot pattern we were looking for
    unless ($test_passed) {
        die "Failed to find expected pattern of partitionable and dynamic slots";
    }
}

my $abort = sub {
    # We will hit this if we condor_rm the job, which we do after seeing the correct pattern.
    if($test_passed) {
	#CondorTest::debug("Job successfully condor_rm'ed after seeing correct pattern.\n", 1);
    }
    else {
	die "Job aborted, but \$test_passed is not True\n";
    }
};



my $on_evictedwithoutcheckpoint = sub {
	#CondorTest::debug("Evicted Without Checkpoint from removing jobs.\n",1);
};

my $on_submit = sub {
};

sub on_update {
};

$result = SimpleJob::RunCheck(
	test_name => "$testname",
	on_abort => $abort,
	on_evictedwithoutcheckpoint => $on_evictedwithoutcheckpoint,
	on_execute => $on_execute,
	on_submit => $on_submit,
	on_imageupdated => \&on_update,
	alt_timed => \&timed_callback,
	on_success => \&exit_success_callback,
	timeout => 15,
	queue_sz => 10,
	duration => 3600,
	request_memory => 1,
	#GetClusterId => $GetClusterId,
);
print "******************** Test for KILL = TRUE\n";
if($result == 1) {
	print "ok\n\n\n";
} else {
	print "bad\n\n\n";
}

CondorTest::EndTest();
