krebs.systemd.restartIfCredentialsChange: check hashes

This commit is contained in:
tv 2022-12-29 15:22:29 +01:00
parent b3c5492b69
commit 4354fea0b4

View File

@ -3,8 +3,26 @@
body.options.krebs.systemd.services = lib.mkOption { body.options.krebs.systemd.services = lib.mkOption {
default = {}; default = {};
type = lib.types.attrsOf (lib.types.submodule { type = lib.types.attrsOf (lib.types.submodule (cfg_: let
serviceName = cfg_.config._module.args.name;
cfg = config.systemd.services.${serviceName} // cfg_.config;
in {
options = { options = {
credentialPaths = lib.mkOption {
default =
lib.sort
lib.lessThan
(lib.filter
lib.types.absolute-pathname.check
(map
(lib.compose [ lib.maybeHead (lib.match "[^:]*:(.*)") ])
(lib.toList cfg.serviceConfig.LoadCredential)));
readOnly = true;
};
credentialUnitName = lib.mkOption {
default = "trigger-${lib.systemd.encodeName serviceName}";
readOnly = true;
};
restartIfCredentialsChange = lib.mkOption { restartIfCredentialsChange = lib.mkOption {
default = false; default = false;
description = '' description = ''
@ -15,30 +33,40 @@
type = lib.types.bool; type = lib.types.bool;
}; };
}; };
}); }));
}; };
body.config = { body.config.systemd = lib.mkMerge (lib.mapAttrsToList (serviceName: cfg: {
systemd.paths = lib.mapAttrs' (serviceName: _: paths.${cfg.credentialUnitName} = {
lib.nameValuePair "trigger-${lib.systemd.encodeName serviceName}" { wantedBy = [ "multi-user.target" ];
wantedBy = [ "multi-user.target" ]; pathConfig.PathChanged = cfg.credentialPaths;
pathConfig.PathChanged = };
lib.filter services.${cfg.credentialUnitName} = {
lib.types.absolute-pathname.check serviceConfig = {
(map Type = "oneshot";
(lib.compose [ lib.maybeHead (lib.match "[^:]*:(.*)") ]) StateDirectory = "credentials";
(lib.toList ExecStart = pkgs.writeDash "${cfg.credentialUnitName}.sh" ''
config.systemd.services.${serviceName}.serviceConfig.LoadCredential)); set -efu
}
) config.krebs.systemd.services;
systemd.services = lib.mapAttrs' (serviceName: cfg: PATH=${lib.makeBinPath [
lib.nameValuePair "trigger-${lib.systemd.encodeName serviceName}" { pkgs.coreutils
serviceConfig = { pkgs.diffutils
Type = "oneshot"; pkgs.systemd
ExecStart = "${pkgs.systemd}/bin/systemctl restart ${lib.shell.escape serviceName}"; ]}
};
} cache=/var/lib/credentials/${lib.shell.escape serviceName}.sha1sum
) config.krebs.systemd.services; tmpfile=$(mktemp -t "$(basename "$cache")".XXXXXXXX)
}; trap 'rm -f "$tmpfile"' EXIT
sha1sum ${toString cfg.credentialPaths} > "$tmpfile"
if test -f "$cache" && cmp -s "$tmpfile" "$cache"; then
exit
fi
mv "$tmpfile" "$cache"
systemctl restart ${lib.shell.escape serviceName}
'';
};
};
}) config.krebs.systemd.services);
} }