#!/usr/bin/env expect
############################################################################
# Purpose: Test of Slurm functionality
#          Test heterogeneous job GPU allocations.
############################################################################
# Copyright (C) 2019 SchedMD LLC
# Written by Morris Jette
#
# 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.,
# 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
############################################################################
source ./globals

set file_in1       "$test_dir/input1"
set file_in2       "$test_dir/input2"
set number_commas  "\[0-9_,\]+"

if {![check_config_select "cons_tres"]} {
	skip "This test is only compatible with select/cons_tres"
}
if {[get_config_param "FrontendName"] ne "MISSING"} {
	skip "This test is incompatible with front-end systems"
}
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 < 2} {
	skip "This test requires 2 or more nodes in the default partition"
}
set nb_nodes 2
set gpu_cnt [get_highest_gres_count $nb_nodes "gpu"]
if {$gpu_cnt < 1} {
	skip "This test requires 1 or more GPUs on $nb_nodes nodes of the default partition"
}

#
# Build input script files
#
make_bash_script $file_in1 "$scontrol -dd show job \$SLURM_JOB_ID
$srun --mpi=none --het-group=0,1 -l $file_in2
exit 0"

make_bash_script $file_in2 "echo HOST:\$SLURMD_NODENAME CUDA_VISIBLE_DEVICES:\$CUDA_VISIBLE_DEVICES"

set timeout $max_job_delay
set match   0
spawn $salloc --gpus=$gpu_cnt --nodes=1 -t1 -J $test_name : --gpus=1 --nodes=1 $file_in1
expect {
	-re "($number): HOST:($re_word_str) CUDA_VISIBLE_DEVICES:($number_commas)" {
		set gpu_alloc [cuda_count $expect_out(3,string)]
		if {$expect_out(1,string) == 0 && $gpu_alloc == $gpu_cnt} {
			incr match
		}
		if {$expect_out(1,string) == 1 && $gpu_alloc == 1} {
			incr match
		}
		exp_continue
	}
	timeout {
		fail "salloc not responding"
	}
	eof {
		wait
	}
}
if {$match != 2} {
	fail "Invalid heterogeneous job output ($match != 2)"
}
