Files
proxmox/scripts/utils/retry_with_backoff.sh

37 lines
1.2 KiB
Bash
Raw Permalink Normal View History

#!/usr/bin/env bash
# Retry with exponential backoff - Recommendation from docs/10-best-practices/RECOMMENDATIONS_AND_SUGGESTIONS.md
# Usage: source this file, then: retry_with_backoff 3 2 some_command [args...]
# $1 = max_attempts, $2 = initial_delay_seconds, rest = command and args
retry_with_backoff() {
local max_attempts="${1:?Usage: retry_with_backoff MAX_ATTEMPTS INITIAL_DELAY COMMAND [ARGS...]}"
local delay="${2:?Usage: retry_with_backoff MAX_ATTEMPTS INITIAL_DELAY COMMAND [ARGS...]}"
shift 2
local attempt=1
while [ "$attempt" -le "$max_attempts" ]; do
if "$@"; then
return 0
fi
if [ "$attempt" -lt "$max_attempts" ]; then
echo "[WARN] Attempt $attempt failed, retrying in ${delay}s..." >&2
sleep "$delay"
delay=$((delay * 2))
fi
attempt=$((attempt + 1))
done
echo "[ERROR] Failed after $max_attempts attempts" >&2
return 1
}
# Allow script to be sourced or run (run = execute first non-option args as command)
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
if [[ $# -ge 3 ]]; then
retry_with_backoff "$@"
else
echo "Usage: $0 MAX_ATTEMPTS INITIAL_DELAY COMMAND [ARGS...]"
echo "Example: $0 3 2 curl -s -o /dev/null -w '%{http_code}' https://example.com"
exit 2
fi
fi