#!/usr/bin/env expect
############################################################################
# Purpose: Test of Slurm functionality
#          Test sacct functionality and accuracy.
#
# 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) 2005 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     "12.2"
set exit_code   0
set file_in     "test$test_id.input"
set file_out    "test$test_id.output"
set file_err    "test$test_id.error"
set file_prog   "test$test_id.prog"
set file_name   "/tmp/test$test_id.filename"
set job_id      0
set matches     0

# job parameters
set mem_size    1048576
set sleep_time  32
set ret_code    42
set file_size   10485760
set num_tasks   3
set max_time_error 5
set max_mem_error 4300
set step_id	0

print_header $test_id

if {[test_front_end]} {
        send_user "\nWARNING: This test is incompatible with front-end systems\n"
        exit $exit_code
}
if {![test_accting_steps]} {
	send_user "\nWARNING: This test can not be run with nosteps or nojobs "
	send_user "(AccountingStorageEnforce)\n"
	exit 0
}

proc _get_mem {prog} {
	global float number mem_size job_id step_id max_mem_error num_tasks

	set mem_used -1
	set mem_task -1
	set ave_used -1
	set exit_code 0

	spawn $prog --noheader -p --job=$job_id.$step_id --format maxrss,maxrsstask,averss --noconvert
	expect {
		-re "($number).($number).($number)" {
			set mem_used  $expect_out(1,string)
			set mem_task  $expect_out(2,string)
			set ave_used  $expect_out(3,string)

			set mem_used [scale_to_ks $mem_used ""]
			set ave_used [scale_to_ks $ave_used ""]

			exp_continue
		}
		timeout {
			send_user "\nFAILURE: $prog not responding\n"
			set exit_code 1
		}
		eof {
			wait
		}
	}

	if { $exit_code } {
		return 1
	}

	if { $mem_used == -1 } {
		send_user "\nFAILURE: $prog stat memory not found\n"
		return 1
	} elseif { $mem_task != 0 } {
		send_user "\nFAILURE: $prog stat memory task not zero\n"
		return 1
	} elseif { ($ave_used * $num_tasks) < $mem_used } {
		send_user "\nFAILURE: $prog stat ave memory not believable against max memory\n"
		return 1
	}
	# Compute error in KB
	set diff_mem [expr $mem_used - $mem_size]
	set error_mem [expr abs($diff_mem)]
	if {($mem_used < $mem_size) || ($error_mem > $max_mem_error)} {
		send_user "\nFAILURE: $prog memory use discrepancy of $diff_mem KB\n"
		send_user "  Wanted $mem_size KB, got $mem_used KB\n"
		return 1
	} else {
		send_user "\nSUCCESS: $prog memory use discrepancy of $error_mem KB\n"
	}
	return 0
}

# Check the job written and read file size.
proc _get_file_size {prog} {
	global number float job_id step_id file_size

	set max_disk_write  -1
	set ave_disk_write  -1
	set max_disk_read   -1
	set ave_disk_read   -1

	spawn $prog --noheader -p --job=$job_id.$step_id --format MaxDiskWrite,AveDiskWrite,MaxDiskRead,AveDiskRead,MaxDiskWriteTask,MaxDiskReadTask --noconvert
	expect {
		-re  "($float)(\[MGT\]*).($float)(\[MGT\]*).($float)(\[MGT\]*).($float)(\[MGT\]*).($number).($number)" {
			set max_disk_write    $expect_out(1,string)
			set scale1            $expect_out(2,string)
			set ave_disk_write    $expect_out(3,string)
			set scale2            $expect_out(4,string)
			set max_disk_read     $expect_out(5,string)
			set scale3            $expect_out(6,string)
			set ave_disk_read     $expect_out(7,string)
			set scale4            $expect_out(8,string)
			set w_task            $expect_out(9,string)
			set r_task            $expect_out(10,string)

			set max_disk_write [scale_to_megs $max_disk_write $scale1]
			set ave_disk_write [scale_to_megs $ave_disk_write $scale2]
			set max_disk_read  [scale_to_megs $max_disk_read  $scale3]
			set ave_disk_read  [scale_to_megs $ave_disk_read  $scale4]
		}
		timeout {
			send_user "\nFAILURE: $prog not responding\n"
			set exit_code 1
		}
		eof {
			wait
		}
	}

	set mb_file_size [ expr ($file_size/(1024 * 1024)) ]
	if { $max_disk_write == -1 } {
		send_user "\nFAILURE: MaxDiskWrite not reported\n"
		return 1
	}
	if { $ave_disk_write == -1 } {
		send_user "\nFAILURE: AveDiskWrite not reported\n"
		return 1
	}
	if { $max_disk_read == -1 } {
		send_user "\nFAILURE: MaxDiskRead not reported\n"
		return 1
	}
	if { $ave_disk_read == -1 } {
		send_user "\nFAILURE: AveDiskRead not reported\n"
		return 1
	}
	if { $w_task != 1 } {
		send_user "\nFAILURE: MaxDiskWriteTask not 1\n"
		return 1
	}
	if { $r_task != 2 } {
		send_user "\nFAILURE: MaxDiskReadTask not 2\n"
		return 1
	}

	# Compute error in MB
	set diff_io [expr $max_disk_write - $max_disk_read]
	set error_io [expr abs($diff_io)]
	if { $error_io > 0.3 } {
		send_user "\nFAILURE: written file size does not match read size "
		send_user "file_size:$mb_file_size MB "
		send_user "max_disk_write:$max_disk_write MB "
		send_user "max_disk_read:$max_disk_read MB\n"
		return 1
	}

	set diff_io [expr $ave_disk_write - $ave_disk_read]
	set error_io [expr abs($diff_io)]
	if { $error_io > 0.3 } {
		send_user "\nFAILURE: average written file size "
		send_user "does not match average read size "
		send_user "file_size:$mb_file_size MB "
		send_user "ave_disk_write:$ave_disk_write MB "
		send_user "ave_disk_read:$ave_disk_read MB\n"
		return 1
	}

	send_user "\nSUCCESS: $prog reported correct written and read file size\n"
	send_user "file_size:$mb_file_size MB max_disk_write:$max_disk_write MB "
	send_user "max_disk_read:$max_disk_read MB\n"

	return 0
}

#
# Check if accounting is enabled
#
set supported_gather  0
set supported_storage 1
log_user 0
spawn $scontrol show config
expect {
	-re "AccountingStorageType *= accounting_storage/none" {
		set supported_storage 0
		exp_continue
	}
	-re "JobAcctGatherType *= jobacct_gather/linux" {
		set supported_gather 1
		exp_continue
	}
	-re "JobAcctGatherType *= jobacct_gather/cgroup" {
		set supported_gather 1
		exp_continue
	}
	eof {
		wait
	}
}
log_user 1
if {$supported_gather == 0} {
	send_user "\nWARNING: Job accounting information not gathered on this system\n"
	exit 0
}
if {$supported_storage == 0} {
	send_user "\nWARNING: Job accounting information not stored on this system\n"
	exit 0
}

#
# Delete left-over program and rebuild it
#
exec $bin_rm -f $file_prog
exec $bin_rm -f $file_in $file_out $file_err
exec $bin_cc -O -o $file_prog ${file_prog}.c
exec $bin_chmod 700 $file_prog

make_bash_script $file_in "
    $srun ./$file_prog $ret_code $sleep_time $mem_size $file_size $file_name
"

#
# Run a simple job
# Usage: test12.2.prog <exit_code> <sleep_secs> <mem_kb>
# <file_size> <file_name>
#
set config_prob 0
set timeout [expr $max_job_delay + $sleep_time]
set job_mem_limit [expr ($mem_size + $max_mem_error)  / 1024 + 10]
set sbatch_pid [spawn $sbatch -n$num_tasks --mem-per-cpu=$job_mem_limit --output=$file_out --error=$file_err -t2 $file_in]
expect {
	-re "Requested node configuration is not available" {
		set config_prob 1
		exp_continue
	}
	-re "Submitted batch job ($number)" {
		set job_id $expect_out(1,string)
		exp_continue
	}
	timeout {
		send_user "\nFAILURE: srun not responding\n"
		slow_kill $sbatch_pid
		exit 1
	}
	eof {
		wait
	}
}
if {$config_prob != 0} {
	send_user "\nWARNING: Unable to test with current node configuration\n"
	exit 0
}
if {$job_id == 0} {
	send_user "\nFAILURE: batch submit failure\n"
	exit 1
}

#
# Wait for job to run
#
if {[wait_for_job $job_id "RUNNING"] != 0} {
	send_user "\nFAILURE: waiting for job to run\n"
	set exit_code 1
}

# Wait for data to get logged
exec $bin_sleep 15

if {[_get_mem $sstat] != 0} {
	set exit_code 1
}

if {[_get_file_size $sstat] != 0} {
	set exit_code 1
}

#
# Wait for job to complete
#
if {[wait_for_job $job_id "DONE"] != 0} {
	send_user "\nFAILURE: waiting for job to complete\n"
	set exit_code 1
}

#
# Wait for accounting data to be propagated to slurmdbd
#
sleep 10

