modules/consul-service-registry: fix bugs, add external registration mode

This commit is contained in:
Max Headroom 2023-03-05 23:50:26 +01:00
parent 674fde3617
commit 7aab09157e

View file

@ -1,4 +1,4 @@
{ config, lib, ... }: { config, lib, pkgs, ... }:
with lib; with lib;
@ -7,28 +7,51 @@ let
consul = "${config.services.consul.package}/bin/consul"; consul = "${config.services.consul.package}/bin/consul";
consulServiceDefinition = submodule ({ name, ... }: { consulServiceDefinition = types.submodule ({ name, ... }: {
options = {
unit = mkOption { unit = mkOption {
description = "Which systemd service to attach to."; description = "Which systemd service to attach to.";
default = name; default = name;
type = types.str; type = types.str;
}; };
mode = mkOption {
description = "How to attach command executions to the service.";
type = types.enum [ "direct" "external" ];
default = "direct";
};
definition = mkOption { definition = mkOption {
description = "Consul service definition."; description = "Consul service definition.";
type = types.attrs; type = types.attrs;
}; };
};
}); });
attachToService = name: conf: let attachToService = name: conf: let
serviceJson = pkgs.writeText "consul-service-${name}.json" (builtins.toJSON conf.definition); serviceJson = pkgs.writeText "consul-service-${name}.json" (builtins.toJSON conf.definition);
in { in {
name = conf.unit; name = {
direct = conf.unit;
external = "register-consul-svc-${conf.unit}";
}.${conf.mode};
value = { value = {
direct = {
serviceConfig = { serviceConfig = {
ExecStartPost = "${consul} services register ${serviceJson}"; ExecStartPost = "${consul} services register ${serviceJson}";
ExecStopPre = "${consul} services deregister ${serviceJson}"; ExecStopPre = "${consul} services deregister ${serviceJson}";
}; };
}; };
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};
}; };
in in