summaryrefslogtreecommitdiff
path: root/nixos/helpers.nix
blob: 0588cd6f90efbad55e6daf88bcfe203dd2307b4e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
let
  nixpkgs = import <nixpkgs> {};
in
{
  mkNginxConfig = name: ''
    access_log /var/log/nginx/${name}.access.log;
    error_log /var/log/nginx/${name}.error.log;
  '';

  joinWgNamespace = ns: cfg:
   nixpkgs.lib.attrsets.recursiveUpdate cfg {
    bindsTo = ["netns@${ns}.service"];
    after = ["wireguard-wg-${ns}.service"];
    unitConfig.JoinsNamespaceOf = "netns@${ns}.service";
    serviceConfig.NetworkNamespacePath = "/var/run/netns/${ns}";
  };

  mkPortProxy = service: ns: port: {
    description = "Forward to ${service} in network namespace ${ns}";
    requires = ["${service}.service"];
    after = ["${service}.service"];
    partOf = ["${service}.service"];
    serviceConfig = {
      Restart = "on-failure";
      TimeoutStopSec = 300;
    };
    wantedBy = ["multi-user.target"];
    script =
      let
        pkgs = nixpkgs.pkgs;
      in
      ''
        ${pkgs.iproute2}/bin/ip netns exec ${ns} ${pkgs.iproute2}/bin/ip link set dev lo up
        ${pkgs.socat}/bin/socat tcp-listen:${toString port},fork,reuseaddr exec:'${pkgs.iproute2}/bin/ip netns exec ${ns} ${pkgs.socat}/bin/socat STDIO "tcp-connect:localhost:${toString port}"',nofork
      '';
  };
}