about summary refs log tree commit diff
path: root/nixpkgs/nixos/modules/system/etc/etc.nix
blob: 9f735364196c6f153598ff2070193a923ce7aae6 (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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# Management of static files in /etc.

{ config, lib, pkgs, ... }:

with lib;

let

  etc' = filter (f: f.enable) (attrValues config.environment.etc);

  etc = pkgs.runCommandLocal "etc" {
    # This is needed for the systemd module
    passthru.targets = map (x: x.target) etc';
  } /* sh */ ''
    set -euo pipefail

    makeEtcEntry() {
      src="$1"
      target="$2"
      mode="$3"
      user="$4"
      group="$5"

      if [[ "$src" = *'*'* ]]; then
        # If the source name contains '*', perform globbing.
        mkdir -p "$out/etc/$target"
        for fn in $src; do
            ln -s "$fn" "$out/etc/$target/"
        done
      else

        mkdir -p "$out/etc/$(dirname "$target")"
        if ! [ -e "$out/etc/$target" ]; then
          ln -s "$src" "$out/etc/$target"
        else
          echo "duplicate entry $target -> $src"
          if [ "$(readlink "$out/etc/$target")" != "$src" ]; then
            echo "mismatched duplicate entry $(readlink "$out/etc/$target") <-> $src"
            ret=1

            continue
          fi
        fi

        if [ "$mode" != symlink ]; then
          echo "$mode" > "$out/etc/$target.mode"
          echo "$user" > "$out/etc/$target.uid"
          echo "$group" > "$out/etc/$target.gid"
        fi
      fi
    }

    mkdir -p "$out/etc"
    ${concatMapStringsSep "\n" (etcEntry: escapeShellArgs [
      "makeEtcEntry"
      # Force local source paths to be added to the store
      "${etcEntry.source}"
      etcEntry.target
      etcEntry.mode
      etcEntry.user
      etcEntry.group
    ]) etc'}
  '';

  etcHardlinks = filter (f: f.mode != "symlink") etc';

  build-composefs-dump = pkgs.runCommand "build-composefs-dump.py"
    {
      buildInputs = [ pkgs.python3 ];
    } ''
    install ${./build-composefs-dump.py} $out
    patchShebangs --host $out
  '';

in

{

  imports = [ ../build.nix ];

  ###### interface

  options = {

    system.etc.overlay = {
      enable = mkOption {
        type = types.bool;
        default = false;
        description = lib.mdDoc ''
          Mount `/etc` as an overlayfs instead of generating it via a perl script.

          Note: This is currently experimental. Only enable this option if you're
          confident that you can recover your system if it breaks.
        '';
      };

      mutable = mkOption {
        type = types.bool;
        default = true;
        description = lib.mdDoc ''
          Whether to mount `/etc` mutably (i.e. read-write) or immutably (i.e. read-only).

          If this is false, only the immutable lowerdir is mounted. If it is
          true, a writable upperdir is mounted on top.
        '';
      };
    };

    environment.etc = mkOption {
      default = {};
      example = literalExpression ''
        { example-configuration-file =
            { source = "/nix/store/.../etc/dir/file.conf.example";
              mode = "0440";
            };
          "default/useradd".text = "GROUP=100 ...";
        }
      '';
      description = lib.mdDoc ''
        Set of files that have to be linked in {file}`/etc`.
      '';

      type = with types; attrsOf (submodule (
        { name, config, options, ... }:
        { options = {

            enable = mkOption {
              type = types.bool;
              default = true;
              description = lib.mdDoc ''
                Whether this /etc file should be generated.  This
                option allows specific /etc files to be disabled.
              '';
            };

            target = mkOption {
              type = types.str;
              description = lib.mdDoc ''
                Name of symlink (relative to
                {file}`/etc`).  Defaults to the attribute
                name.
              '';
            };

            text = mkOption {
              default = null;
              type = types.nullOr types.lines;
              description = lib.mdDoc "Text of the file.";
            };

            source = mkOption {
              type = types.path;
              description = lib.mdDoc "Path of the source file.";
            };

            mode = mkOption {
              type = types.str;
              default = "symlink";
              example = "0600";
              description = lib.mdDoc ''
                If set to something else than `symlink`,
                the file is copied instead of symlinked, with the given
                file mode.
              '';
            };

            uid = mkOption {
              default = 0;
              type = types.int;
              description = lib.mdDoc ''
                UID of created file. Only takes effect when the file is
                copied (that is, the mode is not 'symlink').
                '';
            };

            gid = mkOption {
              default = 0;
              type = types.int;
              description = lib.mdDoc ''
                GID of created file. Only takes effect when the file is
                copied (that is, the mode is not 'symlink').
              '';
            };

            user = mkOption {
              default = "+${toString config.uid}";
              type = types.str;
              description = lib.mdDoc ''
                User name of created file.
                Only takes effect when the file is copied (that is, the mode is not 'symlink').
                Changing this option takes precedence over `uid`.
              '';
            };

            group = mkOption {
              default = "+${toString config.gid}";
              type = types.str;
              description = lib.mdDoc ''
                Group name of created file.
                Only takes effect when the file is copied (that is, the mode is not 'symlink').
                Changing this option takes precedence over `gid`.
              '';
            };

          };

          config = {
            target = mkDefault name;
            source = mkIf (config.text != null) (
              let name' = "etc-" + lib.replaceStrings ["/"] ["-"] name;
              in mkDerivedConfig options.text (pkgs.writeText name')
            );
          };

        }));

    };

  };


  ###### implementation

  config = {

    system.build.etc = etc;
    system.build.etcActivationCommands = let
      etcOverlayOptions = lib.concatStringsSep "," ([
        "relatime"
        "redirect_dir=on"
        "metacopy=on"
      ] ++ lib.optionals config.system.etc.overlay.mutable [
        "upperdir=/.rw-etc/upper"
        "workdir=/.rw-etc/work"
      ]);
    in if config.system.etc.overlay.enable then ''
      # This script atomically remounts /etc when switching configuration. On a (re-)boot
      # this should not run because /etc is mounted via a systemd mount unit
      # instead. To a large extent this mimics what composefs does. Because
      # it's relatively simple, however, we avoid the composefs dependency.
      # Since this script is not idempotent, it should not run when etc hasn't
      # changed.
      if [[ ! $IN_NIXOS_SYSTEMD_STAGE1 ]] && [[ "${config.system.build.etc}/etc" != "$(readlink -f /run/current-system/etc)" ]]; then
        echo "remounting /etc..."

        tmpMetadataMount=$(mktemp --directory)
        mount --type erofs ${config.system.build.etcMetadataImage} $tmpMetadataMount

        # Mount the new /etc overlay to a temporary private mount.
        # This needs the indirection via a private bind mount because you
        # cannot move shared mounts.
        tmpEtcMount=$(mktemp --directory)
        mount --bind --make-private $tmpEtcMount $tmpEtcMount
        mount --type overlay overlay \
          --options lowerdir=$tmpMetadataMount::${config.system.build.etcBasedir},${etcOverlayOptions} \
          $tmpEtcMount

        # Move the new temporary /etc mount underneath the current /etc mount.
        #
        # This should eventually use util-linux to perform this move beneath,
        # however, this functionality is not yet in util-linux. See this
        # tracking issue: https://github.com/util-linux/util-linux/issues/2604
        ${pkgs.move-mount-beneath}/bin/move-mount --move --beneath $tmpEtcMount /etc

        # Unmount the top /etc mount to atomically reveal the new mount.
        umount /etc

      fi
    '' else ''
      # Set up the statically computed bits of /etc.
      echo "setting up /etc..."
      ${pkgs.perl.withPackages (p: [ p.FileSlurp ])}/bin/perl ${./setup-etc.pl} ${etc}/etc
    '';

    system.build.etcBasedir = pkgs.runCommandLocal "etc-lowerdir" { } ''
      set -euo pipefail

      makeEtcEntry() {
        src="$1"
        target="$2"

        mkdir -p "$out/$(dirname "$target")"
        cp "$src" "$out/$target"
      }

      mkdir -p "$out"
      ${concatMapStringsSep "\n" (etcEntry: escapeShellArgs [
        "makeEtcEntry"
        # Force local source paths to be added to the store
        "${etcEntry.source}"
        etcEntry.target
      ]) etcHardlinks}
    '';

    system.build.etcMetadataImage =
      let
        etcJson = pkgs.writeText "etc-json" (builtins.toJSON etc');
        etcDump = pkgs.runCommand "etc-dump" { } "${build-composefs-dump} ${etcJson} > $out";
      in
      pkgs.runCommand "etc-metadata.erofs" {
        nativeBuildInputs = [ pkgs.composefs pkgs.erofs-utils ];
      } ''
        mkcomposefs --from-file ${etcDump} $out
        fsck.erofs $out
      '';

  };

}