1
0

GRE Tunnel to systemd service unit

This commit is contained in:
clerie 2021-01-02 16:52:45 +01:00
parent ddb41ac8cd
commit fb45cc60e9

View File

@ -5,6 +5,35 @@ with lib;
let let
cfg = config.clerie.gre-tunnel; cfg = config.clerie.gre-tunnel;
generateInterfaceUnit = isIPv6: name: tunnel:
nameValuePair "gre-tunnel-${name}" {
description = "GRE Tunnel - ${name}";
requires = [ "network-online.target" ];
after = [ "network.target" "network-online.target" ];
wantedBy = [ "multi-user.target" ];
environment.DEVICE = name;
path = with pkgs; [ iproute ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
};
script = ''
${tunnel.preSetup}
ip${optionalString isIPv6 " -6"} tunnel add ${name} mode gre remote ${tunnel.remote} local ${tunnel.local}
ip link set ${name} up
ip${optionalString isIPv6 " -6"} a add ${tunnel.address} dev ${name}
${tunnel.postSetup}
'';
postStop = ''
ip link set ${name} down
ip tunnel del ${name}
${tunnel.postShutdown}
'';
};
checkOpts = { config, ... }@moduleAttrs: { checkOpts = { config, ... }@moduleAttrs: {
options = { options = {
remote = mkOption { remote = mkOption {
@ -16,6 +45,18 @@ let
address = mkOption { address = mkOption {
type = types.str; type = types.str;
}; };
preSetup = mkOption {
type = types.str;
default = "";
};
postSetup = mkOption {
type = types.str;
default = "";
};
postShutdown = mkOption {
type = types.str;
default = "";
};
}; };
}; };
@ -25,28 +66,18 @@ in {
enable = mkEnableOption "Declarative Policy-Routing"; enable = mkEnableOption "Declarative Policy-Routing";
ipv6 = mkOption { ipv6 = mkOption {
type = with types; attrsOf (submodule checkOpts); type = with types; attrsOf (submodule checkOpts);
default = {};
}; };
ipv4 = mkOption { ipv4 = mkOption {
type = with types; attrsOf (submodule checkOpts); type = with types; attrsOf (submodule checkOpts);
default = {};
}; };
}; };
}; };
config = mkIf cfg.enable { config = mkIf cfg.enable {
clerie.gre-tunnel.rules = [ systemd.services =
{ rule = "lookup main"; prio = 32000; } (mapAttrsToList (generateInterfaceUnit false) cfg.ipv4)
]; ++ (mapAttrsToList (generateInterfaceUnit true) cfg.ipv6);
networking.localCommands = ''
${concatMapStringsSep "\n" ( mapAttrsToList ( name: tunnel: ''
ip -6 tunnel add ${name} mode gre remote ${tunnel.remote} local ${tunnel.local}
ip link set ${name} up
ip -6 a add ${tunnel.address} dev ${name}
'') cfg.ipv6 ) }
${concatMapStringsSep "\n" ( mapAttrsToList ( name: tunnel: ''
ip -4 tunnel add ${name} mode gre remote ${tunnel.remote} local ${tunnel.local}
ip link set ${name} up
ip -4 a add ${tunnel.address} dev ${name}
'') cfg.ipv4 ) }
'';
}; };
} }