#!/usr/bin/env expect
############################################################################
# Purpose: Test of Slurm functionality
#          Test some valid combinations of srun --gpu options
############################################################################
# Copyright (C) 2018 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 skipped        ""
set file_in1       "$test_dir/input1"
set file_in2       "$test_dir/input2"
set number_commas  "\[0-9_,\]+"
set one_task_pc    0


proc _test_gpus_cnt {cmd expected_gpus_times_tasks expected_job_gpus} {
	set match 0
	set job_gpus 0
	set output [run_command_output $cmd]
        if [regexp {JOB_GRES=(\S+)} $output {} gres_string] {
                set gres_dict [count_gres $gres_string]
                if [dict exists $gres_dict "gpu"] {
                        set job_gpus [dict get $gres_dict "gpu"]
                }
        }
        foreach {- cuda_string} [regexp -all -inline {CUDA_VISIBLE_DEVICES:([0-9_,]+)} $output] {
                incr match [cuda_count $cuda_string]
        }
	subtest {$match == $expected_gpus_times_tasks} "$cmd tasks*gpus result=$match, expected=$expected_gpus_times_tasks"
	subtest {$job_gpus == $expected_job_gpus} "$cmd JOB_GRES result=$job_gpus, expected=$expected_job_gpus"
}

proc test_gpus_cnt {srun_opts expected_gpus_times_tasks expected_job_gpus} {
	global file_in1 srun number_commas bin_cat test_name
	set expected_failure false
	if {$expected_gpus_times_tasks == 0 && $expected_job_gpus == 0} {
		set expected_failure true
	}

	_test_gpus_cnt "$srun $srun_opts -t1 -J $test_name -l $file_in1" $expected_gpus_times_tasks $expected_job_gpus

	if {$expected_failure} {
		set jobid [submit_job -xfail -subtest "$srun_opts -t1 -J sbatch_$test_name --wrap='$srun -l $file_in1'"]
	} else {
		set jobid [submit_job -subtest "$srun_opts -t1 -J sbatch_$test_name --wrap='$srun -l $file_in1'"]
		if {$jobid != 0} {
			if {[wait_for_job -pollinterval 0.1 $jobid "DONE"] != 0} {
				fail "Job did not complete within timeout"
			}
			if {[wait_for_file -pollinterval 0.1 "./slurm-$jobid.out"]} {
				fail "No output created within timeout"
			}
			_test_gpus_cnt "$bin_cat ./slurm-$jobid.out" $expected_gpus_times_tasks $expected_job_gpus
			run_command "rm ./slurm-$jobid.out"
		} else {
			subskip -count 2 "Skipping #GPUs * #NTASKS and #GPUS subtests since job submit failed"
		}
	}
}

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"
}

set nb_nodes [get_partition_param [default_partition] "TotalNodes"]
if {$nb_nodes > 1} {
	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"
}
# Determine what the selecttype param is
if {[param_contains [get_config_param "SelectTypeParameters"] "CR_ONE_TASK_PER_CORE"]} {
	set one_task_pc 1
}

set node_name [get_nodes_by_request "--gres=gpu:1 -n1 -t1"]
if { [llength $node_name] != 1 } {
	skip "This test need to be able to submit jobs with at least --gres=gpu:1"
}
set cpus_per_node     [get_node_param $node_name "CPUTot"]
set sockets_per_node  [get_node_param $node_name "Sockets"]
set threads_per_core  [get_node_param $node_name "ThreadsPerCore"]
set cores_per_socket  [get_node_param $node_name "CoresPerSocket"]
set cpus_per_socket   [expr $cpus_per_node / $sockets_per_node]

log_debug "GPU count is $gpu_cnt"
log_debug "Sockets per node is $sockets_per_node"
log_debug "CPUs per socket is $cpus_per_socket"

if {$gpu_cnt > $cpus_per_node} {
	set gpu_cnt $cpus_per_node
}

set tot_gpus $gpu_cnt
if {$nb_nodes > 1} {
	incr tot_gpus $gpu_cnt
}
set gpus_per_node $gpu_cnt
if {$gpus_per_node > 1 && $sockets_per_node > 1} {
	set gpus_per_socket [expr $gpus_per_node / $sockets_per_node]
} else {
	set gpus_per_socket $gpus_per_node
}

#
# Build input script files
#
make_bash_script $file_in1 "echo HOST:\$SLURMD_NODENAME CUDA_VISIBLE_DEVICES:\$CUDA_VISIBLE_DEVICES
if \[ \$SLURM_PROCID -eq 0 \]; then
$scontrol -dd show job \$SLURM_JOB_ID | grep JOB_GRES=
fi
exit 0"

