1{ config, pkgs, lib, ... }:
2
3with lib;
4
5let
6 cfg = config.services.nix-serve;
7in
8{
9 options = {
10 services.nix-serve = {
11 enable = mkEnableOption (lib.mdDoc "nix-serve, the standalone Nix binary cache server");
12
13 port = mkOption {
14 type = types.port;
15 default = 5000;
16 description = lib.mdDoc ''
17 Port number where nix-serve will listen on.
18 '';
19 };
20
21 bindAddress = mkOption {
22 type = types.str;
23 default = "0.0.0.0";
24 description = lib.mdDoc ''
25 IP address where nix-serve will bind its listening socket.
26 '';
27 };
28
29 package = mkOption {
30 type = types.package;
31 default = pkgs.nix-serve;
32 defaultText = literalExpression "pkgs.nix-serve";
33 description = lib.mdDoc ''
34 nix-serve package to use.
35 '';
36 };
37
38 openFirewall = mkOption {
39 type = types.bool;
40 default = false;
41 description = lib.mdDoc "Open ports in the firewall for nix-serve.";
42 };
43
44 secretKeyFile = mkOption {
45 type = types.nullOr types.str;
46 default = null;
47 description = lib.mdDoc ''
48 The path to the file used for signing derivation data.
49 Generate with:
50
51 ```
52 nix-store --generate-binary-cache-key key-name secret-key-file public-key-file
53 ```
54
55 For more details see {manpage}`nix-store(1)`.
56 '';
57 };
58
59 extraParams = mkOption {
60 type = types.separatedString " ";
61 default = "";
62 description = lib.mdDoc ''
63 Extra command line parameters for nix-serve.
64 '';
65 };
66 };
67 };
68
69 config = mkIf cfg.enable {
70 systemd.services.nix-serve = {
71 description = "nix-serve binary cache server";
72 after = [ "network.target" ];
73 wantedBy = [ "multi-user.target" ];
74
75 path = [ config.nix.package.out pkgs.bzip2.bin ];
76 environment.NIX_REMOTE = "daemon";
77
78 script = ''
79 ${lib.optionalString (cfg.secretKeyFile != null) ''
80 export NIX_SECRET_KEY_FILE="$CREDENTIALS_DIRECTORY/NIX_SECRET_KEY_FILE"
81 ''}
82 exec ${cfg.package}/bin/nix-serve --listen ${cfg.bindAddress}:${toString cfg.port} ${cfg.extraParams}
83 '';
84
85 serviceConfig = {
86 Restart = "always";
87 RestartSec = "5s";
88 User = "nix-serve";
89 Group = "nix-serve";
90 DynamicUser = true;
91 LoadCredential = lib.optionalString (cfg.secretKeyFile != null)
92 "NIX_SECRET_KEY_FILE:${cfg.secretKeyFile}";
93 };
94 };
95
96 networking.firewall = mkIf cfg.openFirewall {
97 allowedTCPPorts = [ cfg.port ];
98 };
99 };
100}