sourcegraph/dev/postgres_exporter.sh
Quinn Slack cba9083554
dev postgres_exporter: respect PG* env var effective values (#7664)
PostgreSQL's `PG*` env vars have defined fallbacks. For example, the default for PGUSER (if unset) is `$USER`. This commit makes the dev postgres_exporter use the effective values instead of hardcoding the defaults.

This fixes many instances of errors in the dev/start.sh script of the form:

```
22:21:17   postgres_exporter | time="2020-01-11T06:21:17Z" level=error msg="Error opening connection to database (postgresql://sourcegraph:PASSWORD_REMOVED@localhost:5432/postgres?sslmode=disable): pq: password authentication failed for user \"sourcegraph\"" source="postgres_exporter.go:1403"
```

(Personally, I do not have PGUSER set in my environment, and my PostgreSQL username is `sqs`. I could set PGUSER, but this change makes it so I don't need to, and it will work in more cases without the dev needing to do manual workarounds for the dev postgres_exporter.)
2020-01-16 20:04:43 -08:00

32 lines
1.2 KiB
Bash
Executable File

#!/usr/bin/env bash
# Description: Prometheus collects metrics and aggregates them into graphs.
#
set -euf -o pipefail
IMAGE=wrouesnel/postgres_exporter:v0.7.0@sha256:785c919627c06f540d515aac88b7966f352403f73e931e70dc2cbf783146a98b
CONTAINER=postgres_exporter
# Use psql to read the effective values for PG* env vars (instead of, e.g., hardcoding the default
# values).
get_pg_env() { psql -c '\set' | grep $1 | cut -f 2 -d "'"; }
PGHOST=${PGHOST-$(get_pg_env HOST)}
PGUSER=${PGUSER-$(get_pg_env USER)}
PGPORT=${PGPORT-$(get_pg_env PORT)}
ADJUSTED_HOST=${PGHOST:-127.0.0.1}
if [[ ("$ADJUSTED_HOST" == "localhost" || "$ADJUSTED_HOST" == "127.0.0.1") && "$OSTYPE" != "linux-gnu" ]]; then
ADJUSTED_HOST="host.docker.internal"
fi
NET_ARG=""
DATA_SOURCE_NAME="postgresql://${PGUSER}:${PGPASSWORD}@${ADJUSTED_HOST}:${PGPORT}/postgres?sslmode=${PGSSLMODE:-disable}"
if [[ "$OSTYPE" == "linux-gnu" ]]; then
NET_ARG="--net=host"
DATA_SOURCE_NAME="postgresql://${PGUSER}:${PGPASSWORD}@${ADJUSTED_HOST}:${PGPORT}/postgres?sslmode=${PGSSLMODE:-disable}"
fi
exec docker run --rm -p9187:9187 ${NET_ARG} --name=postgres_exporter -e DATA_SOURCE_NAME=${DATA_SOURCE_NAME} ${IMAGE}