2023-03-06 00:50:26 +02:00
|
|
|
{ config, lib, pkgs, ... }:
|
2023-03-05 23:50:01 +02:00
|
|
|
|
|
|
|
with lib;
|
|
|
|
|
|
|
|
let
|
|
|
|
cfg = config.consul;
|
|
|
|
|
|
|
|
consul = "${config.services.consul.package}/bin/consul";
|
|
|
|
|
2023-03-06 00:50:26 +02:00
|
|
|
consulServiceDefinition = types.submodule ({ name, ... }: {
|
|
|
|
options = {
|
|
|
|
unit = mkOption {
|
|
|
|
description = "Which systemd service to attach to.";
|
|
|
|
default = name;
|
|
|
|
type = types.str;
|
|
|
|
};
|
|
|
|
mode = mkOption {
|
|
|
|
description = "How to attach command executions to the service.";
|
|
|
|
type = types.enum [ "direct" "external" ];
|
|
|
|
default = "direct";
|
|
|
|
};
|
|
|
|
definition = mkOption {
|
|
|
|
description = "Consul service definition.";
|
|
|
|
type = types.attrs;
|
|
|
|
};
|
2023-03-05 23:50:01 +02:00
|
|
|
};
|
|
|
|
});
|
|
|
|
|
|
|
|
attachToService = name: conf: let
|
|
|
|
serviceJson = pkgs.writeText "consul-service-${name}.json" (builtins.toJSON conf.definition);
|
|
|
|
in {
|
2023-03-06 00:50:26 +02:00
|
|
|
name = {
|
|
|
|
direct = conf.unit;
|
|
|
|
external = "register-consul-svc-${conf.unit}";
|
|
|
|
}.${conf.mode};
|
2023-03-05 23:50:01 +02:00
|
|
|
value = {
|
2023-03-06 00:50:26 +02:00
|
|
|
direct = {
|
|
|
|
serviceConfig = {
|
|
|
|
ExecStartPost = "${consul} services register ${serviceJson}";
|
2023-03-06 01:11:52 +02:00
|
|
|
ExecStopPost = "${consul} services deregister ${serviceJson}";
|
2023-03-06 00:50:26 +02:00
|
|
|
};
|
2023-03-05 23:50:01 +02:00
|
|
|
};
|
2023-03-06 00:50:26 +02:00
|
|
|
external = {
|
|
|
|
after = [ "${conf.unit}.service" ];
|
|
|
|
wantedBy = [ "${conf.unit}.service" ];
|
|
|
|
unitConfig.BindsTo = "${conf.unit}.service";
|
|
|
|
serviceConfig = {
|
|
|
|
Type = "oneshot";
|
|
|
|
RemainAfterExit = true;
|
|
|
|
ExecStart = "${consul} services register ${serviceJson}";
|
|
|
|
ExecStop = "${consul} services deregister ${serviceJson}";
|
|
|
|
};
|
|
|
|
};
|
|
|
|
}.${conf.mode};
|
2023-03-05 23:50:01 +02:00
|
|
|
};
|
|
|
|
in
|
|
|
|
|
|
|
|
{
|
|
|
|
options.consul = {
|
|
|
|
services = mkOption {
|
|
|
|
type = with types; attrsOf consulServiceDefinition;
|
|
|
|
default = {};
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
config = lib.mkIf (cfg.services != {}) {
|
|
|
|
systemd.services = mapAttrs' attachToService cfg.services;
|
|
|
|
warnings = optional (!config.services.consul.enable) "Consul service registrations found, but Consul agent is not enabled on this machine.";
|
|
|
|
};
|
|
|
|
}
|