Skip to content

Instantly share code, notes, and snippets.

@jesusvazquez
Created March 10, 2020 12:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jesusvazquez/4495b03fe3f1250ab57b517fd0b4b9e4 to your computer and use it in GitHub Desktop.
Save jesusvazquez/4495b03fe3f1250ab57b517fd0b4b9e4 to your computer and use it in GitHub Desktop.
Resolve DNS with exponential backoff
#!/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