truestuff/wait-for-idle-queue.sh

46 lines
1.1 KiB
Bash
Executable File

#! /usr/bin/env bash
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
USER_HOME=$HOME
[[ -n "${SUDO_USER}" ]] && USER_HOME="$(eval "echo ~${SUDO_USER}")"
. ${SHRC_D:-$SCRIPT_DIR}/01_util.functions
set -e
IGNORE_CRON=${1:-${IGNORE_CRON}}
count_unfinished_jobs() {
local TEST_CRON
TEST_CRON="${IGNORE_CRON:+" and .method != \"cronjob.run\""}"
midclt call core.get_jobs | jq -r '
.[] | select( .time_finished == null '"$TEST_CRON"' )
' | wc -l
}
wait_for_idle_queue() {
local TIMEOUT="${1:-${TIMEOUT:-120}}" START="$(date +%s)"
while [[ "$( count_unfinished_jobs )" -gt 0 ]]; do
printf '.'
if (( TIMEOUT > 0 && ($(date +%s) - START) > TIMEOUT )); then
printf 'TIMEOUT %s reached.\n' "$TIMEOUT" >&2
printf '\n'
return 1
break;
fi
sleep 2
done
printf '\n'
}
abort_unfinished_jobs() {
midclt call core.get_jobs \
| jq -r '.[] | select( .time_finished == null ) | .id ' \
| xargs -rn1 midclt call core.job_abort
}
wait_for_idle_queue || if [[ -z "$NO_AUTO_ABORT" ]]; then
abort_unfinished_jobs
fi