#
# Report basic sacct info
#
spawn $sacct --noheader -P --job=$job_id.$step_id --format jobid,jobname,state,exitcode --starttime=00:00
expect {
	-re "$job_id\.$step_id" {
		incr matches
		exp_continue
	}
	-re "$file_prog" {
		incr matches
		exp_continue
	}
	-re "FAILED" {
		incr matches
		exp_continue
	}
	-re "COMPLETING" {
		send_user "\nWARNING: Step in completing state rather than FAILED\n"
		incr matches
		exp_continue
	}
	-re "$ret_code" {
		incr matches
		exp_continue
	}
	timeout {
		send_user "\nFAILURE: sacct not responding\n"
		set exit_code 1
	}
	eof {
		wait
	}
}

if {$matches < 4} {
	send_user "\nFAILURE: sacct reporting failed ($matches < 4)\n"
	set exit_code 1
}

#
# Report the sacct accounting info
# Note we load each digit of seconds individually to avoid this error:
#   expected integer but got "08" (looks like invalid octal number)
#
set elapsed_time 0
spawn $sacct --noheader -P --job=$job_id.$step_id --format elapsed  --starttime=00:00
expect {
	-re "($number):($number):(\[0-9\])(\[0-9\])" {
		set hours $expect_out(1,string)
		set mins $expect_out(2,string)
		set sec_ten $expect_out(3,string)
		set sec_one $expect_out(4,string)
		set secs [expr $sec_ten * 10 + $sec_one]
		set elapsed_time [expr ($hours * 3600) + ($mins * 60) + $secs]
		exp_continue
	}
	timeout {
		send_user "\nFAILURE: sacct not responding\n"
		set exit_code 1
	}
	eof {
		wait
	}
}
set diff_time [expr $elapsed_time - $sleep_time]
set error_time [expr abs($diff_time)]
if {$error_time > $max_time_error} {
	send_user "\nFAILURE: sacct elapsed time discrepancy of $error_time secs\n"
	send_user "  Wanted $sleep_time secs, got $elapsed_time secs\n"
	set exit_code 1
} else {
	send_user "\nSUCCESS: sacct elapsed time discrepancy of $error_time secs\n"
}

set total_cpu 0
spawn $sacct --noheader -P --job=$job_id.$step_id --format totalcpu --starttime=00:00
# Ignore the milliseconds portion
expect {
	-re "($number):(\[0-9\])(\[0-9\])" {
		set mins $expect_out(1,string)
		set sec_ten $expect_out(2,string)
		set sec_one $expect_out(3,string)
		set secs [expr $sec_ten * 10 + $sec_one]
		set total_cpu [expr ($mins * 60) + $secs]
		exp_continue
	}
	timeout {
		send_user "\nFAILURE: sacct not responding\n"
		set exit_code 1
	}
	eof {
		wait
	}
}
if {$total_cpu > $sleep_time} {
	send_user "\nFAILURE: sacct reported an impossible TotalCPU time of $total_cpu secs\n"
	send_user "  Has to be less than $sleep_time secs!\n"
	set exit_code 1
} else {
	send_user "\nSUCCESS: sacct TotalCPU time looks reasonable ($total_cpu seconds)\n"
}

set min_cpu 0
spawn $sacct --noheader -P --job=$job_id.$step_id --format mincpu --starttime=00:00
expect {
	-re "($number):($number):(\[0-9\])(\[0-9\])" {
		set hours $expect_out(1,string)
		set mins $expect_out(2,string)
		set sec_ten $expect_out(3,string)
		set sec_one $expect_out(4,string)
		set secs [expr $sec_ten * 10 + $sec_one]
		set min_cpu [expr ($hours * 3600) + ($mins * 60) + $secs]
		exp_continue
	}
	timeout {
		send_user "\nFAILURE: sacct not responding\n"
		set exit_code 1
	}
	eof {
		wait
	}
}
if {$min_cpu > $sleep_time} {
	send_user "\nFAILURE: sacct reported an impossible MinCPU time of $min_cpu secs\n"
	send_user "  Has to be less than $sleep_time secs!\n"
	set exit_code 1
} else {
	send_user "\nSUCCESS: sacct MinCPU time looks reasonable ($min_cpu seconds)\n"
}

if {[_get_mem $sacct] != 0} {
	set exit_code 1
}

if {[_get_file_size $sacct] != 0} {
	set exit_code 1
}

if {$exit_code == 0} {
	exec rm -f $file_prog $file_in $file_out $file_err $file_name
	send_user "\nSUCCESS\n"
}
exit $exit_code
