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
|
|
|
};
|
|
|
|
});
|
|
|
|
|
2023-03-06 17:42:14 +02:00
|
|
|
attachToService = unit: servicesRaw: let
|
|
|
|
services = map (getAttr "definition") servicesRaw;
|
|
|
|
servicesJson = pkgs.writeText "consul-services-${unit}.json" (builtins.toJSON { inherit services; });
|
|
|
|
mode = if any (x: x.mode == "external") servicesRaw then "external" else "direct";
|
2023-03-05 23:50:01 +02:00
|
|
|
in {
|
2023-03-06 00:50:26 +02:00
|
|
|
name = {
|
2023-03-06 17:42:14 +02:00
|
|
|
direct = unit;
|
|
|
|
external = "register-consul-svc-${unit}";
|
|
|
|
}.${mode};
|
2023-03-05 23:50:01 +02:00
|
|
|
value = {
|
2023-03-06 00:50:26 +02:00
|
|
|
direct = {
|
|
|
|
serviceConfig = {
|
2023-03-06 17:42:14 +02:00
|
|
|
ExecStartPost = "${consul} services register ${servicesJson}";
|
|
|
|
ExecStopPost = "${consul} services deregister ${servicesJson}";
|
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 = {
|
2023-03-06 17:42:14 +02:00
|
|
|
after = [ "${unit}.service" ];
|
|
|
|
wantedBy = [ "${unit}.service" ];
|
|
|
|
unitConfig.BindsTo = "${unit}.service";
|
2023-03-06 00:50:26 +02:00
|
|
|
serviceConfig = {
|
|
|
|
Type = "oneshot";
|
|
|
|
RemainAfterExit = true;
|
2023-03-06 17:42:14 +02:00
|
|
|
ExecStart = "${consul} services register ${servicesJson}";
|
|
|
|
ExecStop = "${consul} services deregister ${servicesJson}";
|
2023-03-06 00:50:26 +02:00
|
|
|
};
|
|
|
|
};
|
2023-03-06 17:42:14 +02:00
|
|
|
}.${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 != {}) {
|
2023-03-06 17:42:14 +02:00
|
|
|
systemd.services = mapAttrs' attachToService (groupBy (getAttr "unit") (attrValues cfg.services));
|
2023-03-05 23:50:01 +02:00
|
|
|
warnings = optional (!config.services.consul.enable) "Consul service registrations found, but Consul agent is not enabled on this machine.";
|
|
|
|
};
|
|
|
|
}
|