fork/nix-minecraft

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

InfinidogeDRAFT: switch module from tmux to abduco8682670

feat/abduco
12.9 KiB353 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  mkEnableOpt = description: mkBoolOpt' false description;
25in
26{
27  options.services.minecraft-servers = {
28    enable = mkEnableOpt ''
29      If enabled, the servers in <option>services.minecraft-servers.servers</option>
30      will be created and started as applicable.
31      The data for the servers will be loaded from and
32      saved to <option>services.minecraft-servers.dataDir</option>
33    '';
34
35    eula = mkEnableOpt ''
36      Whether you agree to
37      <link xlink:href="https://account.mojang.com/documents/minecraft_eula">
38      Mojang's EULA</link>. This option must be set to
39      <literal>true</literal> to run Minecraft server.
40    '';
41
42    openFirewall = mkEnableOpt ''
43      Whether to open ports in the firewall for each server.
44      Sets the default for <option>services.minecraft-servers.servers.<name>.openFirewall</option>.
45    '';
46
47    dataDir = mkOpt' types.path "/srv/minecraft" ''
48      Directory to store the Minecraft servers.
49      Each server will be under a subdirectory named after
50      the server name in this directory, such as <literal>/srv/minecraft/servername</literal>.
51    '';
52
53    runDir = mkOpt' types.path "/run/minecraft" ''
54      Directory to place the runtime console sockets into.
55      Each server's console will be a socket file in the form of <literal>servername.sock</literal>.
56      To connect to the console, run `abduco -a /run/minecraft/servername.sock attach`,
57      press `Ctrl + \` to detach.
58    '';
59
60    user = mkOption {
61      type = types.string;
62      default = "minecraft";
63      description = ''
64        Name of the user to create and run servers under.
65        It is recommended to leave this as the default, as it is
66        the same user as <option>services.minecraft-server</option>.
67      '';
68      internal = true;
69      visible = false;
70    };
71
72    group = mkOption {
73      type = types.string;
74      default = "minecraft";
75      description = ''
76        Name of the group to create and run servers under.
77        In order to modify the server files or attach to the console socket,
78        your user must be a part of this group.
79        It is recommended to leave this as the default, as it is
80        the same group as <option>services.minecraft-server</option>.
81      '';
82    };
83
84    servers = mkOption {
85      default = { };
86      description = ''
87        Servers to create and manage using this module.
88        Each server can be stopped with <literal>systemctl stop minecraft-server-servername</literal>.
89        ::: {.warning}
90        If the server is not stopped using `systemctl`, the service will automatically restart the server.
91        See <option>services.minecraft-servers.servers.<name>.restart</option>.
92        :::
93      '';
94      type = types.attrsOf (types.submodule {
95        options = {
96          enable = mkEnableOpt ''
97            Whether to enable this server.
98            If set to <literal>false</literal>, does NOT delete any data in the data directory,
99            just does not generate the service file.
100          '';
101
102          autoStart = mkBoolOpt' true ''
103            Whether to start this server on boot.
104            If set to <literal>false</literal>, can still be started with
105            <literal>systemctl start minecraft-server-servername</literal>.
106            Requires the server to be enabled.
107          '';
108
109          openFirewall = mkOption {
110            type = types.bool;
111            default = cfg.openFirewall;
112            defaultText = "The value of <literal>services.minecraft-servers.openFirewall</literal>";
113            description = ''
114              Whether to open ports in the firewall for this server.
115            '';
116          };
117
118          restart = mkOpt' types.str "always" ''
119            Value of systemd's <literal>Restart=</literal> service configuration option.
120            Due to the servers being started in console sockets, values other than
121            <literal>"no"</literal> and <literal>"always"</literal> may not work properly.
122            As a consequence of the <literal>"always"</literal> option, stopping the server
123            in-game with the <literal>stop</literal> command will cause the server to automatically restart.
124          '';
125
126          whitelist = mkOption {
127            type =
128              let
129                minecraftUUID = types.strMatching
130                  "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" // {
131                  description = "Minecraft UUID";
132                };
133              in
134              types.attrsOf minecraftUUID;
135            default = { };
136            description = ''
137              Whitelisted players, only has an effect when
138              enabled via <option>services.minecraft-servers.<name>.serverProperties</option>
139              by setting <literal>white-list</literal> to <literal>true</literal.
140            '';
141            example = literalExpression ''
142              {
143                username1 = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
144                username2 = "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy";
145              }
146            '';
147          };
148
149          serverProperties = mkOption {
150            type = with types; attrsOf (oneOf [ bool int str ]);
151            default = { };
152            example = literalExpression ''
153              {
154                server-port = 43000;
155                difficulty = 3;
156                gamemode = 1;
157                max-players = 5;
158                motd = "NixOS Minecraft server!";
159                white-list = true;
160                enable-rcon = true;
161                "rcon.password" = "hunter2";
162              }
163            '';
164            description = ''
165              Minecraft server properties for the server.properties file of this server. See
166              <link xlink:href="https://minecraft.gamepedia.com/Server.properties#Java_Edition_3"/>
167              for documentation on these values.
168            '';
169          };
170
171          package = mkOption {
172            description = "The Minecraft server package to use.";
173            type = types.package;
174            default = pkgs.minecraft-server;
175            defaultText = literalExpression "pkgs.minecraft-server";
176            example = "pkgs.minecraftServers.vanilla-1_18_2";
177          };
178
179          jvmOpts = mkOpt' (types.separatedString " ") "-Xmx2G -Xms1G" "JVM options for this server.";
180
181          symlinks = mkOpt' (types.attrsOf types.package) { } ''
182            Things to symlink into this server's data directory, in the form of
183            a nix package/derivation. Can be used to declaratively manage
184            arbitrary files in the server's data directory.
185          '';
186        };
187      });
188    };
189  };
190
191  config = mkIf cfg.enable
192    (
193      let
194        servers = filterAttrs (_: cfg: cfg.enable) cfg.servers;
195      in
196      {
197        users = {
198          users.minecraft = {
199            description = "Minecraft server service user";
200            home = cfg.dataDir;
201            isSystemUser = true;
202            group = "minecraft";
203          };
204          groups.minecraft = { };
205        };
206
207        assertions = [
208          {
209            assertion = cfg.eula;
210            message = "You must agree to Mojangs EULA to run minecraft-servers."
211              + " Read https://account.mojang.com/documents/minecraft_eula and"
212              + " set `services.minecraft-servers.eula` to `true` if you agree.";
213          }
214          {
215            assertion = !config.services.minecraft-server.enable && cfg.dataDir != config.services.minecraft-server.dataDir;
216            message = "`services.minecraft-servers.dataDir` and `services.minecraft-server.dataDir` conflict."
217              + " Set one to use a different data directory.";
218          }
219          {
220            assertion =
221              let
222                serverPorts = mapAttrsToList
223                  (name: conf: conf.serverProperties.server-port or 25565)
224                  (filterAttrs (_: cfg: cfg.openFirewall) servers);
225
226                counts = map (port: count (x: x == port) serverPorts) (unique serverPorts);
227              in
228              lib.all (x: x == 1) counts;
229          }
230        ];
231
232        networking.firewall =
233          let
234            toOpen = filterAttrs (_: cfg: cfg.openFirewall) servers;
235            UDPPorts = mapAttrsToList (name: conf: conf.serverProperties.server-port or 25565) toOpen;
236            TCPPorts = concatLists
237              (mapAttrsToList
238                (name: conf: with conf;
239                (optional (serverProperties.enable-rcon or false) (serverProperties."rcon.port" or 25575)) ++
240                (optional (serverProperties.enable-query or false) (serverProperties."query.port" or 25565))
241                )
242                toOpen
243              );
244          in
245          rec {
246            allowedUDPPorts = UDPPorts;
247            allowedTCPPorts = UDPPorts ++ TCPPorts;
248          };
249
250        system.activationScripts.minecraft-server-data-dir.text = ''
251          mkdir -p ${cfg.dataDir}
252          chown minecraft:minecraft ${cfg.dataDir}
253          chmod -R 775 ${cfg.dataDir}
254        '';
255
256        systemd.services = mapAttrs'
257          (name: conf:
258            let
259              serverDir = "${cfg.dataDir}/${name}";
260              runner = "${getBin pkgs.abduco}/bin/abduco";
261              socket = "${cfg.runDir}/${name}.sock";
262
263              startScript = pkgs.writeScript "minecraft-start-${name}" ''
264                #!${pkgs.runtimeShell}
265
266                umask u=rwx,g=rwx,o=rx
267                cd ${serverDir}
268                ${runner} -c ${socket} ${conf.package}/bin/minecraft-server ${conf.jvmOpts}
269              '';
270
271              stopScript = pkgs.writeScript "minecraft-stop-${name}" ''
272                #!${pkgs.runtimeShell}
273
274                if ! [ -d "/proc/$1" ]; then
275                  exit 0
276                fi
277
278                echo "stop" | ${runner} -p -a ${socket}
279              '';
280            in
281            {
282              name = "minecraft-server-${name}";
283              value = {
284                description = "Minecraft Server ${name}";
285                wantedBy = mkIf conf.autoStart [ "multi-user.target" ];
286                after = [ "network.target" ];
287
288                enable = conf.enable;
289
290                serviceConfig = {
291                  ExecStart = "${startScript}";
292                  ExecStop = "${stopScript} $MAINPID";
293                  Restart = conf.restart;
294                  User = "minecraft";
295                  Type = "forking";
296                  GuessMainPID = true;
297                  RuntimeDirectory = "minecraft";
298                };
299
300                preStart =
301                  let
302                    eula = builtins.toFile "eula.txt" ''
303                      # eula.txt managed by NixOS Configuration
304                      eula=true
305                    '';
306
307                    whitelist = pkgs.writeText "whitelist.json"
308                      (builtins.toJSON
309                        (mapAttrsToList (n: v: { name = n; uuid = v; }) conf.whitelist));
310
311                    serverProperties =
312                      let
313                        cfgToString = v: if builtins.isBool v then boolToString v else toString v;
314                      in
315                      pkgs.writeText "server.properties" (''
316                        # server.properties managed by NixOS configuration
317                      '' + concatStringsSep "\n" (mapAttrsToList
318                        (n: v: "${n}=${cfgToString v}")
319                        conf.serverProperties));
320
321                    mkSymlinks = pkgs.writeShellScript "minecraft-server-${name}-symlinks"
322                      (concatStringsSep "\n"
323                        (mapAttrsToList
324                          (n: v: ''
325                            if [[ -L "${n}" ]]; then
326                              unlink ${n}
327                            elif [[ -e "${n}" ]]; then
328                              echo "${n} already exists, moving"
329                              mv "${n}" "${n}.bak"
330                            fi
331                            ln -sf ${v} ${n}
332                          '')
333                          conf.symlinks));
334                  in
335                  ''
336                    umask u=rwx,g=rwx,o=rx
337                    mkdir -p ${serverDir}
338                    cd ${serverDir}
339                    ln -sf ${eula} eula.txt
340                    ${if conf.whitelist != {} then "ln -sf ${whitelist} whitelist.json" else ""}
341                    ${if conf.serverProperties != {} then "cp -f ${serverProperties} server.properties" else ""}
342                    ${mkSymlinks}
343                  '';
344
345                postStart = ''
346                  ${pkgs.coreutils}/bin/chmod 660 ${socket}
347                '';
348              };
349            })
350          servers;
351      }
352    );
353}