summaryrefslogtreecommitdiffstats
path: root/nixos/lib/systemd-lib.nix
blob: cc70216fccbd74bb74a820c7ead0f9f77ab7d23e (plain)
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
{
  config,
  lib,
  pkgs,
  utils,
}:

let
  inherit (lib)
    all
    attrByPath
    attrNames
    concatLists
    concatMap
    concatMapStrings
    concatStrings
    concatStringsSep
    const
    elem
    elemAt
    filter
    filterAttrs
    flatten
    flip
    hasPrefix
    head
    isInt
    isFloat
    isList
    isPath
    isString
    length
    makeBinPath
    makeSearchPathOutput
    mapAttrs
    mapAttrsToList
    mapNullable
    match
    mkAfter
    mkIf
    optional
    optionalAttrs
    optionalString
    pipe
    range
    replaceStrings
    reverseList
    splitString
    stringLength
    stringToCharacters
    tail
    toIntBase10
    trace
    types
    ;

  inherit (lib.strings) toJSON;

  cfg = config.systemd;
  lndir = "${pkgs.buildPackages.lndir}/bin/lndir";
  systemd = cfg.package;
in
rec {

  shellEscape = s: (replaceStrings [ "\\" ] [ "\\\\" ] s);

  mkPathSafeName = replaceStrings [ "@" ":" "\\" "[" "]" ] [ "-" "-" "-" "" "" ];

  # a type for options that take a unit name
  # note: redundantly escaping backslash in the bracket expression makes the regex
  # slightly more portable even though POSIX doesn't require it.
  unitNameType = types.strMatching "[a-zA-Z0-9@%:_.\\\\-]+[.](service|socket|device|mount|automount|swap|target|path|timer|scope|slice)";

  makeUnit =
    name: unit:
    if unit.enable then
      pkgs.runCommand "unit-${mkPathSafeName name}"
        {
          preferLocalBuild = true;
          allowSubstitutes = false;
          text = unit.text or "";
          __structuredAttrs = true;
        }
        ''
          name=${shellEscape name}
          mkdir -p "$out/$(dirname -- "$name")"
          printf "%s" "$text" > "$out/$name"
        ''
    else
      pkgs.runCommand "unit-${mkPathSafeName name}-disabled"
        {
          preferLocalBuild = true;
          allowSubstitutes = false;
        }
        ''
          name=${shellEscape name}
          mkdir -p "$out/$(dirname "$name")"
          ln -s /dev/null "$out/$name"
        '';

  boolValues = [
    true
    false
    "yes"
    "no"
  ];

  digits = map toString (range 0 9);

  isByteFormat =
    s:
    let
      l = reverseList (stringToCharacters s);
      suffix = head l;
      nums = tail l;
    in
    builtins.isInt s
    || (
      elem suffix (
        [
          "K"
          "M"
          "G"
          "T"
        ]
        ++ digits
      )
      && all (num: elem num digits) nums
    );

  assertByteFormat =
    name: group: attr:
    optional (
      attr ? ${name} && !isByteFormat attr.${name}
    ) "Systemd ${group} field `${name}' must be in byte format [0-9]+[KMGT].";

  toIntBaseDetected =
    value:
    assert (match "[0-9]+|0x[0-9a-fA-F]+" value) != null;
    (fromTOML "v=${value}").v;

  hexChars = stringToCharacters "0123456789abcdefABCDEF";

  isMacAddress =
    s:
    stringLength s == 17
    && flip all (splitString ":" s) (bytes: all (byte: elem byte hexChars) (stringToCharacters bytes));

  assertMacAddress =
    name: group: attr:
    optional (
      attr ? ${name} && !isMacAddress attr.${name}
    ) "Systemd ${group} field `${name}' must be a valid MAC address.";

  assertNetdevMacAddress =
    name: group: attr:
    optional (
      attr ? ${name} && (!isMacAddress attr.${name} && attr.${name} != "none")
    ) "Systemd ${group} field `${name}` must be a valid MAC address or the special value `none`.";

  isNumberOrRangeOf =
    check: v:
    if isInt v then
      check v
    else
      let
        parts = splitString "-" v;
        lower = toIntBase10 (head parts);
        upper = if tail parts != [ ] then toIntBase10 (head (tail parts)) else lower;
      in
      length parts <= 2 && lower <= upper && check lower && check upper;
  isPort = i: i >= 0 && i <= 65535;
  isPortOrPortRange = isNumberOrRangeOf isPort;

  assertPort =
    name: group: attr:
    optional (
      attr ? ${name} && !isPort attr.${name}
    ) "Error on the systemd ${group} field `${name}': ${attr.name} is not a valid port number.";

  assertPortOrPortRange =
    name: group: attr:
    optional (attr ? ${name} && !isPortOrPortRange attr.${name})
      "Error on the systemd ${group} field `${name}': ${attr.name} is not a valid port number or range of port numbers.";

  assertValueOneOf =
    name: values: group: attr:
    optional (
      attr ? ${name} && !elem attr.${name} values
    ) "Systemd ${group} field `${name}' cannot have value `${toString attr.${name}}'.";

  assertValuesSomeOfOr =
    name: values: default: group: attr:
    optional (
      attr ? ${name}
      && !(all (x: elem x values) (splitString " " attr.${name}) || attr.${name} == default)
    ) "Systemd ${group} field `${name}' cannot have value `${toString attr.${name}}'.";

  assertHasField =
    name: group: attr:
    optional (!(attr ? ${name})) "Systemd ${group} field `${name}' must exist.";

  assertRange =
    name: min: max: group: attr:
    optional (
      attr ? ${name} && !(min <= attr.${name} && max >= attr.${name})
    ) "Systemd ${group} field `${name}' is outside the range [${toString min},${toString max}]";

  assertRangeOrOneOf =
    name: min: max: values: group: attr:
    optional
      (
        attr ? ${name}
        && !(
          ((isInt attr.${name} || isFloat attr.${name}) && min <= attr.${name} && max >= attr.${name})
          || elem attr.${name} values
        )
      )
      "Systemd ${group} field `${name}' is not a value in range [${toString min},${toString max}], or one of ${toString values}";

  assertRangeWithOptionalMask =
    name: min: max: group: attr:
    if (attr ? ${name}) then
      if isInt attr.${name} then
        assertRange name min max group attr
      else if isString attr.${name} then
        let
          fields = match "([0-9]+|0x[0-9a-fA-F]+)(/([0-9]+|0x[0-9a-fA-F]+))?" attr.${name};
        in
        if fields == null then
          [
            "Systemd ${group} field `${name}' must either be an integer or two integers separated by a slash (/)."
          ]
        else
          let
            value = toIntBaseDetected (elemAt fields 0);
            mask = mapNullable toIntBaseDetected (elemAt fields 2);
          in
          optional (!(min <= value && max >= value))
            "Systemd ${group} field `${name}' has main value outside the range [${toString min},${toString max}]."
          ++ optional (
            mask != null && !(min <= mask && max >= mask)
          ) "Systemd ${group} field `${name}' has mask outside the range [${toString min},${toString max}]."
      else
        [ "Systemd ${group} field `${name}' must either be an integer or a string." ]
    else
      [ ];

  assertMinimum =
    name: min: group: attr:
    optional (
      attr ? ${name} && attr.${name} < min
    ) "Systemd ${group} field `${name}' must be greater than or equal to ${toString min}";

  assertOnlyFields =
    fields: group: attr:
    let
      badFields = filter (name: !elem name fields) (attrNames attr);
    in
    optional (
      badFields != [ ]
    ) "Systemd ${group} has extra fields [${concatStringsSep " " badFields}].";

  assertInt =
    name: group: attr:
    optional (
      attr ? ${name} && !isInt attr.${name}
    ) "Systemd ${group} field `${name}' is not an integer";

  assertRemoved =
    name: see: group: attr:
    optional (attr ? ${name}) "Systemd ${group} field `${name}' has been removed. See ${see}";

  assertKeyIsSystemdCredential =
    name: group: attr:
    optional (
      attr ? ${name} && !(hasPrefix "@" attr.${name})
    ) "Systemd ${group} field `${name}' is not a systemd credential";

  assertRouteMetricOrTriple =
    name: group: attr:
    let
      isMetric = n: 0 <= n && 4294967295 >= n;

      parts = splitString ":" attr.${name};
      partsValid =
        length parts == 3 && all (p: (match "[0-9]+" p) != null && isMetric (toIntBase10 p)) parts;
      valid = (isInt attr.${name} && isMetric attr.${name}) || partsValid;
    in
    optional (attr ? ${name} && !valid) (
      "Systemd ${group} field `${name}' must either be an integer in the range [0,4294967295]"
      + " or a string containing three integers separated with `:`"
    );

  checkUnitConfig =
    group: checks: attrs:
    let
      # We're applied at the top-level type (attrsOf unitOption), so the actual
      # unit options might contain attributes from mkOverride and mkIf that we need to
      # convert into single values before checking them.
      defs = mapAttrs (const (
        v:
        if v._type or "" == "override" then
          v.content
        else if v._type or "" == "if" then
          v.content
        else
          v
      )) attrs;
      errors = concatMap (c: c group defs) checks;
    in
    if errors == [ ] then true else trace (concatStringsSep "\n" errors) false;

  checkUnitConfigWithLegacyKey =
    legacyKey: group: checks: attrs:
    let
      dump = lib.generators.toPretty { } (
        lib.generators.withRecursion {
          depthLimit = 2;
          throwOnDepthLimit = false;
        } attrs
      );
      attrs' =
        if legacyKey == null then
          attrs
        else if !attrs ? ${legacyKey} then
          attrs
        else if removeAttrs attrs [ legacyKey ] == { } then
          attrs.${legacyKey}
        else
          throw ''
            The declaration

            ${dump}

            must not mix unit options with the legacy key '${legacyKey}'.

            This can be fixed by moving all settings from within ${legacyKey}
            one level up.
          '';
    in
    checkUnitConfig group checks attrs';

  toOption =
    x:
    if x == true then
      "true"
    else if x == false then
      "false"
    else
      toString x;

  attrsToSection =
    as:
    concatStrings (
      concatLists (
        mapAttrsToList (
          name: value:
          map (x: ''
            ${name}=${toOption x}
          '') (if isList value then value else [ value ])
        ) as
      )
    );

  settingsToSections =
    settings:
    concatStringsSep "\n" (
      mapAttrsToList (section_name: section_attrs: ''
        [${section_name}]
        ${attrsToSection section_attrs}
      '') settings
    );

  generateUnits =
    {
      allowCollisions ? true,
      type,
      units,
      upstreamUnits,
      upstreamWants,
      packages ? cfg.packages,
      package ? cfg.package,
    }:
    let
      typeDir =
        {
          system = "system";
          initrd = "system";
          user = "user";
          nspawn = "nspawn";
        }
        .${type};
    in
    pkgs.runCommand "${type}-units"
      {
        preferLocalBuild = true;
        allowSubstitutes = false;
      }
      ''
        mkdir -p $out

        # Copy the upstream systemd units we're interested in.
        for i in ${toString upstreamUnits}; do
          fn=${package}/example/systemd/${typeDir}/$i
          if ! [ -e $fn ]; then echo "missing $fn"; false; fi
          if [ -L $fn ]; then
            target="$(readlink "$fn")"
            if [ ''${target:0:3} = ../ ]; then
              ln -s "$(readlink -f "$fn")" $out/
            else
              cp -pd $fn $out/
            fi
          else
            ln -s $fn $out/
          fi
        done

        # Copy .wants links, but only those that point to units that
        # we're interested in.
        for i in ${toString upstreamWants}; do
          fn=${package}/example/systemd/${typeDir}/$i
          if ! [ -e $fn ]; then echo "missing $fn"; false; fi
          x=$out/$(basename $fn)
          mkdir $x
          for i in $fn/*; do
            y=$x/$(basename $i)
            cp -pd $i $y
            if ! [ -e $y ]; then rm $y; fi
          done
        done

        # Symlink all units provided listed in systemd.packages.
        packages="${toString packages}"

        # Filter duplicate directories
        declare -A unique_packages
        for k in $packages ; do unique_packages[$k]=1 ; done

        for i in ''${!unique_packages[@]}; do
          for fn in $i/etc/systemd/${typeDir}/* $i/lib/systemd/${typeDir}/*; do
            if ! [[ "$fn" =~ .wants$ ]]; then
              if [[ -d "$fn" ]]; then
                targetDir="$out/$(basename "$fn")"
                mkdir -p "$targetDir"
                ${lndir} "$fn" "$targetDir"
              else
                ln -s $fn $out/
              fi
            fi
          done
        done

        # Symlink units defined by systemd.units where override strategy
        # shall be automatically detected. If these are also provided by
        # systemd or systemd.packages, then add them as
        # <unit-name>.d/overrides.conf, which makes them extend the
        # upstream unit.
        for i in ${
          toString (
            mapAttrsToList (n: v: v.unit) (
              filterAttrs (
                n: v: (attrByPath [ "overrideStrategy" ] "asDropinIfExists" v) == "asDropinIfExists"
              ) units
            )
          )
        }; do
          fn=$(basename $i/*)
          if [ -e $out/$fn ]; then
            if [ "$(readlink -f $i/$fn)" = /dev/null ]; then
              ln -sfn /dev/null $out/$fn
            else
              ${
                if allowCollisions then
                  ''
                    mkdir -p $out/$fn.d
                    ln -s $i/$fn $out/$fn.d/overrides.conf
                  ''
                else
                  ''
                    echo "Found multiple derivations configuring $fn!"
                    exit 1
                  ''
              }
            fi
         else
            ln -fs $i/$fn $out/
          fi
        done

        # Symlink units defined by systemd.units which shall be
        # treated as drop-in file.
        for i in ${
          toString (
            mapAttrsToList (n: v: v.unit) (
              filterAttrs (n: v: v ? overrideStrategy && v.overrideStrategy == "asDropin") units
            )
          )
        }; do
          fn=$(basename $i/*)
          mkdir -p $out/$fn.d
          ln -s $i/$fn $out/$fn.d/overrides.conf
        done

        # Create service aliases from aliases option.
        ${concatStrings (
          mapAttrsToList (
            name: unit:
            concatMapStrings (name2: ''
              ln -sfn '${name}' $out/'${name2}'
            '') (unit.aliases or [ ])
          ) units
        )}

        # Create .wants, .upholds and .requires symlinks from the wantedBy, upheldBy and
        # requiredBy options.
        ${concatStrings (
          mapAttrsToList (
            name: unit:
            concatMapStrings (name2: ''
              mkdir -p $out/'${name2}.wants'
              ln -sfn '../${name}' $out/'${name2}.wants'/
            '') (unit.wantedBy or [ ])
          ) units
        )}

        ${concatStrings (
          mapAttrsToList (
            name: unit:
            concatMapStrings (name2: ''
              mkdir -p $out/'${name2}.upholds'
              ln -sfn '../${name}' $out/'${name2}.upholds'/
            '') (unit.upheldBy or [ ])
          ) units
        )}

        ${concatStrings (
          mapAttrsToList (
            name: unit:
            concatMapStrings (name2: ''
              mkdir -p $out/'${name2}.requires'
              ln -sfn '../${name}' $out/'${name2}.requires'/
            '') (unit.requiredBy or [ ])
          ) units
        )}

        ${optionalString (type == "system") ''
          # Stupid misc. symlinks.
          ln -s ${cfg.defaultUnit} $out/default.target
          ln -s ${cfg.ctrlAltDelUnit} $out/ctrl-alt-del.target

          ln -s ../remote-fs.target $out/multi-user.target.wants/
        ''}
      ''; # */

  makeJobScript =
    {
      name,
      text,
      enableStrictShellChecks,
    }:
    let
      scriptName = replaceStrings [ "\\" "@" ] [ "-" "_" ] (shellEscape name);
      out =
        (
          if !enableStrictShellChecks then
            pkgs.writeShellScriptBin scriptName ''
              set -e

              ${text}
            ''
          else
            pkgs.writeShellApplication {
              name = scriptName;
              inherit text;
            }
        ).overrideAttrs
          (_: {
            # The derivation name is different from the script file name
            # to keep the script file name short to avoid cluttering logs.
            name = "unit-script-${scriptName}";
          });
    in
    lib.getExe out;

  unitConfig =
    {
      config,
      name,
      options,
      ...
    }:
    {
      config = {
        unitConfig = {
          ${if config.requires != [ ] then "Requires" else null} = toString config.requires;
          ${if config.wants != [ ] then "Wants" else null} = toString config.wants;
          ${if config.upholds != [ ] then "Upholds" else null} = toString config.upholds;
          ${if config.after != [ ] then "After" else null} = toString config.after;
          ${if config.before != [ ] then "Before" else null} = toString config.before;
          ${if config.bindsTo != [ ] then "BindsTo" else null} = toString config.bindsTo;
          ${if config.partOf != [ ] then "PartOf" else null} = toString config.partOf;
          ${if config.conflicts != [ ] then "Conflicts" else null} = toString config.conflicts;
          ${if config.requisite != [ ] then "Requisite" else null} = toString config.requisite;
          ${if config.description != "" then "Description" else null} = config.description;
          ${if config.documentation != [ ] then "Documentation" else null} = toString config.documentation;
          ${if config.onFailure != [ ] then "OnFailure" else null} = toString config.onFailure;
          ${if config.onSuccess != [ ] then "OnSuccess" else null} = toString config.onSuccess;
          ${if options.startLimitIntervalSec.isDefined then "StartLimitIntervalSec" else null} =
            toString config.startLimitIntervalSec;
          ${if options.startLimitBurst.isDefined then "StartLimitBurst" else null} =
            toString config.startLimitBurst;
        }
        // optionalAttrs (config ? restartTriggers && config.restartTriggers != [ ]) {
          X-Restart-Triggers = "${pkgs.writeText "X-Restart-Triggers-${name}" (
            pipe config.restartTriggers [
              flatten
              (map (x: if isPath x then "${x}" else x))
              toString
            ]
          )}";
        }
        // optionalAttrs (config ? reloadTriggers && config.reloadTriggers != [ ]) {
          X-Reload-Triggers = "${pkgs.writeText "X-Reload-Triggers-${name}" (
            pipe config.reloadTriggers [
              flatten
              (map (x: if isPath x then "${x}" else x))
              toString
            ]
          )}";
        };
      };
    };

  serviceConfig =
    let
      nixosConfig = config;
    in
    {
      name,
      lib,
      config,
      ...
    }:
    {
      config = {
        name = "${name}.service";
        environment.PATH =
          mkIf (config.path != [ ])
            "${makeBinPath config.path}:${makeSearchPathOutput "bin" "sbin" config.path}";

        enableStrictShellChecks = lib.mkOptionDefault nixosConfig.systemd.enableStrictShellChecks;
      };
    };

  pathConfig =
    { name, config, ... }:
    {
      config = {
        name = "${name}.path";
      };
    };

  socketConfig =
    { name, config, ... }:
    {
      config = {
        name = "${name}.socket";
      };
    };

  sliceConfig =
    { name, config, ... }:
    {
      config = {
        name = "${name}.slice";
      };
    };

  targetConfig =
    { name, config, ... }:
    {
      config = {
        name = "${name}.target";
      };
    };

  timerConfig =
    { name, config, ... }:
    {
      config = {
        name = "${name}.timer";
      };
    };

  stage2ServiceConfig =
    { config, ... }:
    {
      imports = [ serviceConfig ];
      # Default path for systemd services. Should be quite minimal.
      config.path = mkIf config.enableDefaultPath (mkAfter [
        pkgs.coreutils
        pkgs.findutils
        pkgs.gnugrep
        pkgs.gnused
        systemd
      ]);
    };

  stage1ServiceConfig = serviceConfig;

  mountConfig =
    { config, ... }:
    {
      config = {
        name = "${utils.escapeSystemdPath config.where}.mount";
        mountConfig = {
          What = config.what;
          Where = config.where;
        }
        // optionalAttrs (config.type != "") {
          Type = config.type;
        }
        // optionalAttrs (config.options != "") {
          Options = config.options;
        };
      };
    };

  automountConfig =
    { config, ... }:
    {
      config = {
        name = "${utils.escapeSystemdPath config.where}.automount";
        automountConfig = {
          Where = config.where;
        };
      };
    };

  commonUnitText =
    def: lines:
    (settingsToSections { Unit = def.unitConfig; })
    + lines
    + optionalString (def.wantedBy != [ ]) ''

      [Install]
      WantedBy=${concatStringsSep " " def.wantedBy}
    '';

  targetToUnit = def: {
    inherit (def)
      name
      aliases
      wantedBy
      requiredBy
      upheldBy
      enable
      overrideStrategy
      ;
    text = (settingsToSections { Unit = def.unitConfig; });
  };

  serviceToUnit = def: {
    inherit (def)
      name
      aliases
      wantedBy
      requiredBy
      upheldBy
      enable
      overrideStrategy
      ;
    text = commonUnitText def (
      ''
        [Service]
      ''
      + (
        let
          env = cfg.globalEnvironment // def.environment;
        in
        concatMapStrings (
          n:
          let
            s = optionalString (env.${n} != null) "Environment=${toJSON "${n}=${env.${n}}"}\n";
            # systemd max line length is now 1MiB
            # https://github.com/systemd/systemd/commit/e6dde451a51dc5aaa7f4d98d39b8fe735f73d2af
          in
          if stringLength s >= 1048576 then
            throw "The value of the environment variable ‘${n}’ in systemd service ‘${def.name}.service’ is too long."
          else
            s
        ) (attrNames env)
      )
      + (
        if def ? reloadIfChanged && def.reloadIfChanged then
          ''
            X-ReloadIfChanged=true
          ''
        else if (def ? restartIfChanged && !def.restartIfChanged) then
          ''
            X-RestartIfChanged=false
          ''
        else
          ""
      )
      + optionalString (def ? stopIfChanged && !def.stopIfChanged) ''
        X-StopIfChanged=false
      ''
      + optionalString (def ? notSocketActivated && def.notSocketActivated) ''
        X-NotSocketActivated=true
      ''
      + attrsToSection def.serviceConfig
    );
  };

  socketToUnit = def: {
    inherit (def)
      name
      aliases
      wantedBy
      requiredBy
      upheldBy
      enable
      overrideStrategy
      ;
    text = commonUnitText def ''
      [Socket]
      ${attrsToSection def.socketConfig}
      ${concatStringsSep "\n" (map (s: "ListenStream=${s}") def.listenStreams)}
      ${concatStringsSep "\n" (map (s: "ListenDatagram=${s}") def.listenDatagrams)}
    '';
  };

  timerToUnit = def: {
    inherit (def)
      name
      aliases
      wantedBy
      requiredBy
      upheldBy
      enable
      overrideStrategy
      ;
    text = commonUnitText def (settingsToSections {
      Timer = def.timerConfig;
    });
  };

  pathToUnit = def: {
    inherit (def)
      name
      aliases
      wantedBy
      requiredBy
      upheldBy
      enable
      overrideStrategy
      ;
    text = commonUnitText def (settingsToSections {
      Path = def.pathConfig;
    });
  };

  mountToUnit = def: {
    inherit (def)
      name
      aliases
      wantedBy
      requiredBy
      upheldBy
      enable
      overrideStrategy
      ;
    text = commonUnitText def (settingsToSections {
      Mount = def.mountConfig;
    });
  };

  automountToUnit = def: {
    inherit (def)
      name
      aliases
      wantedBy
      requiredBy
      upheldBy
      enable
      overrideStrategy
      ;
    text = commonUnitText def (settingsToSections {
      Automount = def.automountConfig;
    });
  };

  sliceToUnit = def: {
    inherit (def)
      name
      aliases
      wantedBy
      requiredBy
      upheldBy
      enable
      overrideStrategy
      ;
    text = commonUnitText def (settingsToSections {
      Slice = def.sliceConfig;
    });
  };

  # Create a directory that contains systemd definition files from an attrset
  # that contains the file names as keys and the content as values. The values
  # in that attrset are determined by the supplied format.
  definitions =
    directoryName: format: definitionAttrs:
    let
      listOfDefinitions = mapAttrsToList (name: format.generate "${name}.conf") definitionAttrs;
    in
    pkgs.runCommand directoryName { } ''
      mkdir -p $out
      ${(concatStringsSep "\n" (map (pkg: "cp ${pkg} $out/${pkg.name}") listOfDefinitions))}
    '';

  # The maximum number of characters allowed in a GPT partition label. This
  # limit is specified by UEFI and enforced by systemd-repart.
  # Corresponds to GPT_LABEL_MAX from systemd's gpt.h.
  GPTMaxLabelLength = 36;

}