#!/usr/bin/env expect
############################################################################
# Purpose: Test of Slurm functionality
#          Test scheduling of gres/gpu and gres/mps
############################################################################
# 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 skips       0
set file_in1   "test$test_id.input1"
set file_in2   "test$test_id.input2"
set file_out1  "test$test_id.output1"
set file_out2  "test$test_id.output2"
set job_id      0
set job_list    {}
set failure_count 0
set mps_cnt     100

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

set node_with_mps [get_nodes_by_request "--gres=mps:100 -t1"]
if {[llength $node_with_mps] != 1} {
	skip "This test requires being able to submit job with --gres=mps:100"
}

proc cleanup {} {
	global bin_rm file_in1 file_in2 file_out1 file_out2 job_list scancel

	cancel_job $job_list
	run_command -none "$bin_rm -f $file_in1 $file_in2 $file_out1 $file_out2"
}

#
# Simple MPS request, check environment variables
#
log_info "==== TEST 1 ===="
make_bash_script $file_in1 "
echo HOST:\$SLURMD_NODENAME
echo CUDA_VISIBLE_DEVICES:\$CUDA_VISIBLE_DEVICES
echo CUDA_MPS_ACTIVE_THREAD_PERCENTAGE:\$CUDA_MPS_ACTIVE_THREAD_PERCENTAGE
exit 0"
set timeout $max_job_delay
set device -1
set host "unknown"
set matches 0
set percentage -1
set target_job  [expr $mps_cnt / 2]
set srun_pid [spawn $srun --gres=mps:$target_job -w $node_with_mps -n1 -t1 -J "test$test_id" $file_in1]
expect {
	-re "HOST:($re_word_str)" {
		incr matches
		set host $expect_out(1,string)
		exp_continue
	}
	-re "CUDA_VISIBLE_DEVICES:($number)" {
		if {$expect_out(1,string) != 0} {
			log_error "CUDA_VISIBLE_DEVICES != 0"
			incr failure_count
		}
		incr matches
		exp_continue
	}
	-re "CUDA_MPS_ACTIVE_THREAD_PERCENTAGE:($number)" {
		incr matches
		exp_continue
	}
	timeout {
		slow_kill $srun_pid
		fail "srun not responding"
	}
	eof {
		wait
	}
}
if {$matches != 3} {
	log_error "Output is bad ($matches != 3)"
	incr failure_count
}

#
# Run two steps in parallel to consume gres/mps using sbatch
#
log_info "==== TEST 2 ===="
set target_job  [expr $mps_cnt / 2]
set target_step [expr $target_job / 2]
make_bash_script $file_in1 "
echo HOST:\$SLURMD_NODENAME CUDA_VISIBLE_DEVICES:\$CUDA_VISIBLE_DEVICES CUDA_MPS_ACTIVE_THREAD_PERCENTAGE:\$CUDA_MPS_ACTIVE_THREAD_PERCENTAGE
$bin_sleep 5
exit 0"
make_bash_script $file_in2 "
$srun --mem=0 --overlap --gres=mps:$target_job  $file_in1 &
wait
$bin_date
$srun --mem=0 --overlap --gres=mps:$target_step $file_in1 &
$srun --mem=0 --overlap --gres=mps:$target_step $file_in1 &
wait
$bin_date
exit 0"
exec $bin_rm -f $file_out1
set job_id 0
set sbatch_pid [spawn $sbatch --gres=mps:$target_job -w $node_with_mps -n1 -t1 -o $file_out1 -J "test$test_id" $file_in2]
expect {
	-re "Submitted batch job ($number)" {
		set job_id $expect_out(1,string)
		lappend job_list $job_id
		exp_continue
	}
	timeout {
		fail "sbatch not responding"
	}
	eof {
		wait
	}
}
if {$job_id == 0} {
	fail "Job not submitted"
}
if {[wait_for_job $job_id "DONE"] != 0} {
	fail "Job $job_id did not complete"
}
if {[wait_for_file $file_out1] != 0} {
	fail "No output file"
}
set match 0
spawn $bin_cat $file_out1
expect {
	-re "CUDA_VISIBLE_DEVICES:($number) CUDA_MPS_ACTIVE_THREAD_PERCENTAGE:($number)" {
		if {$expect_out(1,string) != 0} {
			log_error "CUDA_VISIBLE_DEVICES != 0"
			incr failure_count
		}
		incr match
		if {$match == 1} {
			set perc $expect_out(2,string)
		} else {
			if {$match == 2} {
				set perc_sum $expect_out(2,string)
			} else {
				if {$perc_sum != $expect_out(2,string)} {
					log_error "Bad CUDA percentage ($perc_sum != $expect_out(2,string))"
					incr failure_count
				} elseif {[expr $perc - $perc_sum - $expect_out(2,string)] > 1} {
					log_error "Bad CUDA percentage ($perc != ($perc_sum - $expect_out(2,string))"
					incr failure_count
				}
			}
		}
		exp_continue
	}
	eof {
		wait
	}
}
if {$match != 3} {
	log_error "Bad CUDA information about job ($match != 3)"
	incr failure_count
}

