#!/usr/bin/env expect
############################################################################
# Purpose: Test of Slurm functionality
#          Test accounting for GPU resources with various allocation options
############################################################################
# Copyright (C) SchedMD LLC.
#
# 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 file_out       "$test_dir/output"
set job_id         0

#
# Validate the job, batch step and step 0 of a job have the proper GPU counts
# No step to test if step_gpus == -1
#
#
proc test_acct { job_id job_gpus step_gpus req_gpus have_gpu_types batch_gpus } {
	global re_word_str number
	global bin_cat bin_rm file_out sacct

	if {$job_id == 0} {
		return
	}

	log_debug "Job $job_id Expecting job GPUs:$job_gpus  Step GPUs:$step_gpus"

	# Wait for ReqTRES to be populated for the job. Job completion records are
	# sent immediately to the database, but job start records get queued and
	# can take longer.
	wait_for_command_match -fail "$sacct -X -n -o ReqTRES --parsable2 -j $job_id" "gres/gpu"
	# Also wait for steps to show up in the DB
	wait_for_command_match -fail "$sacct -n -o JobId --parsable2 -j $job_id" "$job_id.batch"
	if {$step_gpus != -1} {
		wait_for_command_match -fail "$sacct -n -o JobId --parsable2 -j $job_id" "$job_id.0"
	}

	set output [run_command_output -fail "$sacct --job=$job_id --parsable2 --start=now-15minutes --format JobID,ReqTRES,AllocTRES --noheader"]
	set job_tres_dict [dict create]
	foreach line [split $output "\n"] {
		lassign [split $line "|"] JobID ReqTRES AllocTRES
		dict set job_tres_dict $JobID ReqTRES $ReqTRES
		dict set job_tres_dict $JobID AllocTRES $AllocTRES
	}

	# Check and count reported gpus on the step
	if {$step_gpus != -1} {
		set gpus_reported_count 0
		if ![dict exists $job_tres_dict "$job_id.0"] {
			fail "sacct did not report a record for step $job_id.0"
		}
		set tres_dict [dict get $job_tres_dict "$job_id.0"]
		foreach tres_value [dict values $tres_dict] {
			if {$have_gpu_types} {
				foreach {{} gpu_count} [regexp -all -inline {gres/gpu:[^=]+=(\d+)} $tres_value] {
					subtest {$gpu_count == $step_gpus} "Step GPUs reported by sacct should be $step_gpus" "$gpu_count != $step_gpus"
					incr gpus_reported_count
				}
			} else {
				foreach {{} gpu_count} [regexp -all -inline {gres/gpu=(\d+)} $tres_value] {
					subtest {$gpu_count == $step_gpus} "Step GPUs reported by sacct should be $step_gpus" "$gpu_count != $step_gpus"
					incr gpus_reported_count
				}
			}
		}
		subtest {$gpus_reported_count == 1} "sacct should report step GPUs 1 time" "found $gpus_reported_count times"
	}

	# Check and count reported batch gpus on the job
	set gpus_reported_count 0
	if ![dict exists $job_tres_dict "$job_id.batch"] {
		fail "sacct did not report a record for job $job_id.batch"
	}
	set tres_dict [dict get $job_tres_dict "$job_id.batch"]
	foreach tres_value [dict values $tres_dict] {
		if {$have_gpu_types} {
			foreach {{} gpu_count} [regexp -all -inline {gres/gpu:[^=]+=(\d+)} $tres_value] {
				subtest {$gpu_count == $batch_gpus} "Batch GPUs reported by sacct should be $batch_gpus" "$gpu_count != $batch_gpus"
				incr gpus_reported_count
			}
		} else {
			foreach {{} gpu_count} [regexp -all -inline {gres/gpu=(\d+)} $tres_value] {
				subtest {$gpu_count == $batch_gpus} "Batch GPUs reported by sacct should be $batch_gpus" "$gpu_count != $batch_gpus"
				incr gpus_reported_count
			}
		}
	}
	subtest {$gpus_reported_count == 1} "sacct should report batch GPUs 1 time" "found $gpus_reported_count times"

	# Check and count reported gpus on the job
	set gpus_reported_count 0
	if ![dict exists $job_tres_dict $job_id] {
		fail "sacct did not report a record for job $job_id"
	}
	set tres_dict [dict get $job_tres_dict $job_id]
	foreach tres_value [dict values $tres_dict] {
		if {$have_gpu_types} {
			foreach {{} gpu_count} [regexp -all -inline {gres/gpu:[^=]+=(\d+)} $tres_value] {
				subtest {$gpu_count == $job_gpus} "Job GPUs reported by sacct should be $job_gpus" "$gpu_count != $job_gpus"
				incr gpus_reported_count
			}
		} else {
			foreach {{} gpu_count} [regexp -all -inline {gres/gpu=(\d+)} $tres_value] {
				subtest {$gpu_count == $job_gpus} "Job GPUs reported by sacct should be $job_gpus" "$gpu_count != $job_gpus"
				incr gpus_reported_count
			}
		}
	}
	subtest {$gpus_reported_count == 2} "sacct should report job GPUs 2 times" "found $gpus_reported_count times"
}

