本文主要是介绍[k8s] kubectl执行失败后等待一段时间再重试 (Shell实现),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
使用Shell脚本实现功能: kubectl
执行失败后,等待30秒后再重试,一共重试3次,代码如下:
#!/bin/bashKUBECTL_BIN=/var/lib/snapd/snap/bin/kubectlERR_MSG_K8S_NOTRUNNING="microk8s is not running"
ERR_MSG_CONNECTION_TIMEOUT="connection timed out"
ERR_MSG_CONNECTION_REFUSED="refused - did you specify the right host or port"function debuglog() {local log_content=${@:1}local caller=$(basename "$0")echo "`date +"%Y-%m-%d %H:%M:%S"` [$caller] INFO $log_content" 2>&1
}function api_kubectlX() {local retry=$1shiftlocal args=$@local ret=0local cmdstr="${args[@]}"local tmpfile=$(mktemp)for ((i=0;i<$retry;i++)); do${KUBECTL_BIN} $@ 2>"$tmpfile"ret=$?if [ $ret -eq 0 ]; thendebuglog "KUBECTL $cmdstr ret: 0"breakfilocal errinfo=$(< "$tmpfile")local need_retry="no"if [ -n "$(echo "$errinfo" | grep "$ERR_MSG_K8S_NOTRUNNING")" ]; thenneed_retry="yes"elif [ -n "$(echo "$errinfo" | grep "$ERR_MSG_CONNECTION_TIMEOUT")" ]; thenneed_retry="yes"elif [ -n "$(echo "$errinfo" | grep "$ERR_MSG_CONNECTION_REFUSED")" ]; thenneed_retry="yes"elif [ $ret -eq 143 ]; then # 143 means SIGTERM, just retryneed_retry="yes"elseneed_retry="no"fiif [ $need_retry != "yes" ]; thendebuglog "KUBECTL ret: $ret/($errinfo) $cmdstr"breakfidebuglog "KUBECTL ret: $ret/($errinfo) (retry:$i) $cmdstr"sleep 30donerm -- ${tmpfile}return $ret
}function api_kubectl() {local args=(3 "$@")api_kubectlX "${args[@]}"return $?
}# 使用方法:
api_kubectl get ns
这篇关于[k8s] kubectl执行失败后等待一段时间再重试 (Shell实现)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!