#
# Run two steps in parallel to consume gres/mps using salloc
# Reuse scripts from test 2 above
#
log_info "==== TEST 3 ===="
set match 0
set salloc_pid [spawn $salloc --gres=mps:$target_job -w $node_with_mps -n1 -t1 -J "test$test_id" ./$file_in2]
expect {
	-re "CUDA_VISIBLE_DEVICES:($number) CUDA_MPS_ACTIVE_THREAD_PERCENTAGE:($number)" {
		if {$expect_out(1,string) != 0} {
			log_error "CUDA_VISIBLE_DEVICES != 0"
			incr failure_count
		}
		incr match
		if {$match == 1} {
			set perc $expect_out(2,string)
		} else {
			if {$match == 2} {
				set perc_sum $expect_out(2,string)
			} else {
				if {$perc_sum != $expect_out(2,string)} {
					log_error "Bad CUDA percentage ($perc_sum != $expect_out(2,string))"
					incr failure_count
				} elseif {[expr $perc - $perc_sum - $expect_out(2,string)] > 1} {
					log_error "Bad CUDA percentage ($perc != ($perc_sum - $expect_out(2,string))"
					incr failure_count
				}
			}
		}
		exp_continue
	}
	timeout {
		slow_kill $salloc_pid
		fail "salloc not responding"
	}
	eof {
		wait
	}
}
if {$match != 3} {
	log_error "Bad CUDA information about job ($match != 3)"
	incr failure_count
}

#
# Run three steps in parallel to make sure steps get delay as needed to avoid
# oversubscribing consumed MPS resources
#
log_info "==== TEST 4 ===="
set target_job  [expr $mps_cnt / 2]
set target_step [expr $target_job / 2]
make_bash_script $file_in1 "
echo HOST:\$SLURMD_NODENAME CUDA_VISIBLE_DEVICES:\$CUDA_VISIBLE_DEVICES CUDA_MPS_ACTIVE_THREAD_PERCENTAGE:\$CUDA_MPS_ACTIVE_THREAD_PERCENTAGE
$bin_sleep 5
exit 0"
make_bash_script $file_in2 "
$srun --mem=0 --overlap --gres=mps:$target_step $file_in1 &
$srun --mem=0 --overlap --gres=mps:$target_step $file_in1 &
$srun --mem=0 --overlap --gres=mps:$target_step $file_in1 &
wait
$bin_date
exit 0"
exec $bin_rm -f $file_out1
set job_id 0
set sbatch_pid [spawn $sbatch --gres=mps:$target_job -w $node_with_mps -n1 -t1 -o $file_out1 -J "test$test_id" $file_in2]
expect {
	-re "Submitted batch job ($number)" {
		set job_id $expect_out(1,string)
		lappend job_list $job_id
		exp_continue
	}
	timeout {
		fail "sbatch not responding"
	}
	eof {
		wait
	}
}
if {$job_id == 0} {
	fail "Job not submitted"
}
if {[wait_for_job $job_id "DONE"] != 0} {
	fail "Job $job_id did not complete"
}
if {[wait_for_file $file_out1] != 0} {
	fail "No output file"
}
set match 0
spawn $bin_cat $file_out1
expect {
	-re "CUDA_VISIBLE_DEVICES:($number) CUDA_MPS_ACTIVE_THREAD_PERCENTAGE:($number)" {
		if {$expect_out(1,string) != 0} {
			log_error "CUDA_VISIBLE_DEVICES != 0"
			incr failure_count
		}
		incr match
		if {$match == 1} {
			set perc $expect_out(2,string)
		} else {
			if {$perc != $expect_out(2,string)} {
				log_error "Inconsistent step MPS percentages ($perc != $expect_out(2,string))"
				incr failure_count
			}
		}
		exp_continue
	}
	eof {
		wait
	}
}
if {$match != 3} {
	log_error "Bad CUDA information about job ($match != 3)"
	incr failure_count
}
log_user 0
set match 0
spawn $bin_cat $file_out1
expect {
	-re "step creation temporarily disabled" {
		incr match
		exp_continue
	}
	eof {
		wait
	}
}
log_user 1
if {$match != 1} {
	log_error "Failed to delay step for sufficient MPS resources ($match != 1)"
	incr failure_count
}

