nixos/mastodon: stop mastodon-init-db.service if check for seeded DB fails

The postgresql runs on a different node than my mastodon itself. Sometimes when
rebooting the entire host it can happen that mastodon gets started
before the DB[1] is up. In that case `mastodon-init-db.service` ran
through with the following log output:

    2024-03-07 15:30:56.856
    Migrating database (this might be a noop)
    2024-03-07 15:30:56.856
    /nix/store/xzm7www0qb7jg5zrgg7knynckx5yhki9-unit-script-mastodon-init-db-start/bin/mastodon-init-db-start: line 9: [: -eq: unary operator expected

It seems wrong to me to have this unit pass if the DB isn't even up,
especially with such an error.

This patch now checks if the exit code of the psql check was non-zero
and fails the entire unit. A retry can be implemented e.g. with
Restart/RestartSec then (which is more elegant than adding a while/sleep
loop anyways) like this:

    systemd.services.mastodon-init-db = {
      serviceConfig = {
        Restart = "on-failure";
        RestartSec = "5s";
        RestartMode = "direct";
        RemainAfterExit = true;
      };
      unitConfig = {
        StartLimitBurst = 5;
        StartLimitIntervalSec = "60";
      };
    };

Also using `-t --csv` now to not render the column name and to not
render a table so we don't need to rely on the format of psql (and parse
it with `sed(1)`).

[1] I added a script that blocks until postgres is there in the meantime
    though.
This commit is contained in:
Maximilian Bosch 2024-03-22 16:53:27 +01:00
parent 732cd2b4b8
commit e7533df80f
No known key found for this signature in database

View file

@ -742,11 +742,16 @@ in {
umask 077 umask 077
export PGPASSWORD="$(cat '${cfg.database.passwordFile}')" export PGPASSWORD="$(cat '${cfg.database.passwordFile}')"
'' + '' '' + ''
if [ `psql -c \ result="$(psql -t --csv -c \
"select count(*) from pg_class c \ "select count(*) from pg_class c \
join pg_namespace s on s.oid = c.relnamespace \ join pg_namespace s on s.oid = c.relnamespace \
where s.nspname not in ('pg_catalog', 'pg_toast', 'information_schema') \ where s.nspname not in ('pg_catalog', 'pg_toast', 'information_schema') \
and s.nspname not like 'pg_temp%';" | sed -n 3p` -eq 0 ]; then and s.nspname not like 'pg_temp%';")" || error_code=$?
if [ "''${error_code:-0}" -ne 0 ]; then
echo "Failure checking if database is seeded. psql gave exit code $error_code"
exit "$error_code"
fi
if [ "$result" -eq 0 ]; then
echo "Seeding database" echo "Seeding database"
SAFETY_ASSURED=1 rails db:schema:load SAFETY_ASSURED=1 rails db:schema:load
rails db:seed rails db:seed