fork/nix-minecraft

git clone https://git.julia.blue/fork/nix-minecraft

Infinidogemodule: run formattera3fd606

develop
18.3 KiB491 linesraw
1{ config, lib, pkgs, ... }:
2with lib;
3let
4  cfg = config.services.minecraft-servers;
5
6  mkOpt = type: default:
7    mkOption { inherit type default; };
8
9  mkOpt' = type: default: description:
10    mkOption { inherit type default description; };
11
12  mkBoolOpt = default: mkOption {
13    inherit default;
14    type = types.bool;
15    example = true;
16  };
17
18  mkBoolOpt' = default: description: mkOption {
19    inherit default description;
20    type = types.bool;
21    example = true;
22  };
23
24  normalizeFiles = files: mapAttrs configToPath (filterAttrs (_: nonEmptyValue) files);
25  nonEmptyValue = x: nonEmpty x && (x ? value -> nonEmpty x.value);
26  nonEmpty = x: x != { } && x != [ ];
27
28  configToPath = name: config:
29    if isStringLike config # Includes paths and packages
30    then config
31    else (getFormat name config).generate name config.value;
32  getFormat = name: config:
33    if config ? format && config.format != null
34    then config.format
35    else inferFormat name;
36  inferFormat = name:
37    let
38      error = throw "nix-minecraft: Could not infer format from file '${name}'. Specify one using 'format'.";
39      extension = builtins.match "[^.]*\\.(.+)" name;
40    in
41    if extension != null && extension != [ ]
42    then formatExtensions.${head extension} or error
43    else error;
44
45  formatExtensions = with pkgs.formats; {
46    "yml" = yaml { };
47    "yaml" = yaml { };
48    "json" = json { };
49    "props" = keyValue { };
50    "properties" = keyValue { };
51    "toml" = toml { };
52    "ini" = ini { };
53  };
54
55  configType = types.submodule {
56    options = {
57      format = mkOption {
58        type = with types; nullOr attrs;
59        default = null;
60        description = ''
61          The format to use when converting "value" into a file. If set to
62          null (the default), we'll try to infer it from the file name.
63        '';
64        example = literalExpression "pkgs.formats.yaml { }";
65      };
66      value = mkOption {
67        type = with types; either (attrsOf anything) (listOf anything);
68        description = ''
69          A value that can be converted into the specified format.
70        '';
71      };
72    };
73  };
74
75  mkEnableOpt = description: mkBoolOpt' false description;
76in
77{
78  options.services.minecraft-servers = {
79    enable = mkEnableOpt ''
80      If enabled, the servers in <option>services.minecraft-servers.servers</option>
81      will be created and started as applicable.
82      The data for the servers will be loaded from and
83      saved to <option>services.minecraft-servers.dataDir</option>
84    '';
85
86    eula = mkEnableOpt ''
87      Whether you agree to
88      <link xlink:href="https://account.mojang.com/documents/minecraft_eula">
89      Mojang's EULA</link>. This option must be set to
90      <literal>true</literal> to run Minecraft server.
91    '';
92
93    openFirewall = mkEnableOpt ''
94      Whether to open ports in the firewall for each server.
95      Sets the default for <option>services.minecraft-servers.servers.<name>.openFirewall</option>.
96    '';
97
98    dataDir = mkOpt' types.path "/srv/minecraft" ''
99      Directory to store the Minecraft servers.
100      Each server will be under a subdirectory named after
101      the server name in this directory, such as <literal>/srv/minecraft/servername</literal>.
102    '';
103
104    runDir = mkOpt' types.path "/run/minecraft" ''
105      Directory to place the runtime tmux sockets into.
106      Each server's console will be a tmux socket file in the form of <literal>servername.sock</literal>.
107      To connect to the console, run `tmux -S /run/minecraft/servername.sock attach`,
108      press `Ctrl + b` then `d` to detach.
109    '';
110
111    user = mkOption {
112      type = types.str;
113      default = "minecraft";
114      description = ''
115        Name of the user to create and run servers under.
116        It is recommended to leave this as the default, as it is
117        the same user as <option>services.minecraft-server</option>.
118      '';
119      internal = true;
120      visible = false;
121    };
122
123    group = mkOption {
124      type = types.str;
125      default = "minecraft";
126      description = ''
127        Name of the group to create and run servers under.
128        In order to modify the server files or attach to the tmux socket,
129        your user must be a part of this group.
130        It is recommended to leave this as the default, as it is
131        the same group as <option>services.minecraft-server</option>.
132      '';
133    };
134
135    environmentFile = mkOpt' (types.nullOr types.path) null ''
136      File consisting of lines in the form varname=value to define environment
137      variables for the minecraft servers.
138
139      Secrets (database passwords, secret keys, etc.) can be provided to server
140      files without adding them to the Nix store by defining them in the
141      environment file and referring to them in option
142      <option>services.minecraft-servers.servers.<name>.files</option> with the
143      syntax @varname@.
144    '';
145
146    servers = mkOption {
147      default = { };
148      description = ''
149        Servers to create and manage using this module.
150        Each server can be stopped with <literal>systemctl stop minecraft-server-servername</literal>.
151        ::: {.warning}
152        If the server is not stopped using `systemctl`, the service will automatically restart the server.
153        See <option>services.minecraft-servers.servers.<name>.restart</option>.
154        :::
155      '';
156      type = types.attrsOf (types.submodule {
157        options = {
158          enable = mkEnableOpt ''
159            Whether to enable this server.
160            If set to <literal>false</literal>, does NOT delete any data in the data directory,
161            just does not generate the service file.
162          '';
163
164          autoStart = mkBoolOpt' true ''
165            Whether to start this server on boot.
166            If set to <literal>false</literal>, can still be started with
167            <literal>systemctl start minecraft-server-servername</literal>.
168            Requires the server to be enabled.
169          '';
170
171          openFirewall = mkOption {
172            type = types.bool;
173            default = cfg.openFirewall;
174            defaultText = "The value of <literal>services.minecraft-servers.openFirewall</literal>";
175            description = ''
176              Whether to open ports in the firewall for this server.
177            '';
178          };
179
180          restart = mkOpt' types.str "always" ''
181            Value of systemd's <literal>Restart=</literal> service configuration option.
182            Due to the servers being started in tmux sockets, values other than
183            <literal>"no"</literal> and <literal>"always"</literal> may not work properly.
184            As a consequence of the <literal>"always"</literal> option, stopping the server
185            in-game with the <literal>stop</literal> command will cause the server to automatically restart.
186          '';
187
188          enableReload = mkOpt' types.bool false ''
189            Reload server when configuration changes (instead of restart).
190
191            This action re-links/copies the declared symlinks/files. You can
192            include additional actions (even in-game commands) by setting
193            <option>services.minecraft-servers.<name>.extraReload</option>.
194          '';
195
196          extraReload = mkOpt' types.lines "" ''
197            Extra commands to run when reloading the service. Only has an
198            effect if
199            <option>services.minecraft-servers.<name>.enableReload</option> is
200            true.
201          '';
202
203          whitelist = mkOption {
204            type =
205              let
206                minecraftUUID = types.strMatching
207                  "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" // {
208                  description = "Minecraft UUID";
209                };
210              in
211              types.attrsOf minecraftUUID;
212            default = { };
213            description = ''
214              Whitelisted players, only has an effect when
215              enabled via <option>services.minecraft-servers.<name>.serverProperties</option>
216              by setting <literal>white-list</literal> to <literal>true</literal.
217            '';
218            example = literalExpression ''
219              {
220                username1 = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
221                username2 = "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy";
222              }
223            '';
224          };
225
226          serverProperties = mkOption {
227            type = with types; attrsOf (oneOf [ bool int str ]);
228            default = { };
229            example = literalExpression ''
230              {
231                server-port = 43000;
232                difficulty = 3;
233                gamemode = 1;
234                max-players = 5;
235                motd = "NixOS Minecraft server!";
236                white-list = true;
237                enable-rcon = true;
238                "rcon.password" = "hunter2";
239              }
240            '';
241            description = ''
242              Minecraft server properties for the server.properties file of this server. See
243              <link xlink:href="https://minecraft.gamepedia.com/Server.properties#Java_Edition_3"/>
244              for documentation on these values.
245            '';
246          };
247
248          package = mkOption {
249            description = "The Minecraft server package to use.";
250            type = types.package;
251            default = pkgs.minecraft-server;
252            defaultText = literalExpression "pkgs.minecraft-server";
253            example = "pkgs.minecraftServers.vanilla-1_18_2";
254          };
255
256          jvmOpts = mkOpt' (types.separatedString " ") "-Xmx2G -Xms1G" "JVM options for this server.";
257
258          symlinks = with types; mkOpt' (attrsOf (either path configType)) { } ''
259            Things to symlink into this server's data directory, in the form of
260            a nix package/derivation. Can be used to declaratively manage
261            arbitrary files in the server's data directory.
262          '';
263          files = with types; mkOpt' (attrsOf (either path configType)) { } ''
264            Things to copy into this server's data directory. Similar to
265            symlinks, but these are actual files. Useful for configuration
266            files that don't behave well when read-only.
267          '';
268        };
269      });
270    };
271  };
272
273  config = mkIf cfg.enable
274    (
275      let
276        servers = filterAttrs (_: cfg: cfg.enable) cfg.servers;
277      in
278      {
279        users = {
280          users.minecraft = {
281            description = "Minecraft server service user";
282            home = cfg.dataDir;
283            createHome = true;
284            homeMode = "770";
285            isSystemUser = true;
286            group = "minecraft";
287          };
288          groups.minecraft = { };
289        };
290
291        assertions = [
292          {
293            assertion = cfg.eula;
294            message = "You must agree to Mojangs EULA to run minecraft-servers."
295              + " Read https://account.mojang.com/documents/minecraft_eula and"
296              + " set `services.minecraft-servers.eula` to `true` if you agree.";
297          }
298          {
299            assertion = !config.services.minecraft-server.enable && cfg.dataDir != config.services.minecraft-server.dataDir;
300            message = "`services.minecraft-servers.dataDir` and `services.minecraft-server.dataDir` conflict."
301              + " Set one to use a different data directory.";
302          }
303          {
304            assertion =
305              let
306                serverPorts = mapAttrsToList
307                  (name: conf: conf.serverProperties.server-port or 25565)
308                  (filterAttrs (_: cfg: cfg.openFirewall) servers);
309
310                counts = map (port: count (x: x == port) serverPorts) (unique serverPorts);
311              in
312              lib.all (x: x == 1) counts;
313            message = "Multiple servers are set to use the same port. Change one to use a different port.";
314          }
315        ];
316
317        networking.firewall =
318          let
319            toOpen = filterAttrs (_: cfg: cfg.openFirewall) servers;
320            # Minecraft and RCON
321            getTCPPorts = n: c:
322              [ c.serverProperties.server-port or 25565 ] ++
323              (optional (c.serverProperties.enable-rcon or false) (c.serverProperties."rcon.port" or 25575));
324            # Query
325            getUDPPorts = n: c:
326              optional (c.serverProperties.enable-query or false) (c.serverProperties."query.port" or 25565);
327          in
328          {
329            allowedUDPPorts = flatten (mapAttrsToList getUDPPorts toOpen);
330            allowedTCPPorts = flatten (mapAttrsToList getTCPPorts toOpen);
331          };
332
333        systemd.tmpfiles.rules = mapAttrsToList
334          (name: _:
335            "d '${cfg.dataDir}/${name}' 0770 ${cfg.user} - - -"
336          )
337          servers;
338
339        systemd.services = mapAttrs'
340          (name: conf:
341            let
342              tmux = "${getBin pkgs.tmux}/bin/tmux";
343              tmuxSock = "${cfg.runDir}/${name}.sock";
344
345              symlinks = normalizeFiles ({
346                "eula.txt".value = { eula = true; };
347                "eula.txt".format = pkgs.formats.keyValue { };
348              } // conf.symlinks);
349              files = normalizeFiles ({
350                "whitelist.json".value = mapAttrsToList (n: v: { name = n; uuid = v; }) conf.whitelist;
351                "server.properties".value = conf.serverProperties;
352              } // conf.files);
353
354              startScript = pkgs.writeScript "minecraft-start-${name}" ''
355                #!${pkgs.runtimeShell}
356                ${tmux} -S ${tmuxSock} new -d ${getExe conf.package} ${conf.jvmOpts}
357
358                # HACK: PrivateUsers makes every user besides root/minecraft `nobody`, so this restores old tmux behavior
359                # See https://github.com/Infinidoge/nix-minecraft/issues/5
360                ${tmux} -S ${tmuxSock} server-access -aw nobody
361              '';
362
363              stopScript = pkgs.writeScript "minecraft-stop-${name}" ''
364                #!${pkgs.runtimeShell}
365
366                if ! [ -d "/proc/$1" ]; then
367                  exit 0
368                fi
369
370                ${tmux} -S ${tmuxSock} send-keys stop Enter
371              '';
372            in
373            {
374              name = "minecraft-server-${name}";
375              value = rec {
376                description = "Minecraft Server ${name}";
377                wantedBy = mkIf conf.autoStart [ "multi-user.target" ];
378                after = [ "network.target" ];
379
380                enable = conf.enable;
381
382                serviceConfig = {
383                  ExecStart = "${startScript}";
384                  ExecStop = "${stopScript} $MAINPID";
385                  Restart = conf.restart;
386                  WorkingDirectory = "${cfg.dataDir}/${name}";
387                  User = "minecraft";
388                  Type = "forking";
389                  GuessMainPID = true;
390                  RuntimeDirectory = "minecraft";
391                  RuntimeDirectoryPreserve = "yes";
392                  EnvironmentFile = mkIf (cfg.environmentFile != null)
393                    (toString cfg.environmentFile);
394
395                  # Hardening
396                  CapabilityBoundingSet = [ "" ];
397                  DeviceAllow = [ "" ];
398                  LockPersonality = true;
399                  PrivateDevices = true;
400                  PrivateTmp = true;
401                  PrivateUsers = true;
402                  ProtectClock = true;
403                  ProtectControlGroups = true;
404                  ProtectHome = true;
405                  ProtectHostname = true;
406                  ProtectKernelLogs = true;
407                  ProtectKernelModules = true;
408                  ProtectKernelTunables = true;
409                  ProtectProc = "invisible";
410                  RestrictNamespaces = true;
411                  RestrictRealtime = true;
412                  RestrictSUIDSGID = true;
413                  SystemCallArchitectures = "native";
414                  UMask = "0007";
415                };
416                restartIfChanged = !conf.enableReload;
417                reloadIfChanged = conf.enableReload;
418
419                reload = ''
420                  ${postStop}
421                  ${preStart}
422                '' + conf.extraReload;
423
424                preStart =
425                  let
426                    mkSymlinks = pkgs.writeShellScript "minecraft-server-${name}-symlinks"
427                      (concatStringsSep "\n"
428                        (mapAttrsToList
429                          (n: v: ''
430                            if [[ -L "${n}" ]]; then
431                              unlink "${n}"
432                            elif [[ -e "${n}" ]]; then
433                              echo "${n} already exists, moving"
434                              mv "${n}" "${n}.bak"
435                            fi
436                            mkdir -p "$(dirname "${n}")"
437                            ln -sf "${v}" "${n}"
438                          '')
439                          symlinks));
440
441                    mkFiles = pkgs.writeShellScript "minecraft-server-${name}-files"
442                      (concatStringsSep "\n"
443                        (mapAttrsToList
444                          (n: v: ''
445                            if [[ -L "${n}" ]]; then
446                              unlink "${n}"
447                            elif ${pkgs.diffutils}/bin/cmp -s "${n}" "${v}"; then
448                              rm "${n}"
449                            elif [[ -e "${n}" ]]; then
450                              echo "${n} already exists, moving"
451                              mv "${n}" "${n}.bak"
452                            fi
453                            mkdir -p $(dirname "${n}")
454                            ${pkgs.gawk}/bin/awk '{
455                              for(varname in ENVIRON)
456                                gsub("@"varname"@", ENVIRON[varname])
457                              print
458                            }' "${v}" > "${n}"
459                          '')
460                          files));
461                  in
462                  ''
463                    ${mkSymlinks}
464                    ${mkFiles}
465                  '';
466
467                postStart = ''
468                  ${pkgs.coreutils}/bin/chmod 660 ${tmuxSock}
469                '';
470
471                postStop =
472                  let
473                    rmSymlinks = pkgs.writeShellScript "minecraft-server-${name}-rm-symlinks"
474                      (concatStringsSep "\n"
475                        (mapAttrsToList (n: v: "unlink \"${n}\"") symlinks)
476                      );
477                    rmFiles = pkgs.writeShellScript "minecraft-server-${name}-rm-files"
478                      (concatStringsSep "\n"
479                        (mapAttrsToList (n: v: "rm -f \"${n}\"") files)
480                      );
481                  in
482                  ''
483                    ${rmSymlinks}
484                    ${rmFiles}
485                  '';
486              };
487            })
488          servers;
489      }
490    );
491}