nixos-modules/server/lxc-containers.nix: build rootfs before starting container

This commit is contained in:
Astro 2021-03-27 00:28:03 +01:00
parent 1a9037dda6
commit 37dd4550bb
1 changed files with 20 additions and 7 deletions

View File

@ -74,9 +74,6 @@ in
environment.etc =
builtins.foldl' (etc: ctName: etc // {
"lxc/containers/${ctName}/rootfs" = {
source = self.packages.x86_64-linux."${ctName}-rootfs";
};
"lxc/containers/${ctName}/config" = {
enable = true;
source =
@ -89,7 +86,7 @@ in
lxc.uts.name = ${ctName}
# Handled by lxc@.service
lxc.start.auto = 0
lxc.rootfs.path = /etc/lxc/containers/${ctName}/rootfs
lxc.rootfs.path = /var/lib/lxc/${ctName}/rootfs
lxc.init.cmd = "/init"
lxc.mount.entry = /nix/store nix/store none bind,ro 0 0
@ -98,6 +95,7 @@ in
#lxc.mount.entry = none dev tmpfs defaults 0 0
lxc.mount.entry = none root tmpfs defaults 0 0
lxc.mount.entry = none tmp tmpfs defaults 0 0
# TODO: make non-ephemeral
lxc.mount.entry = none var tmpfs defaults 0 0
lxc.mount.entry = none home tmpfs defaults 0 0
lxc.mount.entry = none usr tmpfs defaults 0 0
@ -125,13 +123,24 @@ in
"lxc/common.conf".source = "${pkgs.lxc}/share/lxc/config/common.conf";
} (builtins.attrNames containers);
systemd.targets.lxc-containers = {
wantedBy = [ "multi-user.target" ];
wants = map (ctName: "lxc@${ctName}.service") (builtins.attrNames containers);
systemd.services."lxc-rootfs@" = {
description = "Build a NixOS rootfs for LXC container '%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 \
"nix build -o /var/lib/lxc/$1/rootfs zentralwerk-network#$1-rootfs"
'';
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";
serviceConfig = {
Type = "simple";
ExecStart = "${pkgs.lxc}/bin/lxc-start -F -C -n %i";
@ -142,4 +151,8 @@ in
RestartSec = "5s";
};
};
systemd.targets.lxc-containers = {
wantedBy = [ "multi-user.target" ];
wants = map (ctName: "lxc@${ctName}.service") (builtins.attrNames containers);
};
}