#!/usr/bin/env expect
############################################################################
# Purpose: Test of scontrol update job for heterogeneous jobs.
############################################################################
# Copyright (C) 2017 SchedMD LLC.
# Written by Isaac Hartung <ihartung@schedmd.com>
# CODE-OCEC-09-009. All rights reserved.
#
# This file is part of Slurm, a resource management program.
# For details, see <https://slurm.schedmd.com/>.
# Please also read the included file: DISCLAIMER.
#
# Slurm 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 2 of the License, or (at your option)
# any later version.
#
# Slurm 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 Slurm; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA.
############################################################################
source ./globals

if {[get_config_param "FrontendName"] ne "MISSING"} {
        skip "This test is incompatible with front-end systems"
} else {
	set task_num 2
}

if {[get_config_param "SchedulerType"] ne "sched/backfill"} {
	skip "This test requires SchedulerType = sched/backfill"
}

set nb_nodes [get_partition_param [default_partition] "TotalNodes"]
if {$nb_nodes < 3} {
	skip "Need 3 or more nodes in default partition"
}

proc cleanup {} {
	global het_job_id scancel

	if {$het_job_id > 0} {
		exec $scancel $het_job_id
	}
}

proc check { id tl matches } {
	global scontrol

	set count 0

	spawn $scontrol show job=$id
	expect {
		-re "TimeLimit=00:0$tl:00" {
			incr count
			exp_continue
		}
		timeout {
			fail "scontrol not responding"
		}
		eof {
			wait
		}
	}
	if {$count != $matches} {
		fail "scontrol failure ($count != 3)"
	}
}

set het_job_id 0
set timeout $max_job_delay
spawn $salloc -t9 -N1 : -N1 : -N1 $bin_bash
expect {
	-re "job ($number) has been allocated resources" {
		set het_job_id $expect_out(1,string)
		reset_bash_prompt
		exp_continue
	}
	-re "$test_prompt" {
		#log_debug "Job initiated"
	}
	timeout {
		fail "salloc: allocation not granted in $timeout seconds"
	}
	eof {
		wait
	}
}
if {$het_job_id == 0} {
	fail "salloc failure"
}

expect *

set timeout 3

check $het_job_id 9 3

exec $scontrol update job=$het_job_id Timelimit=8
check $het_job_id 8 3

exec $scontrol update job=$het_job_id+0 Timelimit=5
check $het_job_id+0 5 1

exec $scontrol update job=$het_job_id+1 Timelimit=6
check $het_job_id+1 6 1

exec $scontrol update job=$het_job_id+2 Timelimit=7
check $het_job_id+2 7 1

check $het_job_id+1 6 1
check $het_job_id+0 5 1
