2021-08-10 06:07:36 +00:00
|
|
|
#!/bin/bash -E
|
|
|
|
|
|
|
|
KUBECTL_RETRY=5
|
|
|
|
KUBECTL_RETRY_DELAY=10
|
|
|
|
|
|
|
|
kubectl_retry() {
|
|
|
|
local retries=0 action="${1}" ret=0 stdout stderr
|
|
|
|
shift
|
|
|
|
|
|
|
|
# temporary files for kubectl output
|
|
|
|
stdout=$(mktemp rook-kubectl-stdout.XXXXXXXX)
|
|
|
|
stderr=$(mktemp rook-kubectl-stderr.XXXXXXXX)
|
|
|
|
|
2022-04-20 14:22:28 +00:00
|
|
|
while ! ( kubectl "${action}" "${@}" 2>"${stderr}" 1>"${stdout}" )
|
2021-08-10 06:07:36 +00:00
|
|
|
do
|
|
|
|
# in case of a failure when running "create", ignore errors with "AlreadyExists"
|
|
|
|
if [ "${action}" == 'create' ]
|
|
|
|
then
|
2022-04-24 07:35:41 +00:00
|
|
|
# count lines in stderr that do not have "AlreadyExists" or "Warning"
|
|
|
|
ret=$(grep -cvw -e 'AlreadyExists' -e '^Warning:' "${stderr}")
|
2021-08-10 06:07:36 +00:00
|
|
|
if [ "${ret}" -eq 0 ]
|
|
|
|
then
|
|
|
|
# Success! stderr is empty after removing all "AlreadyExists" lines.
|
|
|
|
break
|
|
|
|
fi
|
|
|
|
fi
|
|
|
|
|
2021-08-10 12:41:27 +00:00
|
|
|
# in case of a failure when running "delete", ignore errors with "NotFound"
|
|
|
|
if [ "${action}" == 'delete' ]
|
|
|
|
then
|
2022-04-24 07:35:41 +00:00
|
|
|
# count lines in stderr that do not have "NotFound" or "Warning"
|
|
|
|
ret=$(grep -cvw -e 'NotFound' -e '^Warning:' "${stderr}")
|
2021-08-10 12:41:27 +00:00
|
|
|
if [ "${ret}" -eq 0 ]
|
|
|
|
then
|
|
|
|
# Success! stderr is empty after removing all "NotFound" lines.
|
|
|
|
break
|
|
|
|
fi
|
|
|
|
fi
|
|
|
|
|
2021-08-10 06:07:36 +00:00
|
|
|
retries=$((retries+1))
|
|
|
|
if [ ${retries} -eq ${KUBECTL_RETRY} ]
|
|
|
|
then
|
|
|
|
ret=1
|
|
|
|
break
|
|
|
|
fi
|
|
|
|
|
|
|
|
# log stderr and empty the tmpfile
|
|
|
|
cat "${stderr}" > /dev/stderr
|
|
|
|
true > "${stderr}"
|
2022-04-20 14:22:28 +00:00
|
|
|
echo "$(date): 'kubectl_retry ${*}' failed (${retries}/${KUBECTL_RETRY}), will retry in ${KUBECTL_RETRY_DELAY} seconds" > /dev/stderr
|
2021-08-10 06:07:36 +00:00
|
|
|
|
|
|
|
sleep ${KUBECTL_RETRY_DELAY}
|
|
|
|
|
|
|
|
# reset ret so that a next working kubectl does not cause a non-zero
|
|
|
|
# return of the function
|
|
|
|
ret=0
|
|
|
|
done
|
|
|
|
|
2022-04-20 14:22:28 +00:00
|
|
|
echo "$(date): 'kubectl_retry ${*}' done (ret=${ret})" > /dev/stderr
|
|
|
|
|
2021-08-10 06:07:36 +00:00
|
|
|
# write output so that calling functions can consume it
|
|
|
|
cat "${stdout}" > /dev/stdout
|
|
|
|
cat "${stderr}" > /dev/stderr
|
|
|
|
|
|
|
|
rm -f "${stdout}" "${stderr}"
|
|
|
|
|
|
|
|
return ${ret}
|
|
|
|
}
|