From 6e8fd7e77e7e06d6ae1a4315901dbda43d3311d1 Mon Sep 17 00:00:00 2001 From: Astro Date: Sun, 1 Dec 2019 04:13:26 +0100 Subject: [PATCH] lxc: progress --- lib/lxc/default.nix | 58 +++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 53 insertions(+), 5 deletions(-) diff --git a/lib/lxc/default.nix b/lib/lxc/default.nix index 6d704251..edd45566 100644 --- a/lib/lxc/default.nix +++ b/lib/lxc/default.nix @@ -3,9 +3,31 @@ with lib; let profilesDir = "/nix/var/nix/profiles/lxc"; - gcRoots = "/nix/var/nix/gcroots/lxc"; containers = config.lxc.containers; nixPath = config.nix.nixPath; + + toLxcConfig' = path: a: + if builtins.isString a + then "${path} = ${a}\n" + else if builtins.isInt a + then "${path} = ${toString a}\n" + else if builtins.isAttrs a + then lib.concatMapStrings (name: + let + path' = if path == "" + then name + else "${path}.${name}"; + in + toLxcConfig' path' (builtins.getAttr name a) + ) (builtins.attrNames a) + else if builtins.isList a + then lib.concatMapStrings (toLxcConfig' path) a + else throw "Invalid LXC config value"; + toLxcConfig = toLxcConfig' ""; + + lxc-rootfs = pkgs.runCommand "lxc-rootfs" {} '' + mkdir -p $out/share/lxc/rootfs/{dev,nix/store,proc,run,sys,tmp} + ''; in { options = with types; { lxc.containers = mkOption { @@ -15,6 +37,10 @@ in { }; config = mkIf (containers != {}) { + environment = { + systemPackages = [ pkgs.lxc pkgs.apparmor-parser lxc-rootfs ]; + pathsToLink = [ "/share/lxc" ]; + }; virtualisation.lxc = { enable = true; }; @@ -22,7 +48,28 @@ in { systemd.services = builtins.foldl' (services: name: let + systemDir = "/${profilesDir}/${name}/system"; + lxcDefaults = { + lxc = { + uts.name = name; + rootfs.path = "/run/current-system/sw/share/lxc/rootfs"; + mount.entry = [ + "${systemDir}/init /init none bind,ro 0 0" + "/nix/store /nix/store none bind,ro 0 0" + ]; + autodev = 1; + include = "/run/current-system/sw/share/lxc/config/common.conf"; + # TODO: userns? + # TODO: apparmor? + apparmor.profile = "generated"; + environment = "TERM=linux"; + }; + }; config = builtins.getAttr name containers; + lxcConfig = builtins.toFile "lxc-container-${name}.conf" + # TODO: better merging + (toLxcConfig (lxcDefaults // config.lxc)); + builder = { description = "Build NixOS for lxc container ${name}"; wants = [ "nix-daemon.socket" ]; @@ -38,7 +85,6 @@ in { script = '' mkdir -p ${profilesDir}/${name} - mkdir -p ${gcRoots}/${name} nix-env -p ${profilesDir}/${name}/system \ -I nixos-config=${config.nixos-config} \ @@ -48,12 +94,14 @@ in { }; starter = { description = "LXC container ${name}"; - requires = [ "lxc-container-${name}-builder" ]; - after = [ "lxc-container-${name}-builder" ]; + requires = [ "lxc-container-${name}-builder.service" ]; + after = [ "lxc-container-${name}-builder.service" ]; - path = with pkgs; [ lxc ]; + path = with pkgs; [ lxc apparmor-parser ]; script = '' + mkdir -p /var/lib/lxc/${name} + ln -fs ${lxcConfig} /var/lib/lxc/${name}/config lxc-start -F -n ${name} ''; };