summary refs log tree commit diff
path: root/nixos/modules/virtualisation/lxc-container.nix
blob: 55b285b69147abd4649cfef6438e05029ade6c00 (plain) (blame)
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
{ lib, config, pkgs, ... }:

with lib;

let
  templateSubmodule = { ... }: {
    options = {
      enable = mkEnableOption (lib.mdDoc "this template");

      target = mkOption {
        description = lib.mdDoc "Path in the container";
        type = types.path;
      };
      template = mkOption {
        description = lib.mdDoc ".tpl file for rendering the target";
        type = types.path;
      };
      when = mkOption {
        description = lib.mdDoc "Events which trigger a rewrite (create, copy)";
        type = types.listOf (types.str);
      };
      properties = mkOption {
        description = lib.mdDoc "Additional properties";
        type = types.attrs;
        default = {};
      };
    };
  };

  toYAML = name: data: pkgs.writeText name (generators.toYAML {} data);

  cfg = config.virtualisation.lxc;
  templates = if cfg.templates != {} then let
    list = mapAttrsToList (name: value: { inherit name; } // value)
      (filterAttrs (name: value: value.enable) cfg.templates);
  in
    {
      files = map (tpl: {
        source = tpl.template;
        target = "/templates/${tpl.name}.tpl";
      }) list;
      properties = listToAttrs (map (tpl: nameValuePair tpl.target {
        when = tpl.when;
        template = "${tpl.name}.tpl";
        properties = tpl.properties;
      }) list);
    }
  else { files = []; properties = {}; };

in
{
  imports = [
    ../installer/cd-dvd/channel.nix
    ../profiles/clone-config.nix
    ../profiles/minimal.nix
  ];

  options = {
    virtualisation.lxc = {
      templates = mkOption {
        description = lib.mdDoc "Templates for LXD";
        type = types.attrsOf (types.submodule (templateSubmodule));
        default = {};
        example = literalExpression ''
          {
            # create /etc/hostname on container creation. also requires networking.hostName = "" to be set
            "hostname" = {
              enable = true;
              target = "/etc/hostname";
              template = builtins.toFile "hostname.tpl" "{{ container.name }}";
              when = [ "create" ];
            };
            # create /etc/nixos/hostname.nix with a configuration for keeping the hostname applied
            "hostname-nix" = {
              enable = true;
              target = "/etc/nixos/hostname.nix";
              template = builtins.toFile "hostname-nix.tpl" "{ ... }: { networking.hostName = \"{{ container.name }}\"; }";
              # copy keeps the file updated when the container is changed
              when = [ "create" "copy" ];
            };
            # copy allow the user to specify a custom configuration.nix
            "configuration-nix" = {
              enable = true;
              target = "/etc/nixos/configuration.nix";
              template = builtins.toFile "configuration-nix" "{{ config_get(\"user.user-data\", properties.default) }}";
              when = [ "create" ];
            };
          };
        '';
      };

      privilegedContainer = mkOption {
        type = types.bool;
        default = false;
        description = lib.mdDoc ''
          Whether this LXC container will be running as a privileged container or not. If set to `true` then
          additional configuration will be applied to the `systemd` instance running within the container as
          recommended by [distrobuilder](https://linuxcontainers.org/distrobuilder/introduction/).
        '';
      };
    };
  };

  config = {
    boot.isContainer = true;
    boot.postBootCommands =
      ''
        # After booting, register the contents of the Nix store in the Nix
        # database.
        if [ -f /nix-path-registration ]; then
          ${config.nix.package.out}/bin/nix-store --load-db < /nix-path-registration &&
          rm /nix-path-registration
        fi

        # nixos-rebuild also requires a "system" profile
        ${config.nix.package.out}/bin/nix-env -p /nix/var/nix/profiles/system --set /run/current-system
      '';

    system.build.metadata = pkgs.callPackage ../../lib/make-system-tarball.nix {
      contents = [
        {
          source = toYAML "metadata.yaml" {
            architecture = builtins.elemAt (builtins.match "^([a-z0-9_]+).+" (toString pkgs.system)) 0;
            creation_date = 1;
            properties = {
              description = "${config.system.nixos.distroName} ${config.system.nixos.codeName} ${config.system.nixos.label} ${pkgs.system}";
              os = "${config.system.nixos.distroId}";
              release = "${config.system.nixos.codeName}";
            };
            templates = templates.properties;
          };
          target = "/metadata.yaml";
        }
      ] ++ templates.files;
    };

    # TODO: build rootfs as squashfs for faster unpack
    system.build.tarball = pkgs.callPackage ../../lib/make-system-tarball.nix {
      extraArgs = "--owner=0";

      storeContents = [
        {
          object = config.system.build.toplevel;
          symlink = "none";
        }
      ];

      contents = [
        {
          source = config.system.build.toplevel + "/init";
          target = "/sbin/init";
        }
        # Technically this is not required for lxc, but having also make this configuration work with systemd-nspawn.
        # Nixos will setup the same symlink after start.
        {
          source = config.system.build.toplevel + "/etc/os-release";
          target = "/etc/os-release";
        }
      ];

      extraCommands = "mkdir -p proc sys dev";
    };

    system.build.installBootLoader = pkgs.writeScript "install-lxd-sbin-init.sh" ''
      #!${pkgs.runtimeShell}
      ln -fs "$1/init" /sbin/init
    '';

    # Add the overrides from lxd distrobuilder
    # https://github.com/lxc/distrobuilder/blob/05978d0d5a72718154f1525c7d043e090ba7c3e0/distrobuilder/main.go#L630
    systemd.packages = [
      (pkgs.writeTextFile {
        name = "systemd-lxc-service-overrides";
        destination = "/etc/systemd/system/service.d/zzz-lxc-service.conf";
        text = ''
          [Service]
          ProcSubset=all
          ProtectProc=default
          ProtectControlGroups=no
          ProtectKernelTunables=no
          NoNewPrivileges=no
          LoadCredential=
        '' + optionalString cfg.privilegedContainer ''
          # Additional settings for privileged containers
          ProtectHome=no
          ProtectSystem=no
          PrivateDevices=no
          PrivateTmp=no
          ProtectKernelLogs=no
          ProtectKernelModules=no
          ReadWritePaths=
        '';
      })
    ];

    # Allow the user to login as root without password.
    users.users.root.initialHashedPassword = mkOverride 150 "";

    system.activationScripts.installInitScript = mkForce ''
      ln -fs $systemConfig/init /sbin/init
    '';

    # Some more help text.
    services.getty.helpLine =
      ''

        Log in as "root" with an empty password.
      '';

    # Containers should be light-weight, so start sshd on demand.
    services.openssh.enable = mkDefault true;
    services.openssh.startWhenNeeded = mkDefault true;

    # As this is intended as a standalone image, undo some of the minimal profile stuff
    environment.noXlibs = false;
    documentation.enable = true;
    documentation.nixos.enable = true;
    services.logrotate.enable = true;
  };
}