Skip to content

Commit

Permalink
Add module with oneshot service for postgresql migration
Browse files Browse the repository at this point in the history
Problem: From time to time we need to update the version of postgresql
running on our infra. When a major version of postgres is changed,
usually, a dedicated migration for data directory is needed.

Solution: To remove the necessity to do the migration manually,
introduce a module that will add a oneshot service which will perform a
migration prior to starting postresql service.
  • Loading branch information
rvem committed Aug 11, 2023
1 parent 042ae97 commit 7422964
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
1 change: 1 addition & 0 deletions flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
hetzner-cloud = import ./modules/virtualization/hetzner-cloud.nix;
ec2 = import ./modules/virtualization/ec2.nix;
wireguard-monitoring = import ./modules/wireguard-monitoring/default.nix;
postgresql-migration = import ./modules/postgresql-migration.nix
};
} // flake-utils.lib.eachDefaultSystem (system:
# (pinned nix-unstable version does not support aarch64-darwin)
Expand Down
46 changes: 46 additions & 0 deletions modules/postgresql-migration.nix
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{ pkgs, config, lib, ... }:
let
inherit (lib) mkOption mkEnableOption mkIf types;
cfg = config.services.postgresql-migrate;
in {
options.services.postgresql-migrate = {
enable = mkEnableOption "postgresql-migration";
old-postgresql = mkOption {
type = types.package;
description = "Old postgresql package to migrate from";
};
new-postgresql = mkOption {
type = types.package;
description = "New postgresql package to migrate to";
};
};
config = mkIf cfg.enable {
systemd.services.postgresql-migrate = {
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
User = "postgres";
Group = "postgres";
StateDirectory = "postgresql";
WorkingDirectory = "${builtins.dirOf config.services.postgresql.dataDir}";
};
script = let
oldDataDir = "${builtins.dirOf config.services.postgresql.dataDir}/${cfg.old-postgresql.psqlSchema}";
newDataDir = "${config.services.postgresql.dataDir}";
in ''
if [[ ! -d ${newDataDir} ]]; then
install -d -m 0700 -o postgres -g postgres "${newDataDir}"
${cfg.new-postgresql}/bin/initdb -D "${newDataDir}"
${cfg.new-postgresql}/bin/pg_upgrade --old-datadir "${oldDataDir}" --new-datadir "${newDataDir}" \
--old-bindir "${cfg.old-postgresql}/bin" --new-bindir "${cfg.new-postgresql}/bin"
else
echo "${newDataDir} already exists, not performing migration"
fi
'';
};
systemd.services.postgresql = {
after = [ "postgresql-migrate.service" ];
requires = [ "postgresql-migrate.service" ];
};
};
}

0 comments on commit 7422964

Please sign in to comment.