From e2f3bb0e3dc68f42eadf07597e51bc0102ec8e36 Mon Sep 17 00:00:00 2001 From: David Erel Date: Mon, 11 Dec 2023 11:09:26 +0200 Subject: [PATCH] small refactor to encounter missing logs --- test.sh | 8 +------- wait-for-service.sh | 46 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 7 deletions(-) create mode 100755 wait-for-service.sh diff --git a/test.sh b/test.sh index a0e5b22..71732e4 100755 --- a/test.sh +++ b/test.sh @@ -88,18 +88,12 @@ check_log_for_pattern() done echo "Pattern not found in $service_name after $max_attempts attempts. Bailing out..." - set -x - curl --no-progress-meter http://localhost:8123/api/pvlt/1.0/ctl/info/health - docker compose logs return 1 } wait_until_vault_is_up() { - check_log_for_pattern "vault-demo-piiano-vault-1" "Serving HTTP on 0.0.0.0:8123" - if [ "$?" -eq 1 ] ; then - exit 1 - fi + ./wait-for-service.sh http://localhost:8123/api/pvlt/1.0/ctl/info/health } check_vault_health() diff --git a/wait-for-service.sh b/wait-for-service.sh new file mode 100755 index 0000000..ddec3fe --- /dev/null +++ b/wait-for-service.sh @@ -0,0 +1,46 @@ +#!/bin/bash +IFS=$'\n\t' + +# First argument is the service URL that defaults to "http://localhost:3000" +service_url="${1:-http://localhost:3000}" + +# Second optional parameter - max attempts +max_attempts="${2:-10}" + +# Third, optional argument - PID to follow. If it dies, exit +PID="${3:-0}" + +SLEEP_BETWEEN_ATTEMPTS_SECS=3 + +echo "Wait for service on ${service_url} for ${max_attempts} and PID=${PID}" + +# Poll the service until it's up or until the maximum number of attempts is reached +attempt_counter=0 +while [ "$attempt_counter" -lt "$max_attempts" ]; do + response=$(curl --write-out '%{http_code}' --silent --output /dev/null "$service_url" || true) + + if [ "$response" -eq 200 ]; then + echo "Service is up and returned HTTP 200" + exit 0 + else + # print only every 10 messages - do not flood the console + if [ $((attempt_counter % 10)) -eq 0 ]; then + echo "Service returned HTTP $response. Retrying ${attempt_counter}..." + fi + ((attempt_counter++)) + if [ "$attempt_counter" -eq "$max_attempts" ]; then + echo "Max attempts reached. Exiting." + exit 1 + fi + if [ ${PID} -ne 0 ] ; then + if ! ps -p ${PID} > /dev/null 2>&1 ; then + echo "Process ${PID} has died, exit." + exit 1 + fi + fi + sleep ${SLEEP_BETWEEN_ATTEMPTS_SECS} + fi +done + +echo "Service is not up after timeout. Give up" +exit 1