#
# Run step to try to consume gres/mps than allocated to the job
#
log_info "==== TEST 5 ===="
set target_job  [expr $mps_cnt / 2]
set target_step [expr $target_job + 1]
make_bash_script $file_in1 "
echo HOST:\$SLURMD_NODENAME CUDA_VISIBLE_DEVICES:\$CUDA_VISIBLE_DEVICES CUDA_MPS_ACTIVE_THREAD_PERCENTAGE:\$CUDA_MPS_ACTIVE_THREAD_PERCENTAGE
$bin_sleep 5
exit 0"
make_bash_script $file_in2 "
$srun --mem=0 --overlap --gres=mps:$target_step $file_in1
exit 0"
exec $bin_rm -f $file_out1
set job_id 0
set sbatch_pid [spawn $sbatch --gres=mps:$target_job -w $node_with_mps -n1 -t1 -o $file_out1 -J "test$test_id" $file_in2]
expect {
	-re "Submitted batch job ($number)" {
		set job_id $expect_out(1,string)
		lappend job_list $job_id
		exp_continue
	}
	timeout {
		fail "sbatch not responding"
	}
	eof {
		wait
	}
}
if {$job_id == 0} {
	fail "Job not submitted"
}
if {[wait_for_job $job_id "DONE"] != 0} {
	fail "Job $job_id did not complete"
}
if {[wait_for_file $file_out1] != 0} {
	fail "No output file"
}
set match 0
spawn $bin_cat $file_out1
expect {
	-re "Unable to create step" {
		log_debug "Error is expected, no worries"
		incr match
		exp_continue
	}
	-re "CUDA_VISIBLE_DEVICES" {
		log_error "Failed to reject bad step ($match != 1)"
		incr failure_count
	}
	eof {
		wait
	}
}
if {$match != 1} {
	log_error "Failed to reject bad step ($match != 1)"
	incr failure_count
}

#
# Run multi-node job
#
log_info "==== TEST 6 ===="
set node_cnt [get_mps_node_count]
if {$node_cnt > 2} {
	set node_cnt 2
}
set target_job  [expr $mps_cnt / 2]
make_bash_script $file_in1 "
echo HOST:\$SLURMD_NODENAME CUDA_VISIBLE_DEVICES:\$CUDA_VISIBLE_DEVICES CUDA_MPS_ACTIVE_THREAD_PERCENTAGE:\$CUDA_MPS_ACTIVE_THREAD_PERCENTAGE
$bin_sleep 5
exit 0"
set match 0
set hostname "NO_VAL"
set subtest6_nodes [get_nodes_by_request "--gres=mps:$target_job -N$node_cnt -t1"]
if {[llength $subtest6_nodes] != $node_cnt} {
	log_warn "SKIP: Subtest 6 requires being able to submit job with --gres=mps:$target_job -N$node_cnt"
	incr skips
}

set srun_pid [spawn $srun --gres=mps:$target_job -N$node_cnt -w[join $subtest6_nodes ","] -t1 -J "test$test_id" $file_in1]
expect {
	-re "HOST:($re_word_str)" {
		incr match
		if {$match == 1} {
			set hostname $expect_out(1,string)
		} elseif {[get_config_param "FrontendName"] ne "MISSING"} {
			log_debug "Duplicate SLURMD_HOSTNAME in front-end mode as expected"
		} elseif {[string compare $hostname $expect_out(1,string)] == 0} {
			log_error "Two tasks ran on same node ($hostname))"
			incr failure_count
		}
		exp_continue
	}
	timeout {
		slow_kill $srun_pid
		fail "srun not responding"
	}
	eof {
		wait
	}
}
if {$match != $node_cnt} {
	log_error "Failed to get data from multiple nodes ($match != $node_cnt)"
	incr failure_count
}

