#!/usr/bin/env expect
############################################################################
# Purpose: Test of Slurm functionality
#          Test of --use-min-nodes option.
#
# Output:  "TEST: #.#" followed by "SUCCESS" if test was successful, OR
#          "FAILURE: ..." otherwise with an explanation of the failure, OR
#          anything else indicates a failure mode that must be investigated.
############################################################################
# Copyright (C) 2016 SchedMD LLC.
# Written by Alejandro Sanchez <alex@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 test_id     "1.113"
set exit_code   0
set needed_nodes 2
set partition [default_partition]
set matches 0
set ncpus ""

print_header $test_id

if {[test_select_type_params "CR_ONE_TASK_PER_CORE"]} {
	send_user "\nWARNING: This test is incompatible SelectTypeParameters=CR_ONE_TASK_PER_CORE\n"
	exit 0
}

log_user 0
spawn $sinfo -N -h -p $partition -t idle -o "%c"
expect {
	-re "($number)" {
		incr matches
		if {$ncpus eq ""} {
			set ncpus $expect_out(1,string)
		} elseif {$expect_out(1,string) < $ncpus} {
			set ncpus $expect_out(1,string)
		}
		exp_continue
	}
	timeout {
		send_user "\nFAILURE: sinfo not responding\n"
		set exit_code 1
	}
	eof {
		wait
	}
}
log_user 1

if {$matches < $needed_nodes} {
	send_user "\nWARNING: $needed_nodes idle nodes required in partition $partition, only $matches found.\n"
	exit 0
}

set nodes 0
set timeout $max_job_delay
set srun_pid [spawn $srun -p $partition -N1-2 --use-min-nodes -n$ncpus $bin_printenv SLURM_NNODES]
expect {
	-re "srun: job $number queued and waiting for resources" {
		exp_continue
	}
	-re "srun: job $number has been allocated resources" {
		exp_continue
	}
	-re "($number)" {
		set nodes $expect_out(1,string)
		if {$nodes != 1} {
			send_user "\nFAILURE: expected 1 allocated node\n"
			set exit_code 1
		}
	}
	timeout {
		send_user "\nFAILURE: srun not responding\n"
		slow_kill $sun_pid
		set exit_code 1
	}
	eof {
		wait
	}
}

if {$exit_code == 0} {
	send_user "\nSUCCESS\n"
}
exit $exit_code
