1

I am developing a simple data science environment with Python tools and a database. When I enter the nix-shell, I spin up the database process. I would like to spin it down when exiting the environment.

How could I use trap and nix to accomplish that?

1

I've been using something like the following:

./shell.nix:

let
  pkgs = import <nixpkgs> { };

in with pkgs; mkShell {
  buildInputs = [ glibcLocales postgresql ];

  shellHook = ''
    export LANG=en_US.UTF-8
           PGDATABASE=some-dbname \
           PGDATA="$PWD/nix/pgdata" \
           PGHOST="$PWD/nix/sockets" \
           PGPORT="5433" \
           PGUSER="$USER"

    trap "'$PWD/nix/client' remove" EXIT
    nix/client add
  '';
}

./nix/client

#! /usr/bin/env bash

set -eu

client_pid=$PPID

start_postgres() {
    if postgres_is_stopped
    then
        logfile="$PWD/log/pg.log"
        mkdir -p "$PGHOST" "${logfile%/*}"
        (set -m
        pg_ctl start --silent -w --log "$logfile" -o "-k $PGHOST -h ''")
    fi
}

postgres_is_stopped() {
    pg_ctl status >/dev/null
    (( $? == 3 ))
}

case "$1" in
    add)
        mkdir -p nix/pids touch nix/pids/$client_pid
        if [ -d "$PGDATA" ]
        then
            start_postgres
        else
            pg_ctl initdb --silent -o '--auth=trust' && start_postgres && createdb $PGDATABASE
        fi
        ;;
    remove)
        rm nix/pids/$client_pid
        if [ -n "$(find nix/pids -prune -empty)" ]
        then
            pg_ctl stop --silent -W
        fi
        ;;
    *)
        echo "Usage: ${BASH_SOURCE[0]##*/} {add | remove}"
        exit 1
        ;;
esac

The EXIT trap will shut down the database server if no other nix-shell sessions are still using it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.