3 , srvsrht ? "${srv}srht" # Because "buildsrht" does not follow that pattern (missing an "s").
4 , iniKey ? "${srv}.sr.ht"
14 { config, lib, pkgs, ... }:
18 inherit (config.services) postgresql redis;
19 inherit (config.users) users;
20 cfg = config.services.sourcehut;
21 configIni = configIniOfService srv;
22 domain = cfg.settings."sr.ht".global-domain;
24 baseService = serviceName: { noStripe ? true }: extraService: let
25 runDir = "/run/sourcehut/${serviceName}";
26 rootDir = "/run/sourcehut/chroots/${serviceName}";
28 mkMerge [ commonService extraService {
30 environment.HOME = runDir;
33 "sourcehut/${serviceName}"
34 "sourcehut/chroots/${serviceName}"
36 RuntimeDirectoryMode = "2750";
37 # No need for the chroot path once inside the chroot
38 InaccessiblePaths = [ "-+${rootDir}" ];
39 # For intermediate directories created by BindPaths= and others
41 RootDirectory = rootDir;
42 RootDirectoryStartOnly = true;
45 # config.ini is looked up in there, before /etc/srht/config.ini
46 # Note that it fails to be set in ExecStartPre=
47 WorkingDirectory = "-"+runDir;
56 optional cfg.redis.enable "/run/redis" ++
57 optional cfg.postgresql.enable "/run/postgresql";
58 # LoadCredential= are unfortunately not available in ExecStartPre=
59 # Hence this one is run as root (the +) with RootDirectoryStartOnly=
60 # to reach credentials wherever they are.
61 # Note that each systemd service gets its own ${runDir}/config.ini file.
62 ExecStartPre = mkBefore [("+"+pkgs.writeShellScript "${serviceName}-credentials" ''
64 # Replace values begining with a '<' by the content of the file whose name is after.
65 gawk '{ if (match($0,/^([^=]+=)<(.+)/,m)) { getline f < m[2]; print m[1] f } else print $0 }' ${configIni} |
66 ${optionalString noStripe "gawk '!/^stripe-secret-key=/' |"}
67 install -o ${srvCfg.user} -g root -m 400 /dev/stdin ${runDir}/config.ini
69 LogsDirectory = [ "sourcehut/${serviceName}" ];
70 # The following options are only for optimizing:
71 # systemd-analyze security
72 AmbientCapabilities = "";
73 CapabilityBoundingSet = "";
74 # ProtectClock= adds DeviceAllow=char-rtc r
76 LockPersonality = true;
77 MemoryDenyWriteExecute = true;
78 NoNewPrivileges = true;
79 PrivateDevices = true;
81 PrivateNetwork = mkDefault false;
85 ProtectControlGroups = true;
87 ProtectHostname = true;
88 ProtectKernelLogs = true;
89 ProtectKernelModules = true;
90 ProtectKernelTunables = true;
91 ProtectProc = "invisible";
92 ProtectSystem = "strict";
94 RestrictAddressFamilies = [ "AF_UNIX" "AF_INET" "AF_INET6" ];
95 RestrictNamespaces = true;
96 RestrictRealtime = true;
97 RestrictSUIDSGID = true;
98 #SocketBindAllow = [ "tcp:${toString srvCfg.port}" "tcp:${toString srvCfg.prometheusPort}" ];
99 #SocketBindDeny = "any";
102 "~@aio" "~@keyring" "~@memlock" "~@privileged" "~@resources" "~@timer"
105 SystemCallArchitectures = "native";
110 options.services.sourcehut.${srv} = {
111 enable = mkEnableOption "${srv} service";
117 User for ${srv}.sr.ht.
125 Port on which the "${srv}" module should listen.
129 database = mkOption {
131 default = "${srv}.sr.ht";
133 PostgreSQL database name for ${srv}.sr.ht.
138 config = lib.mkIf (cfg.enable && srvCfg.enable) (mkMerge [ extraConfig {
143 group = mkDefault srvCfg.user;
144 description = mkDefault "sourcehut user for ${srv}.sr.ht";
148 "${srvCfg.user}" = { };
149 } // optionalAttrs (cfg.postgresql.enable
150 && hasSuffix "0" (postgresql.settings.unix_socket_permissions or "")) {
151 "postgres".members = [ srvCfg.user ];
155 services.nginx.virtualHosts = mkIf cfg.nginx.enable {
156 "${srv}.${domain}" = {
158 locations."/".proxyPass = "http://${cfg.listenAddress}:${toString srvCfg.port}";
159 locations."/query".proxyPass = cfg.settings."meta.sr.ht".api-origin;
160 locations."/static".root = "${pkgs.sourcehut.${srvsrht}}/${pkgs.sourcehut.python.sitePackages}/${srvsrht}";
164 services.postgresql = mkIf cfg.postgresql.enable {
166 local ${srvCfg.database} ${srvCfg.user} trust
168 # shrt-keys stores SSH keys in the PostgreSQL database of the service calling it
169 + optionalString (elem srv ["builds" "git" "hg"]) ''
170 local ${srvCfg.database} ${users."sshsrht".name} trust
172 ensureDatabases = [ srvCfg.database ];
173 ensureUsers = map (name: {
175 ensurePermissions = { "DATABASE \"${srvCfg.database}\"" = "ALL PRIVILEGES"; };
176 }) ([srvCfg.user] ++ optional (elem srv ["builds" "git" "hg"]) users."sshsrht".name);
179 services.sourcehut.services = mkDefault (filter (s: cfg.${s}.enable)
180 [ "builds" "dispatch" "git" "hg" "hub" "lists" "man" "meta" "pages" "paste" "todo" ]);
182 services.sourcehut.settings = mkMerge [
185 origin = mkDefault "https://${srv}.${domain}";
189 (mkIf (cfg.redis.enable && webhooks != null) {
190 "${srv}.sr.ht".webhooks = mkDefault "redis://localhost:${toString redis.port}/${toString (cfg.redis.firstDatabase + webhooks.redisDatabase)}";
193 (mkIf (cfg.redis.enable && redisDatabase != null) {
194 "${srv}.sr.ht".redis = mkDefault "redis://localhost:${toString redis.port}/${toString (cfg.redis.firstDatabase + redisDatabase)}";
197 (mkIf cfg.postgresql.enable {
198 "${srv}.sr.ht".connection-string = mkDefault "postgresql:///${srvCfg.database}?user=${srvCfg.user}&host=/run/postgresql";
202 systemd.services = mkMerge [
203 { "${srvsrht}" = baseService srvsrht { noStripe = srv != "meta"; }
205 description = "sourcehut ${srv}.sr.ht website service";
206 after = [ "network.target" ]
207 ++ optional cfg.postgresql.enable "postgresql.service"
208 ++ optional (srv != "meta" && cfg.meta.enable) "metasrht-api.service";
209 requires = optional cfg.postgresql.enable "postgresql.service";
210 wantedBy = [ "multi-user.target" ];
211 path = optional cfg.postgresql.enable config.services.postgresql.package;
212 # Beware: change in credentials' content will not trigger restart.
213 restartTriggers = [ configIni ];
218 Restart = mkDefault "always";
219 #RestartSec = mkDefault "2min";
220 StateDirectory = [ "sourcehut/${srvsrht}" ];
221 StateDirectoryMode = "2750";
222 ExecStart = "${cfg.python}/bin/gunicorn ${srvsrht}.app:app -b ${cfg.listenAddress}:${toString srvCfg.port}";
225 version = pkgs.sourcehut.${srvsrht}.version;
226 stateDir = "/var/lib/sourcehut/${srvsrht}";
229 # Use the /run/sourcehut/${srvsrht}/config.ini
230 # installed by a previous ExecStartPre= in baseService
231 cd /run/sourcehut/${srvsrht}
233 if test ! -e ${stateDir}/db; then
234 # Setup the initial database
235 ${cfg.python}/bin/python <<EOF
236 from ${srvsrht}.app import db
240 # Set the initial state of the database for future database upgrades
241 if test -e ${cfg.python}/bin/${srvsrht}-migrate; then
242 # Run alembic stamp head once to tell alembic the schema is up-to-date
243 ${cfg.python}/bin/${srvsrht}-migrate stamp head
246 echo ${version} > ${stateDir}/db
249 # Update copy of each users' profile to the latest
250 # See https://lists.sr.ht/~sircmpwn/sr.ht-admins/<20190302181207.GA13778%40cirno.my.domain>
251 if test ! -e ${stateDir}/webhook; then
252 # Update ${iniKey}'s users' profile copy to the latest
253 ${cfg.python}/bin/srht-update-profiles ${iniKey}
255 touch ${stateDir}/webhook
258 ${optionalString cfg.settings.${iniKey}.migrate-on-upgrade ''
259 if [ "$(cat ${stateDir}/db)" != "${version}" ]; then
260 # Manage schema migrations using alembic
261 ${cfg.python}/bin/${srvsrht}-migrate -a upgrade head
263 # Mark down current package version
264 echo ${version} > ${stateDir}/db
271 (mkIf (webhooks != null) {
272 "${srvsrht}-webhooks" = baseService "${srvsrht}-webhooks" {}
274 description = "sourcehut ${srv}.sr.ht webhooks service";
275 after = [ "${srvsrht}.service" ]
276 ++ optional cfg.redis.enable "redis.service";
277 requires = [ "${srvsrht}.service" ]
278 ++ optional cfg.redis.enable "redis.service";
279 wantedBy = [ "${srvsrht}.service" ];
280 requiredBy = [ "${srvsrht}.service" ];
284 Group = mkDefault srvCfg.user;
286 ExecStart = "${cfg.python}/bin/celery -A ${srvsrht}.webhooks worker --loglevel INFO --pool eventlet";
287 # Avoid crashing: os.getloadavg()
288 ProcSubset = mkForce "all";
293 (mapAttrs (timerName: timerConfig: (baseService timerName {}
295 description = "sourcehut ${timerName} service";
296 after = [ "${srvsrht}.service" ];
297 requires = [ "${srvsrht}.service" ];
301 Group = mkDefault srvCfg.user;
303 ExecStart = "${cfg.python}/bin/${timerName}";
308 (mapAttrs (serviceName: service: baseService serviceName {}
310 description = "sourcehut ${serviceName}";
311 after = [ "${srvsrht}.service" ];
312 requires = [ "${srvsrht}.service" ];
313 wantedBy = [ "multi-user.target" ];
317 Group = mkDefault srvCfg.user;
318 Restart = mkDefault "always";
324 systemd.timers = mapAttrs (timerName: timerConfig:
326 description = "sourcehut timer for ${timerName}";
327 wantedBy = [ "timers.target" ];