Skip to content

Commit

Permalink
[REFACTOR] Rework initialization script to be more indempotent
Browse files Browse the repository at this point in the history
This change will "hide" the temporary server from the readiness checks
in addition to not listening on a TCP port. While initializing, the
readiness should be "not ready". It creates a temporary directory
inside of `$DEVENV_STATE` to hold the temporary UNIX socket. It also
overwrites `$PGHOST` to set the default for `psql` and restores the
old value when finished. It removes the temporary socket directory
explicitly and sets a `trap` to remove if there is an error.
  • Loading branch information
penguincoder committed Jul 24, 2023
1 parent 6ddb5c7 commit 0d0d699
Showing 1 changed file with 22 additions and 6 deletions.
28 changes: 22 additions & 6 deletions src/modules/services/postgres.nix
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ let
echo "Creating database: ${database.name}"
echo 'create database "${database.name}";' | psql --dbname postgres
${lib.optionalString (database.schema != null) ''
echo "Applying database schema on ${database.name}"
if [ -f "${database.schema}" ]
Expand Down Expand Up @@ -83,8 +82,10 @@ let
set -euo pipefail
export PATH=${postgresPkg}/bin:${pkgs.coreutils}/bin
SEED_DATABASES="false"
if [[ ! -d "$PGDATA" ]]; then
initdb ${lib.concatStringsSep " " cfg.initdbArgs}
SEED_DATABASES="true"
echo
echo "PostgreSQL init process complete; ready for start up."
echo
Expand All @@ -93,17 +94,32 @@ let
# Setup config
cp ${configFile} "$PGDATA/postgresql.conf"
if [[ ! -f "$PGDATA/.configured" ]]; then
touch "$PGDATA/.configured"
if [[ "$SEED_DATABASES" = "true" ]]; then
echo
echo "PostgreSQL appears unconfigured; going to run initialization scripts."
echo "PostgreSQL recently initialized; going to seed databases."
echo
pg_ctl -D "$PGDATA" -w start
OLDPGHOST="$PGHOST"
PGHOST="$DEVENV_STATE/$(mktemp -d "pg-init-XXXXXX")"
mkdir -p "$PGHOST"
function remove_tmp_pg_init_sock_dir() {
if [[ -d "$1" ]]; then
echo
echo "Removing temporary socket directory for initialization/seeding: $1"
echo
rm -rf "$1"
fi
}
trap "remove_tmp_pg_init_sock_dir '$PGHOST'" EXIT
pg_ctl -D "$PGDATA" -w start -o "-c unix_socket_directories=$PGHOST -c listen_addresses= -p ${toString cfg.port}"
${setupInitialDatabases}
${runInitialScript}
pg_ctl -D "$PGDATA" -m fast -w stop
remove_tmp_pg_init_sock_dir "$PGHOST"
PGHOST="$OLDPGHOST"
unset OLDPGHOST
else
echo
echo "PostgreSQL Database directory appears to contain a database; Skipping initialization"
Expand Down

0 comments on commit 0d0d699

Please sign in to comment.