forked from nix-community/impermanence
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nixos.nix
570 lines (543 loc) · 20.5 KB
/
nixos.nix
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
{ pkgs, config, lib, ... }:
let
inherit (lib) attrNames attrValues zipAttrsWith flatten mkOption
types foldl' unique noDepEntry concatMapStrings listToAttrs
escapeShellArg escapeShellArgs replaceStrings recursiveUpdate all
filter filterAttrs concatStringsSep concatMapStringsSep isString
catAttrs optional literalExpression;
inherit (pkgs.callPackage ./lib.nix { }) splitPath dirListToPath
concatPaths sanitizeName duplicates;
cfg = config.environment.persistence;
users = config.users.users;
allPersistentStoragePaths = { directories = [ ]; files = [ ]; users = [ ]; }
// (zipAttrsWith (_name: flatten) (attrValues cfg));
inherit (allPersistentStoragePaths) files directories;
mountFile = pkgs.runCommand "impermanence-mount-file" { } ''
cp ${./mount-file.bash} $out
patchShebangs $out
'';
in
{
options = {
environment.persistence = mkOption {
default = { };
type =
let
inherit (types) attrsOf bool listOf submodule path either str;
in
attrsOf (
submodule (
{ name, config, ... }:
let
persistentStoragePath = name;
defaultPerms = {
mode = "0755";
user = "root";
group = "root";
};
commonOpts = {
options = {
persistentStoragePath = mkOption {
type = path;
default = persistentStoragePath;
description = ''
The path to persistent storage where the real
file should be stored.
'';
};
};
};
dirPermsOpts = { user, group, mode }: {
user = mkOption {
type = str;
default = user;
description = ''
If the directory doesn't exist in persistent
storage it will be created and owned by the user
specified by this option.
'';
};
group = mkOption {
type = str;
default = group;
description = ''
If the directory doesn't exist in persistent
storage it will be created and owned by the
group specified by this option.
'';
};
mode = mkOption {
type = str;
default = mode;
example = "0700";
description = ''
If the directory doesn't exist in persistent
storage it will be created with the mode
specified by this option.
'';
};
};
fileOpts = perms: {
options = {
file = mkOption {
type = str;
description = ''
The path to the file.
'';
};
parentDirectory = dirPermsOpts perms;
};
};
dirOpts = perms: {
options = {
directory = mkOption {
type = str;
description = ''
The path to the directory.
'';
};
} // (dirPermsOpts perms);
};
rootFile = submodule [
commonOpts
(fileOpts defaultPerms)
];
rootDir = submodule [
commonOpts
(dirOpts defaultPerms)
];
in
{
options =
{
users = mkOption {
type = attrsOf (
submodule (
{ name, config, ... }:
let
userDefaultPerms = {
inherit (defaultPerms) mode;
user = name;
group = users.${userDefaultPerms.user}.group;
};
userFile = submodule [
commonOpts
(fileOpts userDefaultPerms)
];
userDir = submodule [
commonOpts
(dirOpts userDefaultPerms)
];
in
{
options =
{
# Needed because defining fileSystems
# based on values from users.users
# results in infinite recursion.
home = mkOption {
type = path;
default = "/home/${userDefaultPerms.user}";
defaultText = "/home/<username>";
description = ''
The user's home directory. Only
useful for users with a custom home
directory path.
Cannot currently be automatically
deduced due to a limitation in
nixpkgs.
'';
};
files = mkOption {
type = listOf (either str userFile);
default = [ ];
example = [
".screenrc"
];
description = ''
Files that should be stored in
persistent storage.
'';
apply =
map (file:
if isString file then
{
inherit persistentStoragePath;
file = concatPaths [ config.home file ];
parentDirectory = userDefaultPerms;
}
else
file // {
file = concatPaths [ config.home file.file ];
});
};
directories = mkOption {
type = listOf (either str userDir);
default = [ ];
example = [
"Downloads"
"Music"
"Pictures"
"Documents"
"Videos"
];
description = ''
Directories to bind mount to
persistent storage.
'';
apply =
map (directory:
if isString directory then
userDefaultPerms // {
directory = concatPaths [ config.home directory ];
inherit persistentStoragePath;
}
else
directory // {
directory = concatPaths [ config.home directory.directory ];
});
};
};
}
)
);
default = { };
description = ''
A set of user submodules listing the files and
directories to link to their respective user's
home directories.
Each attribute name should be the name of the
user.
For detailed usage, check the <link
xlink:href="https://github.com/nix-community/impermanence">documentation</link>.
'';
example = literalExpression ''
{
talyz = {
directories = [
"Downloads"
"Music"
"Pictures"
"Documents"
"Videos"
"VirtualBox VMs"
{ directory = ".gnupg"; mode = "0700"; }
{ directory = ".ssh"; mode = "0700"; }
{ directory = ".nixops"; mode = "0700"; }
{ directory = ".local/share/keyrings"; mode = "0700"; }
".local/share/direnv"
];
files = [
".screenrc"
];
};
}
'';
};
files = mkOption {
type = listOf (either str rootFile);
default = [ ];
example = [
"/etc/machine-id"
"/etc/nix/id_rsa"
];
description = ''
Files that should be stored in persistent storage.
'';
apply =
map (file:
if isString file then
{
inherit file persistentStoragePath;
parentDirectory = defaultPerms;
}
else
file);
};
directories = mkOption {
type = listOf (either str rootDir);
default = [ ];
example = [
"/var/log"
"/var/lib/bluetooth"
"/var/lib/systemd/coredump"
"/etc/NetworkManager/system-connections"
];
description = ''
Directories to bind mount to persistent storage.
'';
apply =
map (directory:
if isString directory then
defaultPerms // {
inherit directory persistentStoragePath;
}
else
directory);
};
hideMounts = mkOption {
type = bool;
default = false;
example = true;
description = ''
Whether to hide bind mounts from showing up as mounted drives.
'';
};
enableDebugging = mkOption {
type = bool;
default = false;
internal = true;
description = ''
Enable debug trace output when running
scripts. You only need to enable this if asked
to.
'';
};
};
config =
let
allUsers = zipAttrsWith (_name: flatten) (attrValues config.users);
in
{
files = allUsers.files or [ ];
directories = allUsers.directories or [ ];
};
}
)
);
description = ''
A set of persistent storage location submodules listing the
files and directories to link to their respective persistent
storage location.
Each attribute name should be the full path to a persistent
storage location.
For detailed usage, check the <link
xlink:href="https://github.com/nix-community/impermanence">documentation</link>.
'';
example = literalExpression ''
{
"/persistent" = {
directories = [
"/var/log"
"/var/lib/bluetooth"
"/var/lib/systemd/coredump"
"/etc/NetworkManager/system-connections"
{ directory = "/var/lib/colord"; user = "colord"; group = "colord"; mode = "u=rwx,g=rx,o="; }
];
files = [
"/etc/machine-id"
{ file = "/etc/nix/id_rsa"; parentDirectory = { mode = "u=rwx,g=,o="; }; }
];
};
users.talyz = { ... }; # See the dedicated example
}
'';
};
};
config = {
systemd.services =
let
mkPersistFileService = { file, persistentStoragePath, ... }:
let
targetFile = escapeShellArg (concatPaths [ persistentStoragePath file ]);
mountPoint = escapeShellArg file;
enableDebugging = escapeShellArg cfg.${persistentStoragePath}.enableDebugging;
in
{
"persist-${sanitizeName targetFile}" = {
description = "Bind mount or link ${targetFile} to ${mountPoint}";
wantedBy = [ "local-fs.target" ];
before = [ "local-fs.target" ];
path = [ pkgs.util-linux ];
unitConfig.DefaultDependencies = false;
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
ExecStart = "${mountFile} ${mountPoint} ${targetFile} ${enableDebugging}";
ExecStop = pkgs.writeShellScript "unbindOrUnlink-${sanitizeName targetFile}" ''
set -eu
if [[ -L ${mountPoint} ]]; then
rm ${mountPoint}
else
umount ${mountPoint}
rm ${mountPoint}
fi
'';
};
};
};
in
foldl' recursiveUpdate { } (map mkPersistFileService files);
fileSystems =
let
# Create fileSystems bind mount entry.
mkBindMountNameValuePair = { directory, persistentStoragePath, ... }: {
name = concatPaths [ "/" directory ];
value = {
device = concatPaths [ persistentStoragePath directory ];
noCheck = true;
options = [ "bind" ]
++ optional cfg.${persistentStoragePath}.hideMounts "x-gvfs-hide";
};
};
# Create all fileSystems bind mount entries for a specific
# persistent storage path.
in
listToAttrs (map mkBindMountNameValuePair directories);
system.activationScripts =
let
# Script to create directories in persistent and ephemeral
# storage. The directory structure's mode and ownership mirror
# those of persistentStoragePath/dir.
createDirectories = pkgs.runCommand "impermanence-create-directories" { } ''
cp ${./create-directories.bash} $out
patchShebangs $out
'';
mkDirWithPerms = { directory, persistentStoragePath, user, group, mode }:
let
args = [
persistentStoragePath
directory
user
group
mode
cfg.${persistentStoragePath}.enableDebugging
];
in
''
${createDirectories} ${escapeShellArgs args}
'';
# Build an activation script which creates all persistent
# storage directories we want to bind mount.
dirCreationScript =
let
inherit directories;
fileDirectories = unique (map
(f:
{
directory = dirOf f.file;
inherit (f) persistentStoragePath;
} // f.parentDirectory)
files);
in
pkgs.writeShellScript "impermanence-run-create-directories" ''
_status=0
trap "_status=1" ERR
${concatMapStrings mkDirWithPerms (directories ++ fileDirectories)}
exit $_status
'';
mkPersistFile = { file, persistentStoragePath, ... }:
let
mountPoint = file;
targetFile = concatPaths [ persistentStoragePath file ];
args = escapeShellArgs [
mountPoint
targetFile
cfg.${persistentStoragePath}.enableDebugging
];
in
''
${mountFile} ${args}
'';
persistFileScript =
pkgs.writeShellScript "impermanence-persist-files" ''
_status=0
trap "_status=1" ERR
${concatMapStrings mkPersistFile files}
exit $_status
'';
in
{
"createPersistentStorageDirs" = {
deps = [ "users" "groups" ];
text = "${dirCreationScript}";
};
"persist-files" = {
deps = [ "createPersistentStorageDirs" ];
text = "${persistFileScript}";
};
};
assertions =
let
markedNeededForBoot = cond: fs:
if config.fileSystems ? ${fs} then
config.fileSystems.${fs}.neededForBoot == cond
else
cond;
persistentStoragePaths = attrNames cfg;
usersPerPath = allPersistentStoragePaths.users;
homeDirOffenders =
filterAttrs
(n: v: (v.home != config.users.users.${n}.home));
in
[
{
# Assert that all persistent storage volumes we use are
# marked with neededForBoot.
assertion = all (markedNeededForBoot true) persistentStoragePaths;
message =
let
offenders = filter (markedNeededForBoot false) persistentStoragePaths;
in
''
environment.persistence:
All filesystems used for persistent storage must
have the flag neededForBoot set to true.
Please fix or remove the following paths:
${concatStringsSep "\n " offenders}
'';
}
{
assertion = all (users: (homeDirOffenders users) == { }) usersPerPath;
message =
let
offendersPerPath = filter (users: (homeDirOffenders users) != { }) usersPerPath;
offendersText =
concatMapStringsSep
"\n "
(offenders:
concatMapStringsSep
"\n "
(n: "${n}: ${offenders.${n}.home} != ${config.users.users.${n}.home}")
(attrNames offenders))
offendersPerPath;
in
''
environment.persistence:
Users and home doesn't match:
${offendersText}
You probably want to set each
environment.persistence.<path>.users.<user>.home to
match the respective user's home directory as
defined by users.users.<user>.home.
'';
}
{
assertion = duplicates (catAttrs "file" files) == [ ];
message =
let
offenders = duplicates (catAttrs "file" files);
in
''
environment.persistence:
The following files were specified two or more
times:
${concatStringsSep "\n " offenders}
'';
}
{
assertion = duplicates (catAttrs "directory" directories) == [ ];
message =
let
offenders = duplicates (catAttrs "directory" directories);
in
''
environment.persistence:
The following directories were specified two or more
times:
${concatStringsSep "\n " offenders}
'';
}
];
};
}