forked from nix-community/impermanence
-
Notifications
You must be signed in to change notification settings - Fork 0
/
home-manager.nix
474 lines (434 loc) · 17 KB
/
home-manager.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
{ pkgs, config, lib, ... }:
with lib;
let
enableCfg = config.home.impermanence.enable;
cfg = config.home.persistence;
persistentStorageNames = attrNames cfg;
getDirPath = v: if isString v then v else v.directory;
getDirMethod = v: v.method or "bindfs";
isBindfs = v: (getDirMethod v) == "bindfs";
isSymlink = v: (getDirMethod v) == "symlink";
inherit (pkgs.callPackage ./lib.nix { })
splitPath
dirListToPath
concatPaths
sanitizeName
;
mount = "${pkgs.util-linux}/bin/mount";
unmountScript = mountPoint: tries: sleep: ''
triesLeft=${toString tries}
if ${mount} | grep -F ${mountPoint}' ' >/dev/null; then
while (( triesLeft > 0 )); do
if fusermount -u ${mountPoint}; then
break
else
(( triesLeft-- ))
if (( triesLeft == 0 )); then
echo "Couldn't perform regular unmount of ${mountPoint}. Attempting lazy unmount."
fusermount -uz ${mountPoint}
else
sleep ${toString sleep}
fi
fi
done
fi
'';
in
{
options = {
home.impermanence.enable = mkOption {
type = types.bool;
description = ''
Whether to enable impermanence for home-manager.
'';
default = false;
};
home.persistence = mkOption {
default = { };
type = with types; attrsOf (
submodule ({ name, ... }: {
options =
{
persistentStoragePath = mkOption {
type = path;
default = name;
description = ''
The path to persistent storage where the real
files and directories should be stored.
'';
};
directories = mkOption {
type = with types; listOf (either str (submodule {
options = {
directory = mkOption {
type = str;
default = null;
description = "The directory path to be linked.";
};
method = mkOption {
type = types.enum [ "bindfs" "symlink" ];
default = "bindfs";
description = ''
The linking method that should be used for this
directory. bindfs is the default and works for most use
cases, however some programs may behave better with
symlinks.
'';
};
};
}));
default = [ ];
example = [
"Downloads"
"Music"
"Pictures"
"Documents"
"Videos"
"VirtualBox VMs"
".gnupg"
".ssh"
".local/share/keyrings"
".local/share/direnv"
{
directory = ".local/share/Steam";
method = "symlink";
}
];
description = ''
A list of directories in your home directory that
you want to link to persistent storage. You may optionally
specify the linking method each directory should use.
'';
};
files = mkOption {
type = with types; listOf str;
default = [ ];
example = [
".screenrc"
];
description = ''
A list of files in your home directory you want to
link to persistent storage.
'';
};
allowOther = mkOption {
type = with types; nullOr bool;
default = null;
example = true;
apply = x:
if x == null then
warn ''
home.persistence."${name}".allowOther not set; assuming 'false'.
See https://github.com/nix-community/impermanence#home-manager for more info.
''
false
else
x;
description = ''
Whether to allow other users, such as
<literal>root</literal>, access to files through the
bind mounted directories listed in
<literal>directories</literal>. Requires the NixOS
configuration parameter
<literal>programs.fuse.userAllowOther</literal> to
be <literal>true</literal>.
'';
};
removePrefixDirectory = mkOption {
type = types.bool;
default = false;
example = true;
description = ''
Note: This is mainly useful if you have a dotfiles
repo structured for use with GNU Stow; if you don't,
you can likely ignore it.
Whether to remove the first directory when linking
or mounting; e.g. for the path
<literal>"screen/.screenrc"</literal>, the
<literal>screen/</literal> is ignored for the path
linked to in your home directory.
'';
};
};
})
);
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 path relative to the user's
home directory.
For detailed usage, check the <link
xlink:href="https://github.com/nix-community/impermanence">documentation</link>.
'';
example = literalExpression ''
{
"/persistent/home/talyz" = {
directories = [
"Downloads"
"Music"
"Pictures"
"Documents"
"Videos"
"VirtualBox VMs"
".gnupg"
".ssh"
".nixops"
".local/share/keyrings"
".local/share/direnv"
{
directory = ".local/share/Steam";
method = "symlink";
}
];
files = [
".screenrc"
];
allowOther = true;
};
}
'';
};
};
config = lib.mkIf enableCfg {
home.file =
let
link = file:
pkgs.runCommand
"${sanitizeName file}"
{ }
"ln -s '${file}' $out";
mkLinkNameValuePair = persistentStorageName: fileOrDir: {
name =
if cfg.${persistentStorageName}.removePrefixDirectory then
dirListToPath (tail (splitPath [ fileOrDir ]))
else
fileOrDir;
value = { source = link (concatPaths [ cfg.${persistentStorageName}.persistentStoragePath fileOrDir ]); };
};
mkLinksToPersistentStorage = persistentStorageName:
listToAttrs (map
(mkLinkNameValuePair persistentStorageName)
(map getDirPath (cfg.${persistentStorageName}.files ++
(filter isSymlink cfg.${persistentStorageName}.directories)))
);
in
foldl' recursiveUpdate { } (map mkLinksToPersistentStorage persistentStorageNames);
systemd.user.services =
let
mkBindMountService = persistentStorageName: dir:
let
mountDir =
if cfg.${persistentStorageName}.removePrefixDirectory then
dirListToPath (tail (splitPath [ dir ]))
else
dir;
targetDir = escapeShellArg (concatPaths [ cfg.${persistentStorageName}.persistentStoragePath dir ]);
mountPoint = escapeShellArg (concatPaths [ config.home.homeDirectory mountDir ]);
name = "bindMount-${sanitizeName targetDir}";
bindfsOptions = concatStringsSep "," (
optional (!cfg.${persistentStorageName}.allowOther) "no-allow-other"
++ optional (versionAtLeast pkgs.bindfs.version "1.14.9") "fsname=${targetDir}"
);
bindfsOptionFlag = optionalString (bindfsOptions != "") (" -o " + bindfsOptions);
bindfs = "bindfs" + bindfsOptionFlag;
startScript = pkgs.writeShellScript name ''
set -eu
if ! mount | grep -F ${mountPoint}' ' && ! mount | grep -F ${mountPoint}/; then
mkdir -p ${mountPoint}
exec ${bindfs} ${targetDir} ${mountPoint}
else
echo "There is already an active mount at or below ${mountPoint}!" >&2
exit 1
fi
'';
stopScript = pkgs.writeShellScript "unmount-${name}" ''
set -eu
${unmountScript mountPoint 6 5}
'';
in
{
inherit name;
value = {
Unit = {
Description = "Bind mount ${targetDir} at ${mountPoint}";
# Don't restart the unit, it could corrupt data and
# crash programs currently reading from the mount.
X-RestartIfChanged = false;
# Don't add an implicit After=basic.target.
DefaultDependencies = false;
Before = [
"bluetooth.target"
"basic.target"
"default.target"
"paths.target"
"sockets.target"
"timers.target"
];
};
Install.WantedBy = [ "paths.target" ];
Service = {
Type = "forking";
ExecStart = "${startScript}";
ExecStop = "${stopScript}";
Environment = "PATH=${makeBinPath [ pkgs.coreutils pkgs.util-linux pkgs.gnugrep pkgs.bindfs ]}:/run/wrappers/bin";
};
};
};
mkBindMountServicesForPath = persistentStorageName:
listToAttrs (map
(mkBindMountService persistentStorageName)
(map getDirPath (filter isBindfs cfg.${persistentStorageName}.directories))
);
in
builtins.foldl'
recursiveUpdate
{ }
(map mkBindMountServicesForPath persistentStorageNames);
home.activation =
let
dag = config.lib.dag;
mount = "${pkgs.util-linux}/bin/mount";
# The name of the activation script entry responsible for
# reloading systemd user services. The name was initially
# `reloadSystemD` but has been changed to `reloadSystemd`.
reloadSystemd =
if config.home.activation ? reloadSystemD then
"reloadSystemD"
else
"reloadSystemd";
mkBindMount = persistentStorageName: dir:
let
mountDir =
if cfg.${persistentStorageName}.removePrefixDirectory then
dirListToPath (tail (splitPath [ dir ]))
else
dir;
targetDir = escapeShellArg (concatPaths [ cfg.${persistentStorageName}.persistentStoragePath dir ]);
mountPoint = escapeShellArg (concatPaths [ config.home.homeDirectory mountDir ]);
bindfsOptions = concatStringsSep "," (
optional (!cfg.${persistentStorageName}.allowOther) "no-allow-other"
++ optional (versionAtLeast pkgs.bindfs.version "1.14.9") "fsname=${targetDir}"
);
bindfsOptionFlag = optionalString (bindfsOptions != "") (" -o " + bindfsOptions);
bindfs = "${pkgs.bindfs}/bin/bindfs" + bindfsOptionFlag;
systemctl = "XDG_RUNTIME_DIR=\${XDG_RUNTIME_DIR:-/run/user/$(id -u)} ${config.systemd.user.systemctlPath}";
in
''
mkdir -p ${targetDir}
mkdir -p ${mountPoint}
if ${mount} | grep -F ${mountPoint}' ' >/dev/null; then
if ! ${mount} | grep -F ${mountPoint}' ' | grep -F bindfs; then
if ! ${mount} | grep -F ${mountPoint}' ' | grep -F ${targetDir}' ' >/dev/null; then
# The target directory changed, so we need to remount
echo "remounting ${mountPoint}"
${systemctl} --user stop bindMount-${sanitizeName targetDir}
${bindfs} ${targetDir} ${mountPoint}
mountedPaths[${mountPoint}]=1
fi
fi
elif ${mount} | grep -F ${mountPoint}/ >/dev/null; then
echo "Something is mounted below ${mountPoint}, not creating bind mount to ${targetDir}" >&2
else
${bindfs} ${targetDir} ${mountPoint}
mountedPaths[${mountPoint}]=1
fi
'';
mkBindMountsForPath = persistentStorageName:
concatMapStrings
(mkBindMount persistentStorageName)
(map getDirPath (filter isBindfs cfg.${persistentStorageName}.directories));
mkUnmount = persistentStorageName: dir:
let
mountDir =
if cfg.${persistentStorageName}.removePrefixDirectory then
dirListToPath (tail (splitPath [ dir ]))
else
dir;
mountPoint = escapeShellArg (concatPaths [ config.home.homeDirectory mountDir ]);
in
''
if [[ -n ''${mountedPaths[${mountPoint}]+x} ]]; then
${unmountScript mountPoint 3 1}
fi
'';
mkUnmountsForPath = persistentStorageName:
concatMapStrings
(mkUnmount persistentStorageName)
(map getDirPath (filter isBindfs cfg.${persistentStorageName}.directories));
mkLinkCleanup = persistentStorageName: dir:
let
mountDir =
if cfg.${persistentStorageName}.removePrefixDirectory then
dirListToPath (tail (splitPath [ dir ]))
else
dir;
mountPoint = escapeShellArg (concatPaths [ config.home.homeDirectory mountDir ]);
in
''
# Unmount if it's mounted. Ensures smooth transition: bindfs -> symlink
${unmountScript mountPoint 3 1}
# If it is a directory and it's empty
if [ -d ${mountPoint} ] && [ -z "$(ls -A ${mountPoint})" ]; then
echo "Removing empty directory ${mountPoint}"
rm -d ${mountPoint}
fi
'';
mkLinkCleanupForPath = persistentStorageName:
concatMapStrings
(mkLinkCleanup persistentStorageName)
(map getDirPath (filter isSymlink cfg.${persistentStorageName}.directories));
in
mkMerge [
(mkIf (any (path: (filter isSymlink cfg.${path}.directories) != [ ]) persistentStorageNames) {
# Clean up existing empty directories in the way of links
cleanEmptyLinkTargets =
dag.entryBefore
[ "checkLinkTargets" ]
''
${concatMapStrings mkLinkCleanupForPath persistentStorageNames}
'';
})
(mkIf (any (path: (filter isBindfs cfg.${path}.directories) != [ ]) persistentStorageNames) {
createAndMountPersistentStoragePaths =
dag.entryBefore
[ "writeBoundary" ]
''
declare -A mountedPaths
${(concatMapStrings mkBindMountsForPath persistentStorageNames)}
'';
unmountPersistentStoragePaths =
dag.entryBefore
[ "createAndMountPersistentStoragePaths" ]
''
PATH=$PATH:/run/wrappers/bin
unmountBindMounts() {
${concatMapStrings mkUnmountsForPath persistentStorageNames}
}
# Run the unmount function on error to clean up stray
# bind mounts
trap "unmountBindMounts" ERR
'';
runUnmountPersistentStoragePaths =
dag.entryBefore
[ reloadSystemd ]
''
unmountBindMounts
'';
})
(mkIf (any (path: (cfg.${path}.files != [ ]) || ((filter isSymlink cfg.${path}.directories) != [ ])) persistentStorageNames) {
createTargetFileDirectories =
dag.entryBefore
[ "writeBoundary" ]
(concatMapStrings
(persistentStorageName:
concatMapStrings
(targetFilePath: ''
mkdir -p ${escapeShellArg (concatPaths [ cfg.${persistentStorageName}.persistentStoragePath (dirOf targetFilePath) ])}
'')
(map getDirPath (cfg.${persistentStorageName}.files ++ (filter isSymlink cfg.${persistentStorageName}.directories))))
persistentStorageNames);
})
];
};
}