#
# Make sure that gres/gpu and gres/mps jobs either do not share the same GPU
# or run at different times
#
if {[get_config_param "FrontendName"] ne "MISSING"} {
	log_warn "SKIP: Subtest 7 doesn't work with front_end"
	incr skips
} else {
	log_info "==== TEST 7 ===="
	set target_job [expr $mps_cnt / 2]
	make_bash_script $file_in1 "
	echo HOST:\$SLURMD_NODENAME CUDA_VISIBLE_DEVICES:\$CUDA_VISIBLE_DEVICES CUDA_MPS_ACTIVE_THREAD_PERCENTAGE:\$CUDA_MPS_ACTIVE_THREAD_PERCENTAGE
	$scontrol -dd show job \$SLURM_JOB_ID
	$sbatch --gres=mps:$target_job -w \$SLURMD_NODENAME -n1 -t1 -o $file_out2 -J test$test_id $file_in2
	sleep 30
	exit 0"

	make_bash_script $file_in2 "
	echo HOST:\$SLURMD_NODENAME CUDA_VISIBLE_DEVICES:\$CUDA_VISIBLE_DEVICES CUDA_MPS_ACTIVE_THREAD_PERCENTAGE:\$CUDA_MPS_ACTIVE_THREAD_PERCENTAGE
	$scontrol -dd show job \$SLURM_JOB_ID
	$squeue --name=test$test_id --noheader --state=r --format=\"jobid=%i state=%T\"
	exit 0"

	exec $bin_rm -f $file_out1 $file_out2
	set job_id1 0
	set sbatch_pid [spawn $sbatch --gres=gpu:1 -w $node_with_mps -n1 -t1 -o $file_out1 -J "test$test_id" $file_in1]
	expect {
		-re "Submitted batch job ($number)" {
			set job_id1 $expect_out(1,string)
			lappend job_list $job_id1
			exp_continue
		}
		timeout {
			fail "sbatch not responding"
		}
		eof {
			wait
		}
	}
	sleep 30
	if {[wait_for_job $job_id1 "DONE"] != 0} {
		fail "Job $job_id1 did not complete"
	}
	if {[wait_for_file $file_out1] != 0} {
		fail "No output file"
	}
	set dev1 -1
	set job_id2 0
	set match 0
	spawn $bin_cat $file_out1
	expect {
		-re "CUDA_VISIBLE_DEVICES:($number)" {
			incr match
			exp_continue
		}
		-re "gpu:$number\\(IDX:($number)\\)" {
			set dev1 $expect_out(1,string)
			exp_continue
		}
		-re "Submitted batch job ($number)" {
			set job_id2 $expect_out(1,string)
			lappend job_list $job_id2
			exp_continue
		}
		eof {
			wait
		}
	}
	if {$match == 0} {
		log_error "CUDA_VISIBLE_DEVICES not set"
		incr failure_count
	}
	if {$dev1 == -1} {
		log_error "GPU device index not found"
		incr failure_count
	}
	if {$job_id2 == 0} {
		log_error "Failed to submit second job"
		incr failure_count
	}

	if {[wait_for_job $job_id2 "DONE"] != 0} {
		fail "Job $job_id2 did not complete"
	}
	if {[wait_for_file $file_out2] != 0} {
		fail "No output file"
	}
	set dev2 -1
	set match 0
	set running 0
	spawn $bin_cat $file_out2
	expect {
		-re "CUDA_VISIBLE_DEVICES:($number)" {
			incr match
			if {$match == 1} {
				set dev2 $expect_out(1,string)
			}
			exp_continue
		}
		-re "CUDA_MPS_ACTIVE_THREAD_PERCENTAGE:($number)" {
			incr match
			exp_continue
		}
		-re "mps:$number\\(IDX:($number)\\)" {
			set dev1 $expect_out(1,string)} {
			exp_continue
		}
		-re "jobid=$job_id1 state=RUNNING" {
			set running 1
			exp_continue
		}
		eof {
			wait
		}
	}
	if {$match != 2} {
		log_error "CUDA_VISIBLE_DEVICES or CUDA_MPS_ACTIVE_THREAD_PERCENTAGE not set"
		incr failure_count
	}
	if {$dev2 == -1} {
		log_error "GPU device index not found"
		incr failure_count
	} elseif {$dev1 == $dev2} {
		if {$running == 0} {
			log_debug "The jobs are using the same GPU ($dev1) and running at different times, which is fine"
		} else {
			log_error "The jobs are using the same GPU ($dev1) and running at the same time"
			incr failure_count
		}
	} else {
		log_debug "The jobs are using different GPUs ($dev1 != $dev2), which is fine"
	}
}

#
# Clean up and exit
#
if {$failure_count != 0} {
	fail "Test failed due to previous errors (\$failure_count = $failure_count)"
}
if {$skips != 0} {
	skip "Some subtest was skipped ($skips)"
}
