From ea515088b36a127e010ba0811c53eb2dc80927fc Mon Sep 17 00:00:00 2001 From: Astro Date: Sat, 27 Mar 2021 03:43:19 +0100 Subject: [PATCH] lxc-containers.nix: get working --- nix/nixos-module/server/lxc-containers.nix | 37 ++++++++++++++++++---- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/nix/nixos-module/server/lxc-containers.nix b/nix/nixos-module/server/lxc-containers.nix index 6a09be0..affc7bf 100644 --- a/nix/nixos-module/server/lxc-containers.nix +++ b/nix/nixos-module/server/lxc-containers.nix @@ -124,35 +124,58 @@ in } (builtins.attrNames containers); systemd.services."lxc-rootfs@" = { - description = "Build a NixOS rootfs for LXC container '%i'"; + description = "rootfs for '%i'"; wants = [ "nix-daemon.service" ]; path = [ config.nix.package pkgs.util-linux pkgs.git ]; scriptArgs = "%i"; script = '' mkdir -p /var/lib/lxc/$1 - flock /tmp/lxc-rootfs-build.lock -c \ + [ ! -e /var/lib/lxc/$1/rootfs ] && + flock /tmp/lxc-rootfs-build.lock -c \ "nix build -o /var/lib/lxc/$1/rootfs zentralwerk-network#$1-rootfs" + exit 0 ''; - unitConfig.ConditionPathExists = "!/var/lib/lxc/%i/rootfs"; serviceConfig.Type = "oneshot"; }; + systemd.services."lxc@" = { description = "LXC container '%i'"; wants = [ "systemd-networkd.service" ]; requires = [ "lxc-rootfs@%i.service" ]; - unitConfig.ConditionPathExists = "/var/lib/lxc/%i/rootfs"; + after = [ "lxc-rootfs@%i.service" ]; serviceConfig = { Type = "simple"; - ExecStart = "${pkgs.lxc}/bin/lxc-start -F -C -n %i"; + ExecStart = + let + script = pkgs.writeScript "start-lxc-container.sh" '' + #! ${pkgs.stdenv.shell} -e + + [ -e /var/lib/lxc/$1/rootfs ] + exec ${pkgs.lxc}/bin/lxc-start -F -C -n $1 + ''; + in + "${script} %i"; ExecStop = "${pkgs.lxc}/bin/lxc-stop -n %i"; + ExecReload = + let + script = pkgs.writeScript "reload-lxc-container.sh" '' + #! ${pkgs.stdenv.shell} -e + + SYSTEM=$(dirname $(readlink $(readlink /var/lib/lxc/$1/rootfs)/init)) + exec ${pkgs.lxc}/bin/lxc-attach -n $1 $SYSTEM/activate + ''; + in + "${script} %i"; KillMode = "mixed"; OOMPolicy = "kill"; Restart = "always"; - RestartSec = "5s"; + RestartSec = "30s"; }; }; + systemd.targets.lxc-containers = { wantedBy = [ "multi-user.target" ]; - wants = map (ctName: "lxc@${ctName}.service") (builtins.attrNames containers); + wants = map (ctName: "lxc@${ctName}.service") + (builtins.attrNames containers); }; }