From 0d0d69965e2551c7321346c76deaecd2289e553c Mon Sep 17 00:00:00 2001 From: Andrew Coleman Date: Mon, 24 Jul 2023 15:12:18 -0400 Subject: [PATCH] [REFACTOR] Rework initialization script to be more indempotent 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. --- src/modules/services/postgres.nix | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/src/modules/services/postgres.nix b/src/modules/services/postgres.nix index af729436e..581529bd8 100644 --- a/src/modules/services/postgres.nix +++ b/src/modules/services/postgres.nix @@ -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}" ] @@ -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 @@ -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"