Skip to content

Commit e2998b0

Browse files
committed
fix: Handle intermittent network errors
Intermittent network errors may happen when a module's source code is downloaded over HTTP. That happened to me recently (an unexpected 502 from GitHub), which resulted in a missing module in my Docker image (that was partially my fault, as the build process should stop in case of any error). This PR implements automatic retries (with backoff delay) using an OS-agnostic `try_n_times` helper.
1 parent 879f89e commit e2998b0

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

build_module.sh

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,30 @@ while true; do
253253
fi
254254
done
255255

256+
#
257+
# A generic helper function to retry any command with a backoff strategy
258+
#
259+
try_n_times() {
260+
MAX_ATTEMPTS=$1
261+
CMD=$2
262+
CLEAN_CMD=$3
263+
i=0
264+
WAIT_TIME=1
265+
while ! $CMD; do
266+
i=$(expr $i + 1)
267+
if [ $i -le $MAX_ATTEMPTS ]; then
268+
echo "Attempt $i failed! Waiting $WAIT_TIME seconds before retry..."
269+
sleep $WAIT_TIME
270+
test -n "$CLEAN_CMD" && $CLEAN_CMD
271+
WAIT_TIME=$(expr $WAIT_TIME \* 2)
272+
else
273+
echo "$MAX_ATTEMPTS attempts failed!"
274+
return 1
275+
fi
276+
done
277+
return 0
278+
}
279+
256280
#
257281
# Create temporary build area, with working copy of module source
258282
#
@@ -277,15 +301,15 @@ else
277301
;;
278302
"zip")
279303
echo "$ME: INFO Downloading module source"
280-
wget -O $BUILD_DIR/module.zip $1
304+
try_n_times 3 "wget -O $BUILD_DIR/module.zip $1" "rm -f $BUILD_DIR/module.zip"
281305
ARCHIVE_DIR=`zipinfo -1 $BUILD_DIR/module.zip | head -n 1 | cut -f1 -d/`
282306
unzip $BUILD_DIR/module.zip -d $BUILD_DIR
283307
mv $BUILD_DIR/$ARCHIVE_DIR $MODULE_DIR
284308
;;
285309
*)
286310
echo "$ME: INFO Downloading module source"
287311
# Assume tarball of some kind
288-
wget -O $BUILD_DIR/module.tgz $1
312+
try_n_times 3 "wget -O $BUILD_DIR/module.tgz $1" "rm -f $BUILD_DIR/module.tgz"
289313
ARCHIVE_DIR=`tar tfz $BUILD_DIR/module.tgz | head -n 1 | cut -f1 -d/`
290314
cd $BUILD_DIR
291315
tar xfz module.tgz

0 commit comments

Comments
 (0)