putex/nixos-module.nix
2024-07-24 22:00:37 -05:00

104 lines
3.1 KiB
Nix

self: lib:
with lib;
{ config, ... }:
let cfg = config.services.putex;
prog = config.programs.putex;
shq = lib.escapeShellArg;
shqs = lib.escapeShellArgs;
in
let
#runCommand = cmd: derivation { name = "script"; builder = "/bin/sh"; args = [ "-c" cmd ]; };
#writeExecutable = cmd: runCommand ''
# echo "${cmd}" > $out
# chmod +x $out
#'';
generateSystemdUnits =
name: { nats, bucket, key, token, healthcheck, stop, start, enable, package }:
{
services."putex-${name}" = {
script = ''
${package}/bin/putex -vvv \
--nats ${shq nats} \
--bucket ${shq bucket} \
--key ${shq key} \
--token ${shq token} \
--healthcheck ${shq healthcheck} \
--start ${shq start} \
--stop ${shq stop}
'';
after = [ "network.target" ];
wantedBy = [ "network.target" ];
};
};
in
{
options = {
programs.putex = {
enable = mkEnableOption "putex" // { default = true; };
package = mkPackageOption self.packages.${config.nixpkgs.system} "putex" { };
};
services.putex = {
putexes = mkOption {
type = types.attrsOf (types.submodule ({name, ...}: {
options = {
nats = mkOption {
description = "NATS address for cluster backing the lock";
type = types.str;
default = "nats://127.0.0.1";
};
bucket = mkOption {
description = "bucket name in which to store the lock within which in";
type = types.str;
default = "putexes";
};
key = mkOption {
description = "kv key name for lock (the lock's \"name\" in the bucket)";
type = types.str;
default = name;
};
token = mkOption {
description = "kv token value which is unique to this agent within the context of the key.";
type = types.str;
default = "${config.networking.hostName}";
};
healthcheck = mkOption {
description = "script which evaluates the ability of this agent to serve as the host";
type = types.lines;
default = ''
! systemctl is-failed
'';
};
stop = mkOption {
description = "script to start the service";
type = types.lines;
default = ''
systemctl stop ${name}.service
'';
};
start = mkOption {
description = "script to start the service";
type = types.lines;
default = ''
systemctl start ${name}.service
'';
};
enable = mkEnableOption "putex for ${name}" // { default = true; };
package = mkPackageOption self.packages.${config.nixpkgs.system} "putex" { };
};
}));
};
};
};
config = {
services.putex.putexes = {};
environment.systemPackages = mkIf prog.enable [ prog.package ];
systemd = mkMerge (attrValues (mapAttrs generateSystemdUnits cfg.putexes));
};
}