#
# Validate the job, batch step and step 0 of a job have the proper GPU counts
# No step to test if step_gpus == -1
#
#
proc test_out_file { file_out target } {
	global re_word_str number bin_cat

	wait_for_file -fail $file_out

	set match 0
	spawn $bin_cat $file_out
	expect {
		-re "AllocTRES=.*,gres/gpu=($number)" {
			set match $expect_out(1,string)
			exp_continue
		}
		-re "AllocTRES=.*,gres/gpu:($re_word_str)=($number)" {
			set match $expect_out(2,string)
			exp_continue
		}
		eof {
			wait
		}
	}
	subtest {$match == $target} "GPUs accounted should be $target" "$match != $target"
}

#
# Helper function to find $batch_gpus from different outputs
#
proc get_batch_gpus { file_out } {
	global bin_cat

	set batch_host "unknown"
	set batch_gpus "unknown"

	set output [run_command_output -fail "$bin_cat $file_out"]
	set nodes [regexp -all -line -inline {    Nodes=+.*} $output]
	set node_line [lindex $nodes 0]

	if {[llength $nodes] > 1} {
		# Output type where nodes are split on 2 lines, set $node_line to grab the BatchHost node
		#  BatchHost=74dc179a_n1
		#  ...
		# >Nodes=74dc179a_n1 CPU_IDs=0-1 Mem=150 GRES=[[gpu:2]](IDX:0-1)<
		#  Nodes=74dc179a_n2 CPU_IDs=0-1 Mem=150 GRES=gpu:1(IDX:0)

		regexp -all -line {BatchHost=(.*)} $output - batch_host
		set node_line [lindex [lsearch -all -inline $nodes *$batch_host*] 0]
	}

	if {![regexp {gpu:(?:[^:( ]+:)?(\d+)} $node_line - batch_gpus]} {
		fail "Unable to get batch_mps"
	}

	return $batch_gpus
}

if {[get_config_param "AccountingStorageType"] ne "accounting_storage/slurmdbd"} {
	skip "This test can't be run without a usable AccountStorageType"
}

set store_tres [string tolower [get_config_param "AccountingStorageTRES"]]
set store_gpu [string first "gres/gpu" $store_tres]
if {$store_gpu == -1} {
	skip "This test requires accounting for GPUs"
} elseif {[get_config_param "FrontendName"] ne "MISSING"} {
	skip "This test is incompatible with front-end systems"
}

if {![check_config_select "cons_tres"]} {
	skip "This test is only compatible with select/cons_tres"
}

set nb_nodes [get_partition_param [default_partition] "TotalNodes"]
log_debug "Default partition node count is $nb_nodes"
if {$nb_nodes > 2} {
	set nb_nodes 2
}
set gpu_cnt [get_highest_gres_count $nb_nodes "gpu"]
if {$gpu_cnt < 2} {
	skip "This test requires 2 or more GPUs on $nb_nodes nodes of the default partition"
}

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 cpus_per_socket   [expr $cpus_per_node / $sockets_per_node]
set sockets_with_gpus [get_gpu_socket_count $gpu_cnt $sockets_per_node]

log_debug "GPUs per node is $gpu_cnt"
log_debug "Sockets with GPUs $sockets_with_gpus"
log_debug "Sockets per node is $sockets_per_node"
log_debug "CPUs per socket is $cpus_per_socket"
log_debug "CPUs per node is $cpus_per_node"

if {$cpus_per_node < 3} {
	skip "This test requires 3 or more CPUs per node in the default partition"
}

proc cleanup {} {
	global job_id

	cancel_job $job_id
}

#
# Test --gpus-per-node option by job
#
make_bash_script $file_in1 "
	$scontrol -dd show job \${SLURM_JOBID}
	exit 0"

log_info "TEST 1: --gpus-per-node option by job"

set req_gpus 2
set target [expr $nb_nodes * $req_gpus]
exec $bin_rm -f $file_out
set timeout $max_job_delay
set job_id [submit_job -fail "--gres=craynetwork:0 --gpus-per-node=$req_gpus -N$nb_nodes -t1 -o $file_out -J $test_name $file_in1"]

wait_for_job -fail $job_id "DONE"
wait_for_file -fail $file_out

set batch_gpus [get_batch_gpus $file_out]
set have_gpu_types 0
set match 0
spawn $bin_cat $file_out
expect {
	-re "AllocTRES=.*,gres/gpu=($number)" {
		set match $expect_out(1,string)
		exp_continue
	}
	-re "AllocTRES=.*,gres/gpu:($re_word_str)=($number)" {
		if {$match == 0} {
			set have_gpu_types 1
			set match $expect_out(2,string)
		}
		exp_continue
	}
	eof {
		wait
	}
}
subtest {$match == $target} "GPUs accounted should be $target" "$match != $target"
test_acct $job_id $target -1 $req_gpus $have_gpu_types $batch_gpus

#
# Test --gpus option by job
#
log_info "TEST 2: --gpus option by job"

exec $bin_rm -f $file_out
if {$nb_nodes >= 2 || $gpu_cnt >= 3} {
	set target 3
} else {
	set target 2
}
set job_id [submit_job -fail "--gres=craynetwork:0 --gpus=$target -N$nb_nodes -t1 -o $file_out -J $test_name $file_in1"]

wait_for_job -fail $job_id "DONE"
set batch_gpus [get_batch_gpus $file_out]

test_out_file $file_out $target
test_acct $job_id $target -1 $target $have_gpu_types $batch_gpus

#
# Test --gpus-per-task option by job
#
log_info "TEST 3: --gpus-per-task option by job"

exec $bin_rm -f $file_out
if {$cpus_per_node >= 2 && $nb_nodes >= 2} {
	set nb_tasks 3
} elseif {$cpus_per_node >= 2 || $nb_nodes >= 2} {
	set nb_tasks 2
} else {
	set nb_tasks 1
}
set req_gpus 1
set job_id [submit_job -fail "--gres=craynetwork:0 --gpus-per-task=$req_gpus -N$nb_nodes -n$nb_tasks -t1 -o $file_out -J $test_name $file_in1"]

wait_for_job -fail $job_id "DONE"
set batch_gpus [get_batch_gpus $file_out]

test_out_file $file_out $nb_tasks
test_acct $job_id $nb_tasks -1 $req_gpus $have_gpu_types $batch_gpus

#
# Test --gpus-per-socket option by job
#
log_info "TEST 4: --gpus-per-socket option by job"

exec $bin_rm -f $file_out

if {$sockets_with_gpus >= 2} {
	set nb_sockets 2
	set cpus_per_task $cpus_per_socket
} else {
	set nb_sockets 1
	set cpus_per_task 1
}
set req_gpus 1
set job_id [submit_job -fail "--gres=craynetwork:0 --gpus-per-socket=$req_gpus -N$nb_nodes  --ntasks=$nb_nodes --sockets-per-node=$nb_sockets --cpus-per-task=$cpus_per_task -t1 -o $file_out -J $test_name $file_in1"]

wait_for_job -fail $job_id "DONE"
set batch_gpus [get_batch_gpus $file_out]
set target [expr $nb_nodes * $nb_sockets]

test_out_file $file_out $target
test_acct $job_id $target -1 $req_gpus $have_gpu_types $batch_gpus

#
# Test --gpus-per-node option by step
#
make_bash_script $file_in1 "
	$srun $file_in2
	exit 0"

make_bash_script $file_in2 "
	if \[ \$SLURM_PROCID -eq 0 \]; then
		$scontrol -dd show job \${SLURM_JOBID}
		$scontrol show step \${SLURM_JOBID}.\${SLURM_STEPID}
	fi
	exit 0"

log_info "TEST 5: --gpus-per-node option by step"

set req_gpus 2
set target [expr $nb_nodes * $req_gpus]
exec $bin_rm -f $file_out
set timeout $max_job_delay
set job_id [submit_job -fail "--gres=craynetwork:0 --gpus-per-node=$req_gpus -N$nb_nodes -t1 -o $file_out -J $test_name $file_in1"]

wait_for_job -fail $job_id "DONE"
set batch_gpus [get_batch_gpus $file_out]

test_out_file $file_out $target
test_acct $job_id $target $target $req_gpus $have_gpu_types $batch_gpus

#
# Test --gpus option by step
#
log_info "TEST 6: --gpus option by step"

exec $bin_rm -f $file_out
if {$nb_nodes >= 2 || $gpu_cnt >= 3} {
	set target 3
} else {
	set target 2
}
set job_id [submit_job -fail "--gres=craynetwork:0 --gpus=$target -N$nb_nodes -t1 -o $file_out -J $test_name $file_in1"]

wait_for_job -fail $job_id "DONE"
set batch_gpus [get_batch_gpus $file_out]

test_out_file $file_out $target
test_acct $job_id $target $target $target $have_gpu_types $batch_gpus

#
# Test --gpus-per-task option by step
#
log_info "TEST 7: --gpus-per-task option by step"

exec $bin_rm -f $file_out
if {$cpus_per_node >= 2 && $nb_nodes >= 2} {
	set nb_tasks 3
} elseif {$cpus_per_node >= 2 || $nb_nodes >= 2} {
	set nb_tasks 2
} else {
	set nb_tasks 1
}
set req_gpus 1
set job_id [submit_job -fail "--gres=craynetwork:0 --gpus-per-task=$req_gpus -N$nb_nodes -n$nb_tasks -t1 -o $file_out -J $test_name $file_in1"]

wait_for_job -fail $job_id "DONE"
set batch_gpus [get_batch_gpus $file_out]

test_out_file $file_out $nb_tasks
test_acct $job_id $nb_tasks $nb_tasks $req_gpus $have_gpu_types $batch_gpus

#
# Test --gpus-per-socket option by step
#
log_info "TEST 8: --gpus-per-socket option by step"

exec $bin_rm -f $file_out

if {$sockets_with_gpus >= 2} {
	set nb_sockets 2
	set cpus_per_task $cpus_per_socket
} else {
	set nb_sockets 1
	set cpus_per_task 1
}
set req_gpus 1
set job_id [submit_job -fail "--gres=craynetwork:0 --gpus-per-socket=$req_gpus -N$nb_nodes  --ntasks=$nb_nodes --sockets-per-node=$nb_sockets --cpus-per-task=$cpus_per_task -t1 -o $file_out -J $test_name $file_in1"]

wait_for_job -fail $job_id "DONE"
set batch_gpus [get_batch_gpus $file_out]
set target [expr $nb_nodes * $nb_sockets]

test_out_file $file_out $target
test_acct $job_id $target $target $req_gpus $have_gpu_types $batch_gpus

#
# Test --gpus-per-task option by step
#
log_info "TEST 9: --gpus-per-task option by step"

exec $bin_rm -f $file_out
if {$cpus_per_node >= 2 && $nb_nodes >= 2} {
	set job_tasks 3
	set step_tasks 2
} elseif {$cpus_per_node >= 2 || $nb_nodes >= 2} {
	set job_tasks 2
	set step_tasks 2
} else {
	set job_tasks 1
	set step_tasks 1
}
if {$nb_nodes >= 2} {
	set step_nodes 2
} else {
	set step_nodes 1
}
make_bash_script $file_in1 "
	$srun -N$step_nodes -n$step_tasks $file_in2
	exit 0"

set req_gpus 1
set job_id [submit_job -fail "--gres=craynetwork:0 --gpus-per-task=$req_gpus -N$nb_nodes -n$job_tasks -t1 -o $file_out -J $test_name $file_in1"]
wait_for_job -fail $job_id "DONE"
set batch_gpus [get_batch_gpus $file_out]

test_out_file $file_out $step_tasks
test_acct $job_id $job_tasks $step_tasks $req_gpus $have_gpu_types $batch_gpus
