From e7533df80fd18b4a06b44142e863738c3f3bced5 Mon Sep 17 00:00:00 2001 From: Maximilian Bosch Date: Fri, 22 Mar 2024 16:53:27 +0100 Subject: [PATCH] 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. --- nixos/modules/services/web-apps/mastodon.nix | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/nixos/modules/services/web-apps/mastodon.nix b/nixos/modules/services/web-apps/mastodon.nix index 7fc710c6fcec..5e9a7cc22248 100644 --- a/nixos/modules/services/web-apps/mastodon.nix +++ b/nixos/modules/services/web-apps/mastodon.nix @@ -742,11 +742,16 @@ in { umask 077 export PGPASSWORD="$(cat '${cfg.database.passwordFile}')" '' + '' - if [ `psql -c \ - "select count(*) from pg_class c \ - join pg_namespace s on s.oid = c.relnamespace \ - where s.nspname not in ('pg_catalog', 'pg_toast', 'information_schema') \ - and s.nspname not like 'pg_temp%';" | sed -n 3p` -eq 0 ]; then + result="$(psql -t --csv -c \ + "select count(*) from pg_class c \ + join pg_namespace s on s.oid = c.relnamespace \ + where s.nspname not in ('pg_catalog', 'pg_toast', 'information_schema') \ + 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" SAFETY_ASSURED=1 rails db:schema:load rails db:seed