From 6635ea516dd102c9a900ede630598b026473165e Mon Sep 17 00:00:00 2001 From: Max Date: Sun, 27 Aug 2023 16:25:44 +0200 Subject: [PATCH] modules/consul-distributed-services: init --- .../consul-distributed-services/default.nix | 43 +++++++++++++++++++ modules/part.nix | 2 + 2 files changed, 45 insertions(+) create mode 100644 modules/consul-distributed-services/default.nix diff --git a/modules/consul-distributed-services/default.nix b/modules/consul-distributed-services/default.nix new file mode 100644 index 0000000..1297a84 --- /dev/null +++ b/modules/consul-distributed-services/default.nix @@ -0,0 +1,43 @@ +{ config, lib, pkgs, ... }: + +with lib; + +let + consul = config.services.consul.package; +in +{ + options.systemd.services = mkOption { + type = with types; attrsOf (submodule ({ config, ... }: let + cfg = config.distributed; + in { + config = mkIf cfg.enable { + + }; + })); + }; + + config.systemd.packages = pipe config.systemd.services [ + (filterAttrs (_: v: v.distributed.enable)) + (mapAttrsToList (n: v: let + inherit (v.serviceConfig) ExecStart; + + cfg = v.distributed; + + svc = config.consul.services.${cfg.registerService}; + + runWithRegistration = pkgs.writeShellScript "run-with-registration" '' + trap '${svc.commands.deregister}' EXIT + ${svc.commands.register} + ''${@} + ''; + + hasSpecialPrefix = elem (substring 0 1 ExecStart) [ "@" "-" ":" "+" "!" ]; + in assert !hasSpecialPrefix; pkgs.writeTextDir "etc/systemd/system/${n}.service.d/distributed.conf" '' + [Service] + ExecStart= + ExecStart=${consul}/bin/consul lock --name=${n} --n=${toString cfg.replicas} --shell=false --child-exit-code 'services/${n}%i' ${optionalString (cfg.registerService != null) runWithRegistration} ${ExecStart} + ${optionalString (v.serviceConfig ? RestrictAddressFamilies) "RestrictAddressFamilies=AF_NETLINK"} + ${optionalString (cfg.registerService != null) "ExecStopPost=${svc.commands.deregister}"} + '')) + ]; +} diff --git a/modules/part.nix b/modules/part.nix index 311c1c5..00159ad 100644 --- a/modules/part.nix +++ b/modules/part.nix @@ -7,6 +7,7 @@ in { flake.nixosModules = with config.flake.nixosModules; { autopatch = ./autopatch; + consul-distributed-services = ./consul-distributed-services; consul-service-registry = ./consul-service-registry; deploy-rs-receiver = ./deploy-rs-receiver; effect-receiver = ./effect-receiver; @@ -44,6 +45,7 @@ in serverBase = group [ machineBase + consul-distributed-services consul-service-registry deploy-rs-receiver effect-receiver