Skip to content

Commit

Permalink
cloud: Wait for PostgreSQL proxy to become ready
Browse files Browse the repository at this point in the history
Wait for the cloud_sql_proxy to become ready before running the command
that's supposed to use it. This prevents command failures in times of
higher load, when the proxy takes a bit to start, authenticate, and
connect.
  • Loading branch information
spbnick committed Aug 16, 2023
1 parent 1dcbf1a commit 83b189a
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions cloud
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,36 @@ function psql_proxy_session() {
chmod 0600 "$PSQL_PROXY_PGPASS"
password_get_pgpass psql_superuser postgres >| "$PSQL_PROXY_PGPASS"

# Wait for the proxy to become ready
declare max_checks=10
declare delay=3
declare checks
declare output=""
declare ready="false"
for ((checks=0; checks < max_checks; checks++)); do
if output+=$(
PGHOST="$PSQL_PROXY_DIR/$fq_instance" \
PGPASSFILE="$PSQL_PROXY_PGPASS" \
PGUSER="postgres" \
pg_isready
)$'\n'; then
ready="true"
break;
fi
sleep "$delay"
done

# Check if the wait was successful
if ! "$ready"; then
echo "PostgreSQL proxy ${proxy@Q} is not ready " \
"after $((checks * delay)) seconds." >&2
if [ -n "$output" ]; then
echo "pg_isready output:" >&2
echo "$output" >&2
fi
fi
"$ready"

# Run the command
PGHOST="$PSQL_PROXY_DIR/$fq_instance" \
PGPASSFILE="$PSQL_PROXY_PGPASS" \
Expand Down

0 comments on commit 83b189a

Please sign in to comment.