#!/usr/bin/env expect
############################################################################
# Purpose: Stress test with maximum slurmctld message concurrency.
#          We start a large number of job steps, the simultaneously
#          cancel them all. Message can get lost/retransmitted, so
#          there is a delayed test for job step removal.
#
# 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) 2002-2006 The Regents of the University of California.
# Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
# Written by Morris Jette <jette1@llnl.gov>
# CODE-OCEC-09-009. All rights reserved.
#
# 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      "9.8"
set exit_code    0
set file_in      "test$test_id.input"
set job_cnt      10
set delay        10
set job_name     "test$test_id"
set sleep_time   300
set task_cnt     60

print_header $test_id

if {![test_select_type_params "Memory"]} {
	set mem_per_step 0
} else {
	set mem_per_step 8
}

#
# A single slurmd can't handle a large task count without
# running out of memory and pthreads
#
if {[test_front_end] != 0 || $enable_memory_leak_debug != 0} {
	set task_cnt 2
}

#
# Build input script file
# NOTE: The initial sleep is so that all of the submissions have time
#   to occur before contending with a multitude of job step creations.
#   This is especially important on very slow systems (e.g. AIX).
# NOTE: Explicitly set a small memory limit. Without explicitly setting the step
#   memory limit, it will use the system default (same as the job) which may
#   prevent the level of parallelism desired.
#
make_bash_script $file_in "
$bin_sleep 5
ulimit -u `ulimit -u -H`
for ((inx=0; inx < $task_cnt; inx++)) ; do
$srun -N1 -n1 --mem=0 $bin_sleep $sleep_time &
done
$srun -N1 -n1 --mem=0 $bin_sleep $sleep_time
"

#
# Initiate $job_cnt batch jobs
#
set start_cnt 0
set timeout 30
for {set inx 0} {$inx < $job_cnt} {incr inx} {
	set sbatch_pid [spawn $sbatch --gres=craynetwork:0 --job-name=$job_name --mem-per-cpu=[expr $mem_per_step * 10] --output=/dev/null --error=/dev/null -t5 $file_in]
	expect {
		-re "Submitted batch job ($number)" {
			incr start_cnt
			exp_continue
		}
		-re "Unable to contact" {
			send_user "\nFAILURE: slurm appears to be down\n"
			exp_continue
		}
		timeout {
			send_user "\nFAILURE: sbatch not responding\n"
			slow_kill $sbatch_pid
			set exit_code 1
		}
		eof {
			wait
		}
	}
}
if {$start_cnt < $job_cnt} {
	send_user "\nFAILURE: $job_cnt of $start_cnt jobs submitted\n"
	set exit_code 1
} else {
	send_user "\nAll $start_cnt jobs submitted\n"
}

set user_name [get_my_user_name]

#
# There could be hundreds of job steps, we don't want to see
# the details, but want to make sure that we did start many
#
set desired_tasks [expr $task_cnt * 2 / 3]

#
# Give the jobs a few seconds to get initiated, check for steps,
# then kill them all
#
exec $bin_sleep $delay

set job_count  0
set step_count 0
set timeout    60
log_user 0
while { 1 } {
	set job_count 0
	spawn $squeue --state R --name $job_name --user $user_name
	expect {
		-re "$job_name" {
			incr job_count
			exp_continue
		}
		timeout {
			send_user "\nFAILURE: squeue not responding\n"
			set exit_code 1
		}
		eof {
			wait
		}
	}

	set step_count 0
	spawn $squeue --steps --name $job_name --user $user_name
	expect {
		-re "sleep" {
			incr step_count
			exp_continue
		}
		-re "error:" {
			send_user "\nFAILURE: squeue error\n"
			set exit_code 1
			exp_continue
		}
		timeout {
			send_user "\nFAILURE: squeue not responding\n"
			set exit_code 1
		}
		eof {
			wait
		}
	}
	if {$step_count >= $desired_tasks || $step_count == 0} {
		break
	}
	set scaled_task_cnt [expr $job_count * $desired_tasks]
	if {$step_count >= $scaled_task_cnt} {
		send_user "\nOnly started $job_count jobs, reducing step count target to $scaled_task_cnt\n"
		set desired_tasks $scaled_task_cnt
	}
	exec $bin_sleep 3
}

log_user 1
if {$step_count < $desired_tasks} {
	send_user "\nFAILURE: only started $job_count jobs and $step_count steps\n"
	send_user "  We expected at least $desired_tasks and possibly hundreds\n"
	set exit_code 1
} else {
	send_user "\nWe found $job_count jobs and $step_count steps\n"
}
spawn $scancel --quiet --user $user_name
expect {
	eof {
		wait
	}
}

#
# Give a few seconds for clean-up and ensure things are still fine
# If message are lost, slurmctld re-sends job kill RPC 120 seconds later
# In any case, make sure that all jobs get completed
#
exec $bin_sleep     10
set completing_jobs 0
set running_jobs    0
spawn $squeue --noheader --user $user_name
expect {
	-re "test9.8.*$user_name *CG" {
		incr completing_jobs
		exp_continue
	}
	-re "test9.8.*$user_name" {
		incr running_jobs
		exp_continue
	}
	eof {
		wait
	}
}
#
# The following logic handles the scancel request failing
# due to a very busy system (reports FAILURE above)
#
# Increasing the MessageTimeout configuration parameter
# should fix this problem.
#
if {$running_jobs != 0} {
	send_user "\nFAILURE: jobs not all cancelled\n"
	set exit_code 1

	spawn $scancel --quiet --user $user_name
	expect {
		eof {
			wait
		}
	}
}
if {$completing_jobs != 0} {
	send_user "\nWaiting for slurmctld to re-send job kill RPC\n"
	send_user "This will take 120 seconds...\n"
	exec $bin_sleep 120
	set completing_jobs 0
	spawn $squeue --noheader --user $user_name
	expect {
		-re "$job_name *$user_name *CG" {
			incr completing_jobs
			exp_continue
		}
		eof {
			wait
		}
	}
	if {$completing_jobs != 0} {
		send_user "\nFAILURE: jobs not completing\n"
		set exit_code 1
	}
}
if {$completing_jobs != 0} {
	set max_wait [expr $sleep_time - 120]
	if {$max_wait > 0} {
		set completing_jobs 0
		exec $bin_sleep $max_wait
		spawn $squeue --noheader --user $user_name
		expect {
			-re "$job_name *$user_name *CG" {
				incr completing_jobs
				exp_continue
			}
			eof {
				wait
			}
		}
	}
}
if {$completing_jobs != 0} {
	send_user "\nFAILURE: Jobs not completing. Subsequent tests may fail!\n"
}

if {$exit_code == 0} {
	exec $bin_rm -f $file_in
	send_user "\nSUCCESS\n"
}
exit $exit_code
