diff --git a/doc/manual/rl-next/move-nixdaemon-cache-dirs.md b/doc/manual/rl-next/move-nixdaemon-cache-dirs.md new file mode 100644 index 000000000..b61eccdd0 --- /dev/null +++ b/doc/manual/rl-next/move-nixdaemon-cache-dirs.md @@ -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`. diff --git a/lix/libutil/users.cc b/lix/libutil/users.cc index bfb674210..ad763263c 100644 --- a/lix/libutil/users.cc +++ b/lix/libutil/users.cc @@ -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; } diff --git a/misc/systemd/nix-daemon.service.in b/misc/systemd/nix-daemon.service.in index 88d60ea7d..cf0cd7292 100644 --- a/misc/systemd/nix-daemon.service.in +++ b/misc/systemd/nix-daemon.service.in @@ -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