k8s.io/kubernetes@v1.29.3/test/kubemark/common/util.sh (about) 1 #!/usr/bin/env bash 2 3 # Copyright 2017 The Kubernetes Authors. 4 # 5 # Licensed under the Apache License, Version 2.0 (the "License"); 6 # you may not use this file except in compliance with the License. 7 # You may obtain a copy of the License at 8 # 9 # http://www.apache.org/licenses/LICENSE-2.0 10 # 11 # Unless required by applicable law or agreed to in writing, software 12 # distributed under the License is distributed on an "AS IS" BASIS, 13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 # See the License for the specific language governing permissions and 15 # limitations under the License. 16 17 # Running cmd $RETRIES times in case of failures. 18 function run-cmd-with-retries { 19 RETRIES="${RETRIES:-3}" 20 for attempt in $(seq 1 "${RETRIES}"); do 21 local ret_val=0 22 exec 5>&1 # Duplicate &1 to &5 for use below. 23 # We don't use 'local' to declare result as then ret_val always gets value 0. 24 # We use tee to output to &5 (redirected to stdout) while also storing it in the variable. 25 result=$("$@" 2>&1 | tee >(cat - >&5)) || ret_val="$?" 26 if [[ "${ret_val:-0}" -ne "0" ]]; then 27 if [[ $(echo "${result}" | grep -c "already exists") -gt 0 ]]; then 28 if [[ "${attempt}" == 1 ]]; then 29 # shellcheck disable=SC2154 # Color defined in sourced script 30 echo -e "${color_red}Failed to $1 $2 ${3:-} as the resource hasn't been deleted from a previous run.${color_norm}" >& 2 31 exit 1 32 fi 33 # shellcheck disable=SC2154 # Color defined in sourced script 34 echo -e "${color_yellow}Succeeded to $1 $2 ${3:-} in the previous attempt, but status response wasn't received.${color_norm}" 35 return 0 36 fi 37 # shellcheck disable=SC2154 # Color defined in sourced script 38 echo -e "${color_yellow}Attempt $attempt failed to $1 $2 ${3:-}. Retrying.${color_norm}" >& 2 39 sleep $((attempt * 5)) 40 else 41 # shellcheck disable=SC2154 # Color defined in sourced script 42 echo -e "${color_green}Succeeded to $1 $2 ${3:-}.${color_norm}" 43 return 0 44 fi 45 done 46 # shellcheck disable=SC2154 # Color defined in sourced script 47 echo -e "${color_red}Failed to $1 $2 ${3:-}.${color_norm}" >& 2 48 exit 1 49 }