1*af546375SCole Faust#!/bin/bash 2*af546375SCole Faust# Copyright 2020 Google LLC 3*af546375SCole Faust# 4*af546375SCole Faust# Licensed under the Apache License, Version 2.0 (the "License"); 5*af546375SCole Faust# you may not use this file except in compliance with the License. 6*af546375SCole Faust# You may obtain a copy of the License at 7*af546375SCole Faust# 8*af546375SCole Faust# http://www.apache.org/licenses/LICENSE-2.0 9*af546375SCole Faust# 10*af546375SCole Faust# Unless required by applicable law or agreed to in writing, software 11*af546375SCole Faust# distributed under the License is distributed on an "AS IS" BASIS, 12*af546375SCole Faust# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13*af546375SCole Faust# See the License for the specific language governing permissions and 14*af546375SCole Faust# limitations under the License. 15*af546375SCole Faust 16*af546375SCole Faustfunction retry_with_backoff { 17*af546375SCole Faust attempts_left=$1 18*af546375SCole Faust sleep_seconds=$2 19*af546375SCole Faust shift 2 20*af546375SCole Faust command=$@ 21*af546375SCole Faust 22*af546375SCole Faust 23*af546375SCole Faust # store current flag state 24*af546375SCole Faust flags=$- 25*af546375SCole Faust 26*af546375SCole Faust # allow a failures to continue 27*af546375SCole Faust set +e 28*af546375SCole Faust ${command} 29*af546375SCole Faust exit_code=$? 30*af546375SCole Faust 31*af546375SCole Faust # restore "e" flag 32*af546375SCole Faust if [[ ${flags} =~ e ]] 33*af546375SCole Faust then set -e 34*af546375SCole Faust else set +e 35*af546375SCole Faust fi 36*af546375SCole Faust 37*af546375SCole Faust if [[ $exit_code == 0 ]] 38*af546375SCole Faust then 39*af546375SCole Faust return 0 40*af546375SCole Faust fi 41*af546375SCole Faust 42*af546375SCole Faust # failure 43*af546375SCole Faust if [[ ${attempts_left} > 0 ]] 44*af546375SCole Faust then 45*af546375SCole Faust echo "failure (${exit_code}), sleeping ${sleep_seconds}..." 46*af546375SCole Faust sleep ${sleep_seconds} 47*af546375SCole Faust new_attempts=$((${attempts_left} - 1)) 48*af546375SCole Faust new_sleep=$((${sleep_seconds} * 2)) 49*af546375SCole Faust retry_with_backoff ${new_attempts} ${new_sleep} ${command} 50*af546375SCole Faust fi 51*af546375SCole Faust 52*af546375SCole Faust return $exit_code 53*af546375SCole Faust} 54*af546375SCole Faust 55*af546375SCole Faust## Helper functionss 56*af546375SCole Faustfunction now() { date +"%Y-%m-%d %H:%M:%S" | tr -d '\n'; } 57*af546375SCole Faustfunction msg() { println "$*" >&2; } 58*af546375SCole Faustfunction println() { printf '%s\n' "$(now) $*"; } 59*af546375SCole Faust 60*af546375SCole Faust## Helper comment to trigger updated repo dependency release