make_bash_script $file_in2 "echo HOST:\$SLURMD_NODENAME CUDA_VISIBLE_DEVICES:\$CUDA_VISIBLE_DEVICES
$scontrol show node \$SLURM_JOB_NODENAME | grep Gres
exit 0"

#
# Test --gpus options using a subset of GPUs actually available on the node
#
log_info "TEST: --gpus option"
set match 0
set timeout $max_job_delay
if {$tot_gpus > 1} {
	set use_gpus_per_job [expr $tot_gpus - 1]
} else {
	set use_gpus_per_job $tot_gpus
}
# Every node requires at least 1 GPU
if {$use_gpus_per_job < $nb_nodes} {
	set nb_nodes $use_gpus_per_job
}
test_gpus_cnt "--cpus-per-gpu=1 --gpus=$use_gpus_per_job --nodes=$nb_nodes" $use_gpus_per_job $use_gpus_per_job

if {$use_gpus_per_job > 2} {
	log_info "TEST: --gpus option, part 2"
	test_gpus_cnt "--cpus-per-gpu=1 --gpus=$use_gpus_per_job --nodes=$nb_nodes" $use_gpus_per_job $use_gpus_per_job
}

#
# Test --gpus-per-node options using a subset of GPUs actually available on the node
#
log_info "TEST: --gpus-per-node option"
set match 0
if {$gpus_per_node > 1} {
	set use_gpus_per_node [expr $gpus_per_node - 1]
} else {
	set use_gpus_per_node $gpus_per_node
}
test_gpus_cnt "--cpus-per-gpu=1 --gpus-per-node=$use_gpus_per_node --nodes=$nb_nodes" [expr $use_gpus_per_node * $nb_nodes] [expr $use_gpus_per_node * $nb_nodes]

#
# Test --gpus-per-socket options using a subset of GPUs actually available on the node
#
log_info "TEST: --gpus-per-socket option"
set sockets_with_gpus [get_gpu_socket_count $gpu_cnt $sockets_per_node]
set match 0
set node_list [get_nodes_by_request "--gpus-per-socket=1 --sockets-per-node=$sockets_with_gpus --nodes=$nb_nodes"]
if { [llength $node_list] != $nb_nodes } {
	lappend skipped "This test need to be able to submit jobs with at least --gpus-per-socket=1 --sockets-per-node=$sockets_with_gpus --nodes=$node_list"
} else {
	spawn $srun --gpus-per-socket=1 --sockets-per-node=$sockets_with_gpus --ntasks-per-socket=1 --exclusive --nodelist=[join $node_list ","] -t1 -J "$test_name" -l $file_in1
	expect {
		-re "CUDA_VISIBLE_DEVICES:($number_commas)" {
			incr match [cuda_count $expect_out(1,string)]
			exp_continue
		}
		timeout {
			fail "srun not responding"
		}
		eof {
			wait
		}
	}

	set gpus_per_node [get_gres_count "gpu" [join $node_list ","]]
	set expected_gpus 0
	dict for {node gpus} $gpus_per_node {
		incr expected_gpus $gpus
	}
	if {$match < $expected_gpus} {
		fail "srun --gpus-per-socket failure ($match < $expected_gpus)"
	}
}

#
# Test --gpus-per-task options using a subset of GPUs actually available on the node
#
log_info "TEST: --gpus-per-task option"
set match 0
if {$gpu_cnt > 1} {
	set use_gpus_per_node [expr $gpu_cnt - 1]
} else {
	set use_gpus_per_node $gpu_cnt
}
set total_cores [expr $cores_per_socket * $sockets_per_node]
if {$one_task_pc && $cpus_per_node > $total_cores} {
	set ntasks_per_core [expr $cpus_per_node / $total_cores]
	set extra_opt "--ntasks-per-core=$ntasks_per_core"
} else {
	set extra_opt "-t1"
}
test_gpus_cnt "--cpus-per-gpu=1 --gpus-per-task=1 -N1 --ntasks=$use_gpus_per_node $extra_opt" $use_gpus_per_node $use_gpus_per_node

#
# Test --gpus-per-task option without task count
#
log_info "TEST: --gpus-per-task option, part 2 (implicit task count)"
if {$cpus_per_node > 1} {
	set use_tasks_per_node 2
} else {
	set use_tasks_per_node 1
}
if {$gpu_cnt > 1} {
	set use_gpus_per_node [expr ($gpu_cnt - 1) / $use_tasks_per_node]
} else {
	set use_gpus_per_node [expr $gpu_cnt / $use_tasks_per_node]
}
if {$use_gpus_per_node == 0} {
	set use_tasks_per_node 1
	set use_gpus_per_node $gpu_cnt
}
test_gpus_cnt "--gpus-per-task=1 --ntasks-per-node=$use_tasks_per_node -N $nb_nodes" [expr $use_tasks_per_node * $nb_nodes] [expr $use_tasks_per_node * $nb_nodes]

