fork/home-manager

git clone https://git.julia.blue/fork/home-manager

Robert HelgessonMerge PR #421575790441

master
8.9 KiB283 linesraw
1{ config, lib, pkgs, ... }:
2
3let
4
5  cfg = config.systemd.user;
6
7  inherit (lib) getAttr hm isBool literalExpression mkIf mkMerge mkOption types;
8
9  # From <nixpkgs/nixos/modules/system/boot/systemd-lib.nix>
10  mkPathSafeName =
11    lib.replaceStrings [ "@" ":" "\\" "[" "]" ] [ "-" "-" "-" "" "" ];
12
13  toSystemdIni = lib.generators.toINI {
14    listsAsDuplicateKeys = true;
15    mkKeyValue = key: value:
16      let
17        value' = if isBool value then
18          (if value then "true" else "false")
19        else
20          toString value;
21      in "${key}=${value'}";
22  };
23
24  buildService = style: name: serviceCfg:
25    let
26      filename = "${name}.${style}";
27      pathSafeName = mkPathSafeName filename;
28
29      # Needed because systemd derives unit names from the ultimate
30      # link target.
31      source = pkgs.writeTextFile {
32        name = pathSafeName;
33        text = toSystemdIni serviceCfg;
34        destination = "/${filename}";
35      } + "/${filename}";
36
37      install = variant: target: {
38        name = "systemd/user/${target}.${variant}/${filename}";
39        value = { inherit source; };
40      };
41    in lib.singleton {
42      name = "systemd/user/${filename}";
43      value = { inherit source; };
44    } ++ map (install "wants") (serviceCfg.Install.WantedBy or [ ])
45    ++ map (install "requires") (serviceCfg.Install.RequiredBy or [ ]);
46
47  buildServices = style: serviceCfgs:
48    lib.concatLists (lib.mapAttrsToList (buildService style) serviceCfgs);
49
50  servicesStartTimeoutMs = builtins.toString cfg.servicesStartTimeoutMs;
51
52  unitType = unitKind:
53    with types;
54    let primitive = oneOf [ bool int str path ];
55    in attrsOf (attrsOf (attrsOf (either primitive (listOf primitive)))) // {
56      description = "systemd ${unitKind} unit configuration";
57    };
58
59  unitDescription = type: ''
60    Definition of systemd per-user ${type} units. Attributes are
61    merged recursively.
62
63    Note that the attributes follow the capitalization and naming used
64    by systemd. More details can be found in
65    {manpage}`systemd.${type}(5)`.
66  '';
67
68  unitExample = type:
69    literalExpression ''
70      {
71        ${lib.toLower type}-name = {
72          Unit = {
73            Description = "Example description";
74            Documentation = [ "man:example(1)" "man:example(5)" ];
75          };
76
77          ${type} = {
78            …
79          };
80        };
81      };
82    '';
83
84  sessionVariables = mkIf (cfg.sessionVariables != { }) {
85    "environment.d/10-home-manager.conf".text = lib.concatStringsSep "\n"
86      (lib.mapAttrsToList (n: v: "${n}=${toString v}") cfg.sessionVariables)
87      + "\n";
88  };
89
90in {
91  meta.maintainers = [ lib.maintainers.rycee ];
92
93  options = {
94    systemd.user = {
95      systemctlPath = mkOption {
96        default = "${pkgs.systemd}/bin/systemctl";
97        defaultText = literalExpression ''"''${pkgs.systemd}/bin/systemctl"'';
98        type = types.str;
99        description = ''
100          Absolute path to the {command}`systemctl` tool. This
101          option may need to be set if running Home Manager on a
102          non-NixOS distribution.
103        '';
104      };
105
106      services = mkOption {
107        default = { };
108        type = unitType "service";
109        description = (unitDescription "service");
110        example = unitExample "Service";
111      };
112
113      slices = mkOption {
114        default = { };
115        type = unitType "slice";
116        description = (unitDescription "slice");
117        example = unitExample "Slice";
118      };
119
120      sockets = mkOption {
121        default = { };
122        type = unitType "socket";
123        description = (unitDescription "socket");
124        example = unitExample "Socket";
125      };
126
127      targets = mkOption {
128        default = { };
129        type = unitType "target";
130        description = (unitDescription "target");
131        example = unitExample "Target";
132      };
133
134      timers = mkOption {
135        default = { };
136        type = unitType "timer";
137        description = (unitDescription "timer");
138        example = unitExample "Timer";
139      };
140
141      paths = mkOption {
142        default = { };
143        type = unitType "path";
144        description = (unitDescription "path");
145        example = unitExample "Path";
146      };
147
148      mounts = mkOption {
149        default = { };
150        type = unitType "mount";
151        description = (unitDescription "mount");
152        example = unitExample "Mount";
153      };
154
155      automounts = mkOption {
156        default = { };
157        type = unitType "automount";
158        description = (unitDescription "automount");
159        example = unitExample "Automount";
160      };
161
162      startServices = mkOption {
163        default = "suggest";
164        type = with types;
165          either bool (enum [ "suggest" "legacy" "sd-switch" ]);
166        apply = p: if isBool p then if p then "legacy" else "suggest" else p;
167        description = ''
168          Whether new or changed services that are wanted by active targets
169          should be started. Additionally, stop obsolete services from the
170          previous generation.
171
172          The alternatives are
173
174          `suggest` (or `false`)
175          : Use a very simple shell script to print suggested
176            {command}`systemctl` commands to run. You will have to
177            manually run those commands after the switch.
178
179          `legacy` (or `true`)
180          : Use a Ruby script to, in a more robust fashion, determine the
181            necessary changes and automatically run the
182            {command}`systemctl` commands.
183
184          `sd-switch`
185          : Use sd-switch, a third party application, to perform the service
186            updates. This tool offers more features while having a small
187            closure size. Note, it requires a fully functional user D-Bus
188            session. Once tested and deemed sufficiently robust, this will
189            become the default.
190        '';
191      };
192
193      servicesStartTimeoutMs = mkOption {
194        default = 0;
195        type = types.ints.unsigned;
196        description = ''
197          How long to wait for started services to fail until their start is
198          considered successful. The value 0 indicates no timeout.
199        '';
200      };
201
202      sessionVariables = mkOption {
203        default = { };
204        type = with types; attrsOf (either int str);
205        example = { EDITOR = "vim"; };
206        description = ''
207          Environment variables that will be set for the user session.
208          The variable values must be as described in
209          {manpage}`environment.d(5)`.
210        '';
211      };
212    };
213  };
214
215  # If we run under a Linux system we assume that systemd is
216  # available, in particular we assume that systemctl is in PATH.
217  # Do not install any user services if username is root.
218  config = mkIf (pkgs.stdenv.isLinux && config.home.username != "root") {
219    xdg.configFile = mkMerge [
220      (lib.listToAttrs ((buildServices "service" cfg.services)
221        ++ (buildServices "slice" cfg.slices)
222        ++ (buildServices "socket" cfg.sockets)
223        ++ (buildServices "target" cfg.targets)
224        ++ (buildServices "timer" cfg.timers)
225        ++ (buildServices "path" cfg.paths)
226        ++ (buildServices "mount" cfg.mounts)
227        ++ (buildServices "automount" cfg.automounts)))
228
229      sessionVariables
230    ];
231
232    # Run systemd service reload if user is logged in. If we're
233    # running this from the NixOS module then XDG_RUNTIME_DIR is not
234    # set and systemd commands will fail. We'll therefore have to
235    # set it ourselves in that case.
236    home.activation.reloadSystemd = hm.dag.entryAfter [ "linkGeneration" ] (let
237      cmd = {
238        suggest = ''
239          PATH=${dirOf cfg.systemctlPath}:$PATH \
240          bash ${./systemd-activate.sh} "''${oldGenPath=}" "$newGenPath"
241        '';
242        legacy = ''
243          PATH=${dirOf cfg.systemctlPath}:$PATH \
244          ${pkgs.ruby}/bin/ruby ${./systemd-activate.rb} \
245            "''${oldGenPath=}" "$newGenPath" "${servicesStartTimeoutMs}"
246        '';
247        sd-switch = let
248          timeoutArg = if cfg.servicesStartTimeoutMs != 0 then
249            "--timeout " + servicesStartTimeoutMs
250          else
251            "";
252        in ''
253          ${pkgs.sd-switch}/bin/sd-switch \
254            ''${DRY_RUN:+--dry-run} $VERBOSE_ARG ${timeoutArg} \
255            ''${oldGenPath:+--old-units $oldGenPath/home-files/.config/systemd/user} \
256            --new-units $newGenPath/home-files/.config/systemd/user
257        '';
258      };
259
260      ensureRuntimeDir =
261        "XDG_RUNTIME_DIR=\${XDG_RUNTIME_DIR:-/run/user/$(id -u)}";
262
263      systemctl = "${ensureRuntimeDir} ${cfg.systemctlPath}";
264    in ''
265      systemdStatus=$(${systemctl} --user is-system-running 2>&1 || true)
266
267      if [[ $systemdStatus == 'running' || $systemdStatus == 'degraded' ]]; then
268        if [[ $systemdStatus == 'degraded' ]]; then
269          warnEcho "The user systemd session is degraded:"
270          ${systemctl} --user --no-pager --state=failed
271          warnEcho "Attempting to reload services anyway..."
272        fi
273
274        ${ensureRuntimeDir} \
275          ${getAttr cfg.startServices cmd}
276      else
277        echo "User systemd daemon not running. Skipping reload."
278      fi
279
280      unset systemdStatus
281    '');
282  };
283}