{ config, pkgs, lib, mylib, ... }: let # The services that ask for it. Their units come from templates, since # units can't be made from config.systemd.services itself. watched = lib.filterAttrs (_: service: service.restartIfCredentialsChange || service.reloadIfCredentialsChange) config.systemd.services; action = service: if service.reloadIfCredentialsChange then "reload" else "restart"; template = action: { serviceConfig = { Type = "oneshot"; ExecStart = "${pkgs.systemd}/bin/systemctl ${builtins.getAttr action { reload = "try-reload-or-restart"; restart = "try-restart"; }} %i"; }; }; in { # stockholm's repo-sync still uses the old name. imports = [ (lib.mkAliasOptionModule [ "krebs" "systemd" "services" ] [ "systemd" "services" ]) ]; options.systemd.services = lib.mkOption { type = lib.types.attrsOf (lib.types.submodule ({ config, name, ... }: { options = { credentialPaths = lib.mkOption { default = lib.sort lib.lessThan (lib.filter mylib.types.absolute-pathname.check (map (mylib.compose [ mylib.maybeHead (builtins.match "[^:]*:(.*)") ]) (lib.toList config.serviceConfig.LoadCredential or []))); readOnly = true; }; credentialUnitName = lib.mkOption { default = "trigger-${mylib.systemd.encodeName name}"; readOnly = true; }; restartIfCredentialsChange = lib.mkOption { default = false; description = '' Whether to restart the service whenever any of its credentials change. Only credentials with an absolute path in LoadCredential= are supported. ''; type = lib.types.bool; }; reloadIfCredentialsChange = lib.mkOption { default = false; description = '' Whether to reload the service, or restart it if it isn't running or can't be reloaded, whenever any of its credentials change. Its reload must read the credentials again. ''; type = lib.types.bool; }; }; # Without it, a reload leaves the credentials as they were. config.serviceConfig = lib.mkIf config.reloadIfCredentialsChange { RefreshOnReload = "credentials"; }; })); }; config = { assertions = lib.mapAttrsToList (serviceName: service: { # With RefreshOnReload= set, systemd reloads a service without ExecReload= # by refreshing its credentials only, without telling the service. assertion = service.reloadIfCredentialsChange -> service.serviceConfig ? ExecReload || service.serviceConfig.Type or "" == "notify-reload"; message = "systemd.services.${serviceName}.reloadIfCredentialsChange needs ExecReload= or Type=notify-reload"; }) config.systemd.services; systemd.paths = lib.mapAttrs' (serviceName: service: lib.nameValuePair service.credentialUnitName { wantedBy = [ "multi-user.target" ]; pathConfig = { PathChanged = service.credentialPaths; Unit = "credentials-${action service}@${serviceName}.service"; }; } ) watched; # Unconditionally: whether a service asks for them depends on # config.systemd.services. systemd.services."credentials-reload@" = template "reload"; systemd.services."credentials-restart@" = template "restart"; }; }