Wait for Postgres in run script

This commit is contained in:
Colin Seymour
2026-06-15 15:12:14 +00:00
parent b03e782e8f
commit a7bc113eb0
+19 -5
View File
@@ -52,9 +52,27 @@ for env_var in $(bashio::config 'env_vars|keys'); do
export "${name}=${value}" export "${name}=${value}"
done done
# Wait for PostgreSQL to be ready before continuing. The add-on can start
# before the database is accepting connections (e.g. on a Home Assistant reboot
# when both add-ons start together, or under load in CI), so retry instead of
# failing immediately - TeslaMate has no built-in retry for this pre-check and
# the s6 finish script would otherwise halt the whole add-on.
bashio::log.info "Waiting for PostgreSQL at '$DATABASE_HOST:$DATABASE_PORT'..."
pg_wait_attempt=0
pg_wait_max=30
until pg_isready -h "$DATABASE_HOST" -p "$DATABASE_PORT" > /dev/null 2>&1; do
pg_wait_attempt=$((pg_wait_attempt + 1))
if [[ "$pg_wait_attempt" -ge "$pg_wait_max" ]]; then
bashio::log.error "PostgreSQL at '$DATABASE_HOST' is not ready or unreachable after $((pg_wait_max * 2))s"
exit 1
fi
bashio::log.info "PostgreSQL not ready yet, retrying in 2s (${pg_wait_attempt}/${pg_wait_max})..."
sleep 2
done
bashio::log.info "PostgreSQL is ready"
# Create the PostgreSQL database if it doesn't exist # Create the PostgreSQL database if it doesn't exist
bashio::log.info "Checking for database '$DATABASE_NAME' on $DATABASE_HOST" bashio::log.info "Checking for database '$DATABASE_NAME' on $DATABASE_HOST"
if pg_isready -h "$DATABASE_HOST" -p "$DATABASE_PORT" > /dev/null 2>&1; then
# Check the version of PostgreSQL database is v16.7 or later or v17.3 or later # Check the version of PostgreSQL database is v16.7 or later or v17.3 or later
pg_version=$(PGPASSWORD="$DATABASE_PASS" psql -h "$DATABASE_HOST" -p "$DATABASE_PORT" -U "$DATABASE_USER" postgres -Atqc "SELECT regexp_replace(version(), 'PostgreSQL ([^ ]+) .*', '\\1') AS version") pg_version=$(PGPASSWORD="$DATABASE_PASS" psql -h "$DATABASE_HOST" -p "$DATABASE_PORT" -U "$DATABASE_USER" postgres -Atqc "SELECT regexp_replace(version(), 'PostgreSQL ([^ ]+) .*', '\\1') AS version")
major_version=$(echo "$pg_version" | cut -d '.' -f 1) major_version=$(echo "$pg_version" | cut -d '.' -f 1)
@@ -87,10 +105,6 @@ if pg_isready -h "$DATABASE_HOST" -p "$DATABASE_PORT" > /dev/null 2>&1; then
exit 1 exit 1
fi fi
fi fi
else
bashio::log.error "PostgreSQL at '$DATABASE_HOST' is not ready or unreachable"
exit 1
fi
# Import dashboards # Import dashboards
if bashio::config.true 'grafana_import_dashboards'; then if bashio::config.true 'grafana_import_dashboards'; then