#
# Test --gpus-per-task option without task count
#
log_info "TEST: --gpus-per-task option, part 3 (implicit task count)"
if {$gpu_cnt > 1} {
	set use_gpus_per_node [expr $gpu_cnt - 1]
} else {
	set use_gpus_per_node $gpu_cnt
}
test_gpus_cnt "--gpus-per-task=$use_gpus_per_node -N $nb_nodes" [expr $nb_nodes * $use_gpus_per_node] [expr $nb_nodes * $use_gpus_per_node]

if {$sockets_per_node <= $gpu_cnt} {
	set target_gpus $sockets_per_node
} else {
	set target_gpus $gpu_cnt
}

#
# Test --cpus-per-task with different gpu options (Bug 9937)
#
log_info "TEST: --cpus-per-task option with different gpu options(Bug 9937)"
test_gpus_cnt "--gres=gpu:1 --ntasks-per-core=1 -c $cpus_per_node" 1 1
test_gpus_cnt "--gpus=1 --ntasks-per-core=1 -c $cpus_per_node" 1 1
test_gpus_cnt "-n1 --gpus-per-task=1 --ntasks-per-core=1 -c $cpus_per_node" 1 1
test_gpus_cnt "--sockets-per-node=1 --gpus-per-socket=1 --ntasks-per-core=1 -c $cpus_per_node" $target_gpus $target_gpus
# Because we're doing one sockets worth of cpus and if there are two sockets we'll get two gpus.
test_gpus_cnt "--gpus-per-socket=1 --sockets-per-node=1 --threads-per-core=1 -c [expr $cpus_per_node / $threads_per_core]" $sockets_per_node $target_gpus

if {$threads_per_core == 4} {
	log_info "Testing high thread count ThreadsPerCore = 4"
	test_gpus_cnt "--gpus-per-socket=1 --sockets-per-node=1 --threads-per-core=2 -c [expr $cpus_per_node / 2]" $sockets_per_node $sockets_per_node
}
# Negative tests - srun is expected to fail
log_info "Negative tests - srun is expected to fail here"
test_gpus_cnt "--sockets-per-node=1 --gpus-per-socket=1 --ntasks-per-core=1 -c [expr $cpus_per_node * 2]" 0 0
test_gpus_cnt "--gres=gpu:1 -c [expr $cpus_per_node * 2]" 0 0
test_gpus_cnt "--gpus=1 -c [expr $cpus_per_node * 2]" 0 0

if {$threads_per_core > 1} {
	test_gpus_cnt "--gpus=1 --threads-per-core=1 -c $cpus_per_node" 0 0
} else {
	test_gpus_cnt "--gpus=1 --threads-per-core=1 -c [expr $cpus_per_node]" 1 1
}
# End of tests from Bug 9937

test_gpus_cnt "--gres=gpu:1 --ntasks-per-node=1 -c $cpus_per_node" 1 1
test_gpus_cnt "--gres=gpu:1 --ntasks-per-node=1 -c $cpus_per_socket" 1 1
test_gpus_cnt "--gres=gpu:1 --ntasks-per-node=1 -c 1" 1 1
test_gpus_cnt "--gres=gpu:1 --ntasks-per-socket=1 -c $cpus_per_node" 1 1
test_gpus_cnt "--gres=gpu:1 --ntasks-per-socket=1 -c $cpus_per_node" 1 1

test_gpus_cnt "--gpus=1 --ntasks-per-node=1 -c $cpus_per_node" 1 1
test_gpus_cnt "--gpus=1 --ntasks-per-socket=1 -c $cpus_per_node" 1 1

test_gpus_cnt "-n1 --gpus-per-task=1 --ntasks-per-node=1 -c $cpus_per_node" 1 1
test_gpus_cnt "-n1 --gpus-per-task=1 --ntasks-per-socket=1 -c $cpus_per_node" 1 1

# Fatals slurmd w/out -n. Bug 10197
test_gpus_cnt "--sockets-per-node=$sockets_per_node --gpus-per-socket=1 --ntasks-per-core=1 -c 1 -n$sockets_per_node" [expr $sockets_per_node * $sockets_per_node] $sockets_per_node
test_gpus_cnt "--sockets-per-node=1 --gpus-per-socket=1 --ntasks-per-core=1 -c $cpus_per_socket" 1 1
set target_gpus [expr min($sockets_per_node, $gpu_cnt)]
test_gpus_cnt "--sockets-per-node=$sockets_per_node --gpus-per-socket=1 --ntasks-per-core=1 -c $cpus_per_node" $target_gpus $target_gpus

if {[llength $skipped] != 0} {
	skip "Some tests skipped:\n[join $skipped \n]"
}

