libutil/users: support service cache directories

Nix daemon runs in a service context, usually with systemd.

If the Nix daemon unit adds `[Service] CacheDirectory=nix-daemon`, it should
successfully use `/var/cache/nix-daemon` automatically.

Instead, it uses `/root/.cache` right now, which is really bad.

By default, we add `[Service] CacheDirectory=nix` now which means that
caches are moved into `/var/cache/nix`.

Fixes #634.

Change-Id: I854b1045bfdce8f60110aea70bda1bf6657dfd7b
Signed-off-by: Raito Bezarius <raito@lix.systems>
This commit is contained in:
Raito Bezarius
2025-12-05 00:14:42 +01:00
parent 8f5bf1e905
commit 1e98c01912
3 changed files with 50 additions and 2 deletions
@@ -0,0 +1,31 @@
---
synopsis: "Move /root/.cache/nix to /var/cache/nix by default"
cls: [4671]
issues: [fj#634]
category: "Breaking Changes"
credits: [raito]
---
By default, Lix attempts to locate a cache directory for its operations (such
as the narinfo cache) by checking the value of `$XDG_CACHE_DIR`.
However, since the Nix daemon is a system service, using `$XDG_CACHE_DIR` is
not typical in this context.
To address this, systemd provides a better solution. Specifically, when
`CacheDirectory=` is set in the `[Service]` section of a systemd unit, it
automatically sets the `$CACHE_DIRECTORY` environment variable and systemd will
manage that cache directory for us.
Now, our systemd unit includes `CacheDirectory=nix`, which sets the
`$CACHE_DIRECTORY` and takes precedence over `$XDG_CACHE_DIR`.
If the daemon is run under user units, systemd will automatically set
`$XDG_CACHE_DIR`.
If neither of these variables is set, Lix falls back to its default behavior.
By default, Lix will try to find a cache directory for its various operations
(e.g. narinfo cache) by looking into `$XDG_CACHE_DIR`.
In summary, what was stored in `/root/.cache/nix` is now moved to
`/var/cache/nix/nix`.
+18 -2
View File
@@ -73,8 +73,24 @@ Path getHome()
Path getCacheDir()
{
auto cacheDir = getEnv("XDG_CACHE_HOME");
return cacheDir ? *cacheDir : getHome() + "/.cache";
// We follow systemd semantics here:
// https://www.freedesktop.org/software/systemd/man/latest/systemd.exec.html#RuntimeDirectory=
static auto cacheDir = [] {
auto userCacheDir = getEnv("XDG_CACHE_HOME");
auto serviceCacheDir = getEnv("CACHE_DIRECTORY");
if (serviceCacheDir) {
return *serviceCacheDir;
}
if (userCacheDir) {
return *userCacheDir;
}
return getHome() + "/.cache";
}();
return cacheDir;
}
+1
View File
@@ -8,6 +8,7 @@ ConditionPathIsReadWrite=@localstatedir@/nix/daemon-socket
[Service]
ExecStart=@@bindir@/nix-daemon nix-daemon --daemon
CacheDirectory=nix
KillMode=process
LimitNOFILE=1048576
TasksMax=1048576