Created
March 10, 2020 12:23
-
-
Save jesusvazquez/4495b03fe3f1250ab57b517fd0b4b9e4 to your computer and use it in GitHub Desktop.
Resolve DNS with exponential backoff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# vim: ai:ts=8:sw=8:noet | |
# set -eufo pipefail | |
export SHELLOPTS # propagate set to children by default | |
IFS=$'\t\n' | |
# Performs a DNS resolution and waits until the answer has a non-empty response | |
function resolve_dns_with_backoff { | |
local timeout=${DNS_RESOLUTION_TIMEOUT-5} | |
local domain=${1} | |
local attempt=0 | |
local backoff=1 | |
local now | |
local end | |
now=$(date +%s) | |
end=$((now + timeout)) | |
while [[ ${now} < ${end} ]] | |
do | |
response=$(dig +short "${domain}") | |
if [ -n "${response}" ]; then | |
echo "DNS Response is ${response}" | |
return 0 | |
fi | |
echo "Attempt $attempt - DNS Response was empty! Retrying in $backoff seconds.." 1>&2 | |
sleep "${backoff}" | |
attempt=$(( attempt + 1 )) | |
backoff=$(( backoff * 2 )) | |
now=$(date +%s) | |
done | |
return 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment