#!/usr/bin/env expect
############################################################################
# Purpose: Test of Slurm functionality
#          Validate that the SrunPortRange is enforced when starting
#          a job with srun.
############################################################################
# Copyright (C) 2014 SchedMD LLC
# Written by Nathan Yee <nyee32@schedmd.com>
#
# 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

set chk_ports    [get_config_param "SrunPortRange"]
set cwd          "[$bin_pwd]"
set port_dir     "${test_name}\_port_conf"
set config_path  ""
set file_in      "${test_dir}/job_input"
set file_out	 "${test_dir}/job_output"
set tmp_job      "${test_dir}/job_script"
set job_id       0
array set ports {}

if {![is_super_user]} {
    skip "This test can't be run without being a super user of the cluster"
}
if {$chk_ports eq "MISSING"} {
	skip "This test requires SrunPortRange to be configured"
}

# split the port range into 2 numbers
set range [split $chk_ports -]
set i 0
foreach p $range {
	set ports($i) $p
	incr i 1
}

if {[expr $ports(1) - $ports(0)] < 5} {
	skip "This test requires SrunPortRange to be configured with at least 5 ports"
}

#
# Copy the slurm.conf file
#
set config_path [get_conf_path]
set config_file $config_path/slurm.conf
save_conf $config_file

proc cleanup {} {
	global job_id config_file

	cancel_job $job_id

	# Clean up vestigial files and restore original slurm.conf file
	restore_conf $config_file
	reconfigure
}

### Check that SrunPortRange in scontrol show config and slurm.conf match ###
log_info "---Checking SrunPortRange in slurm.conf and scontrol show conf---"

set slurm_conf_range ""
spawn  $bin_grep -i SrunPortRange $config_file
expect {
	-nocase -re "SrunPortRange=($re_word_str)" {
		set slurm_conf_range $expect_out(1,string)
		exp_continue
	}
	timeout {
		fail "cat is not responding"
	}
	eof {
		wait
	}
}

set show_config_range ""
spawn -noecho $bin_bash -c "exec $scontrol show config | $bin_grep SrunPortRange"
expect {
	-re "SrunPortRange *=* ($re_word_str)" {
		set show_config_range $expect_out(1,string)
		exp_continue
	}
	timeout {
		fail "scontrol is not responding"
	}
	eof {
		wait
	}
}

if {$show_config_range ne $slurm_conf_range} {
	fail "SrunPortRange from scontrol show config does not match what is in slurm.conf"
}

set range [split $slurm_conf_range -]
set i 0
foreach p $range {
	set ports($i) $p
	incr i 1
}

### Check to see that srun is using the correct ports specified in slurm.conf ###
log_info "---Checking that srun uses correct ports---"

make_bash_script $file_in "
$srun $bin_bash -c \"
task_id=\\\$($scontrol show step \$SLURM_JOBID\.\$SLURM_STEPID | $bin_grep SrunHost | $bin_awk -F: '{print \\\$3}')
lsof -P -p \\\$task_id 2>/dev/null | $bin_grep LISTEN | $bin_awk '{print \\\$9}' | $bin_awk -F: '{print \\\$2}'
\""

set job_id [submit_job -fail "-o $file_out $file_in"]
wait_for_job -fail $job_id "DONE"

set output [run_command_output "cat $file_out"]
set out_of_range 0
set i 0
foreach p $output {
	if {$p < $ports(0) || $p > $ports(1)} {
		log_debug "port $p is out of range $ports(0) - $ports(1)"
		set out_of_range 1
		incr i 1
	}
}

subtest {$out_of_range != 1} "Check that ports are within range specified in conf"

#
# Change the slurm.conf port range to a smaller number so we can exhaust ports
#
exec $bin_sed -i "s/SrunPortRange=$slurm_conf_range/#SrunPortRange=$slurm_conf_range/Ig" $config_file
exec $bin_echo SrunPortRange=$ports(0)-[expr $ports(0) + 5] > $test_dir/$port_dir
exec $bin_echo include $test_dir/$port_dir >> $config_file
reconfigure -fail

###### Check that srun produces an error when all ports are exhausted ######
log_info "---Checking srun error when ports are exhausted---"

make_bash_script $tmp_job "$srun -t1 sleep 10"

spawn $sbatch -N1 -o/dev/null -t1 $tmp_job
expect {
	-re "Submitted batch job ($number)" {
		set job_id $expect_out(1,string)
		exp_continue
	}
	timeout {
		fail "srun is not responding"
	}
	eof {
		wait
	}
}

if {$job_id == 0} {
	fail "Job was not submitted"
}

if {[wait_for_job $job_id "RUNNING"] != 0} {
	fail "Error waiting for job ($job_id) to start"
}
set match 0
set timeout 60
spawn $srun -t1 sleep 10
expect {
	-re "all ports in range" {
		set match 1
		log_debug "This error is expected, do not worry"
		exp_continue
	}
	timeout {
		fail "srun is not responding"
	}
	eof {
		wait
	}
}

if {$match != 1} {
	fail "srun should have failed due to exhausted ports but did not"
}
