summary refs log tree commit diff
path: root/nixos/modules/virtualisation/containers.nix
blob: 6a4833e1e21550d9164e5e7da6ef645ed7fb1162 (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
{ config, pkgs, ... }:

with pkgs.lib;

{
  options = {

    boot.isContainer = mkOption {
      type = types.bool;
      default = false;
      description = ''
        Whether this NixOS machine is a lightweight container running
        in another NixOS system.
      '';
    };

    systemd.containers = mkOption {
      type = types.attrsOf (types.submodule (
        { config, options, name, ... }:
        {
          options = {

            root = mkOption {
              type = types.path;
              description = ''
                The root directory of the container.
              '';
            };

            config = mkOption {
              description = ''
                A specification of the desired configuration of this
                container, as a NixOS module.
              '';
            };

            path = mkOption {
              type = types.path;
              example = "/nix/var/nix/profiles/containers/webserver";
              description = ''
                As an alternative to specifying
                <option>config</option>, you can specify the path to
                the evaluated NixOS system configuration, typically a
                symlink to a system profile.
              '';
            };

          };

          config = mkMerge
            [ { root = mkDefault "/var/lib/containers/${name}";
              }
              (mkIf options.config.isDefined {
                path = (import ../../lib/eval-config.nix {
                  modules =
                    let extraConfig =
                      { boot.isContainer = true;
                        security.initialRootPassword = mkDefault "!";
                        networking.hostName = mkDefault name;
                        imports = [ ./container-login.nix ];
                      };
                    in [ extraConfig config.config ];
                  prefix = [ "systemd" "containers" name ];
                }).config.system.build.toplevel;
              })
            ];
        }));

      default = {};
      example = literalExample
        ''
          { webserver =
              { root = "/containers/webserver";
                path = "/nix/var/nix/profiles/webserver";
              };
            database =
              { root = "/containers/database";
                config =
                  { config, pkgs, ... }:
                  { services.postgresql.enable = true;
                    services.postgresql.package = pkgs.postgresql92;
                  };
              };
          }
        '';
      description = ''
        A set of NixOS system configurations to be run as lightweight
        containers.  Each container appears as a service
        <literal>container-<replaceable>name</replaceable></literal>
        on the host system, allowing it to be started and stopped via
        <command>systemctl</command> .
      '';
    };

  };


  config = {

    systemd.services = mapAttrs' (name: container: nameValuePair "container-${name}"
      { description = "Container '${name}'";

        wantedBy = [ "multi-user.target" ];

        unitConfig.RequiresMountsFor = [ container.root ];

        preStart =
          ''
            mkdir -p -m 0755 ${container.root}/etc
            if ! [ -e ${container.root}/etc/os-release ]; then
              touch ${container.root}/etc/os-release
            fi

            mkdir -p -m 0755 \
              /nix/var/nix/profiles/per-container/${name} \
              /nix/var/nix/gcroots/per-container/${name}
          '';

        serviceConfig.ExecStart =
          "${config.systemd.package}/bin/systemd-nspawn"
          + " -M ${name} -D ${container.root}"
          + " --bind-ro=/nix/store --bind-ro=/nix/var/nix/db --bind-ro=/nix/var/nix/daemon-socket"
          + " --bind=/nix/var/nix/profiles/per-container/${name}:/nix/var/nix/profiles"
          + " --bind=/nix/var/nix/gcroots/per-container/${name}:/nix/var/nix/gcroots"
          + " ${container.path}/init";

        preStop =
          ''
            pid="$(cat /sys/fs/cgroup/systemd/machine/${name}.nspawn/system/tasks 2> /dev/null)"
            if [ -n "$pid" ]; then
              # Send the RTMIN+3 signal, which causes the container
              # systemd to start halt.target.
              echo "killing container systemd, PID = $pid"
              kill -RTMIN+3 $pid
              # Wait for the container to exit.  We can't let systemd
              # do this because it will send a signal to the entire
              # cgroup.
              for ((n = 0; n < 180; n++)); do
                if ! kill -0 $pid 2> /dev/null; then break; fi
                sleep 1
              done
            fi
          '';

        reloadIfChanged = true;

        serviceConfig.ExecReload =
          "${pkgs.bash}/bin/bash -c '"
          + "echo ${container.path}/bin/switch-to-configuration test "
          + "| ${pkgs.socat}/bin/socat unix:${container.root}/var/lib/root-shell.socket -'";

      }) config.systemd.containers;

  };
}