nixos/postgresql: implement auto-restart & rework dependencies of postgresql.target (#424625)

authored by

Leona Maroni and committed by
GitHub
3b5e1ef5 a74b4f51

+30 -4
+24 -4
nixos/modules/services/databases/postgresql.nix
··· 769 769 systemd.targets.postgresql = { 770 770 description = "PostgreSQL"; 771 771 wantedBy = [ "multi-user.target" ]; 772 - bindsTo = [ 772 + requires = [ 773 773 "postgresql.service" 774 774 "postgresql-setup.service" 775 775 ]; ··· 780 780 781 781 after = [ "network.target" ]; 782 782 783 - # To trigger the .target also on "systemctl start postgresql". 784 - bindsTo = [ "postgresql.target" ]; 783 + # To trigger the .target also on "systemctl start postgresql" as well as on 784 + # restarts & stops. 785 + # Please note that postgresql.service & postgresql.target binding to 786 + # each other makes the Restart=always rule racy and results 787 + # in sometimes the service not being restarted. 788 + wants = [ "postgresql.target" ]; 789 + partOf = [ "postgresql.target" ]; 785 790 786 791 environment.PGDATA = cfg.dataDir; 787 792 ··· 820 825 TimeoutSec = 120; 821 826 822 827 ExecStart = "${cfg.finalPackage}/bin/postgres"; 828 + 829 + Restart = "always"; 823 830 824 831 # Hardening 825 832 CapabilityBoundingSet = [ "" ]; ··· 872 879 }) 873 880 ]; 874 881 875 - unitConfig.RequiresMountsFor = "${cfg.dataDir}"; 882 + unitConfig = 883 + let 884 + inherit (config.systemd.services.postgresql.serviceConfig) TimeoutSec; 885 + maxTries = 5; 886 + bufferSec = 5; 887 + in 888 + { 889 + RequiresMountsFor = "${cfg.dataDir}"; 890 + 891 + # The max. time needed to perform `maxTries` start attempts of systemd 892 + # plus a bit of buffer time (bufferSec) on top. 893 + StartLimitIntervalSec = TimeoutSec * maxTries + bufferSec; 894 + StartLimitBurst = maxTries; 895 + }; 876 896 }; 877 897 878 898 systemd.services.postgresql-setup = {
+6
nixos/tests/postgresql/postgresql.nix
··· 101 101 machine.fail(check_count("SELECT * FROM sth;", 4)) 102 102 machine.succeed(check_count("SELECT xpath('/test/text()', doc) FROM xmltest;", 1)) 103 103 104 + with subtest("killing postgres process should trigger an automatic restart"): 105 + machine.succeed("systemctl kill -s KILL postgresql") 106 + 107 + machine.wait_until_succeeds("systemctl is-active postgresql.service") 108 + machine.wait_until_succeeds("systemctl is-active postgresql.target") 109 + 104 110 with subtest("Backup service works"): 105 111 machine.succeed( 106 112 "systemctl start ${backupService}.service",