fork/nix-minecraft
git clone https://git.julia.blue/fork/nix-minecraft
ff6604f
master
1{ 2config , 3lib , 4options , 5pkgs , 6 ... 7} : 8with lib ; 9let 10cfg = config . services . minecraft-servers ; 11 12mkOpt = type :default :mkOption { inherit type default ; }; 13 14mkOpt' = 15type :default :description : 16mkOption { inherit type default description ; }; 17 18mkBoolOpt = 19default : 20mkOption { 21inherit default ; 22type = types . bool ; 23example = true ; 24}; 25 26mkBoolOpt' = 27default :description : 28mkOption { 29inherit default description ; 30type = types . bool ; 31example = true ; 32}; 33 34minecraftUUID = 35types . strMatching "([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{32})" 36// { 37description = "Minecraft UUID" ; 38}; 39 40normalizeFiles = files :mapAttrs configToPath ( filterAttrs ( _ :nonEmptyValue ) files ); 41nonEmptyValue = x :nonEmpty x && ( x ?value -> nonEmpty x . value ); 42nonEmpty = x :x != { } && x != [ ]; 43 44configToPath = 45name :config : 46if 47isStringLike config # Includes paths and packages 48then 49config 50else 51( getFormat name config ). generate name config . value ; 52getFormat = 53name :config :if config ?format && config . format != null then config . format else inferFormat name ; 54inferFormat = 55name : 56let 57error = throw "nix-minecraft: Could not infer format from file ' ${ name } '. Specify one using 'format'." ; 58extension = builtins . match "[^.]*\\.(.+)" name ; 59in 60if extension != null && extension != [ ] then 61formatExtensions .${ head extension } or error 62else 63error ; 64 65txtList = 66{ } : 67{ 68type = with lib . types ; listOf str ; 69generate = name :value :pkgs . writeText name ( lib . concatStringsSep "\n" value ); 70}; 71 72formatExtensions = with pkgs . formats ; { 73"yml" = yaml { }; 74"yaml" = yaml { }; 75"json" = json { }; 76"props" = keyValue { }; 77"properties" = keyValue { }; 78"toml" = toml { }; 79"ini" = ini { }; 80"txt" = txtList { }; 81}; 82 83configType = types . submodule { 84options = { 85format = mkOption { 86type = with types ; nullOr attrs ; 87default = null ; 88description = '' 89The format to use when converting "value" into a file. If set to 90null (the default), we'll try to infer it from the file name. 91'' ; 92example = literalExpression "pkgs.formats.yaml { }" ; 93}; 94value = mkOption { 95type = with types ; either ( attrsOf anything ) ( listOf anything ); 96description = '' 97A value that can be converted into the specified format. 98'' ; 99}; 100}; 101}; 102 103managementSystem = types . submodule { 104options = { 105tmux = { 106enable = mkEnableOption "management via a TMUX socket" ; 107socketPath = mkOption { 108type = with types ; functionTo path ; 109description = '' 110Function from a server name to the path at which the server's tmux socket is placed. 111To connect to the console, run `tmux -S <path to socket> attach`, 112press `Ctrl + b` then `d` to detach. 113 114Note that while currently the default respects <option>services.minecraft-servers.runDir</option>, 115that option is deprecated and will be removed. 116The default will then change to `name: "/run/minecraft/''${name}.sock`. 117'' ; 118default = name :" ${ cfg . runDir } / ${ name } .sock" ; 119defaultText = literalExpression ''name: "''${cfg.runDir}/''${name}.sock"'' ; 120}; 121}; 122systemd-socket = { 123enable = mkEnableOpt "management through the systemd journal & a command socket" ; 124stdinSocket = { 125path = mkOption { 126type = with types ; functionTo path ; 127description = '' 128Function from a server name to the path at which the server's stdin socket is placed. 129You can send the server commands by writing to this socket, 130for example with shell redirection: `echo 'list' > <path to socket>`. 131 132Note that while currently the default respects <option>services.minecraft-servers.runDir</option>, 133that option is deprecated and will be removed. 134The default will then change to `name: "/run/minecraft/''${name}.stdin`. 135'' ; 136default = name :" ${ cfg . runDir } / ${ name } .stdin" ; 137defaultText = literalExpression ''name: "''${cfg.runDir}/''${name}.stdin"'' ; 138}; 139mode = mkOption { 140type = types . strMatching "[0-7]{4}" ; 141description = "Access mode of the socket file in octal notation" ; 142default = "0660" ; 143}; 144}; 145}; 146}; 147}; 148 149managementSystemConfig = 150name :server : 151let 152ms = server . managementSystem ; 153tmux = " ${ getBin pkgs . tmux } /bin/tmux" ; 154in 155assert assertMsg ( 156! ( ms . tmux . enable && ms . systemd-socket . enable ) 157) "Only one server management system can be enabled at a time." ; 158if ms . tmux . enable then 159let 160sock = ms . tmux . socketPath name ; 161in 162{ 163serviceConfig = { 164Type = "forking" ; 165GuessMainPID = true ; 166}; 167hooks = { 168start = '' 169${ tmux } -S ${ sock } new -d ${ getExe server . package } ${ server . jvmOpts } 170 171# HACK: PrivateUsers makes every user besides root/minecraft `nobody`, so this restores old tmux behavior 172# See https://github.com/Infinidoge/nix-minecraft/issues/5 173${ tmux } -S ${ sock } server-access -aw nobody 174'' ; 175postStart = '' 176${ pkgs . coreutils } /bin/chmod 660 ${ sock } 177'' ; 178stop = '' 179function server_running { 180${ tmux } -S ${ sock } has-session 181} 182 183if ! server_running ; then 184exit 0 185fi 186 187${ tmux } -S ${ sock } send-keys C-u ${ escapeShellArg server . stopCommand } Enter 188 189while server_running; do sleep 1s; done 190'' ; 191}; 192} 193else if ms . systemd-socket . enable then 194{ 195serviceConfig = { 196Type = "simple" ; 197StandardInput = "socket" ; 198StandardOutput = "journal" ; 199StandardError = "journal" ; 200}; 201hooks = { 202start = '' 203${ getExe server . package } ${ server . jvmOpts } 204'' ; 205postStart = "" ; 206stop = '' 207${ optionalString ( server . stopCommand != null ) '' 208echo ${ escapeShellArg server . stopCommand } > ${ escapeShellArg ( ms . systemd-socket . stdinSocket . path name )} 209 210while kill -0 "$1" 2> /dev/null; do sleep 1s; done 211'' } 212'' ; 213}; 214} 215else 216builtins . throw "At least one server management system must be enabled." ; 217 218mkEnableOpt = description :mkBoolOpt' false description ; 219in 220{ 221options . services . minecraft-servers = { 222enable = mkEnableOpt '' 223If enabled, the servers in <option>services.minecraft-servers.servers</option> 224will be created and started as applicable. 225The data for the servers will be loaded from and 226saved to <option>services.minecraft-servers.dataDir</option> 227'' ; 228 229eula = mkEnableOpt '' 230Whether you agree to 231<link xlink:href="https://account.mojang.com/documents/minecraft_eula"> 232Mojang's EULA</link>. This option must be set to 233<literal>true</literal> to run Minecraft server. 234'' ; 235 236openFirewall = mkEnableOpt '' 237Whether to open ports in the firewall for each server. 238Sets the default for <option>services.minecraft-servers.servers.<name>.openFirewall</option>. 239'' ; 240 241dataDir = mkOpt' types . path "/srv/minecraft" '' 242Directory to store the Minecraft servers. 243Each server will be under a subdirectory named after 244the server name in this directory, such as <literal>/srv/minecraft/servername</literal>. 245'' ; 246 247runDir = mkOpt' types . path "/run/minecraft" '' 248Deprecated: Directory to place the runtime tmux sockets into. 249Each server's console will be a tmux socket file in the form of <literal>servername.sock</literal>. 250To connect to the console, run `tmux -S /run/minecraft/servername.sock attach`, 251press `Ctrl + b` then `d` to detach. 252 253Plase use <option>services.minecraft-servers.managementSystem.tmux.socketPath</option>` instead. 254'' ; 255 256user = mkOption { 257type = types . str ; 258default = "minecraft" ; 259description = '' 260Name of the user to create and run servers under. 261It is recommended to leave this as the default, as it is 262the same user as <option>services.minecraft-server</option>. 263'' ; 264internal = true ; 265visible = false ; 266}; 267 268group = mkOption { 269type = types . str ; 270default = "minecraft" ; 271description = '' 272Name of the group to create and run servers under. 273In order to modify the server files your user must be a part of this 274group. If you are using the tmux management system (the default), you also need to be a part of this group to attach to the tmux socket. 275It is recommended to leave this as the default, as it is 276the same group as <option>services.minecraft-server</option>. 277'' ; 278}; 279 280environmentFile = mkOpt' ( types . nullOr types . path ) null '' 281File consisting of lines in the form varname=value to define environment 282variables for the minecraft servers. 283 284Secrets (database passwords, secret keys, etc.) can be provided to server 285files without adding them to the Nix store by defining them in the 286environment file and referring to them in option 287<option>services.minecraft-servers.servers.<name>.files</option> with the 288syntax @varname@. 289'' ; 290 291managementSystem = mkOption { 292type = managementSystem ; 293description = '' 294The default management system for all servers. 295'' ; 296default = { 297tmux . enable = true ; 298}; 299example = '' 300{ 301tmux.enable = false; 302systemd-socket.enable = true; 303} 304'' ; 305}; 306 307servers = mkOption { 308default = { }; 309description = '' 310Servers to create and manage using this module. 311Each server can be stopped with <literal>systemctl stop minecraft-server-servername</literal>. 312::: {.warning} 313If the server is not stopped using `systemctl`, the service will automatically restart the server. 314See <option>services.minecraft-servers.servers.<name>.restart</option>. 315::: 316'' ; 317type = types . attrsOf ( 318types . submodule ( 319{ name , ...} : 320{ 321options = { 322enable = mkEnableOpt '' 323Whether to enable this server. 324If set to <literal>false</literal>, does NOT delete any data in the data directory, 325just does not generate the service file. 326'' ; 327 328autoStart = mkBoolOpt' true '' 329Whether to start this server on boot. 330If set to <literal>false</literal>, can still be started with 331<literal>systemctl start minecraft-server-servername</literal>. 332Requires the server to be enabled. 333'' ; 334 335openFirewall = mkOption { 336type = types . bool ; 337default = cfg . openFirewall ; 338defaultText = "The value of <literal>services.minecraft-servers.openFirewall</literal>" ; 339description = '' 340Whether to open ports in the firewall for this server. 341'' ; 342}; 343 344restart = mkOpt' types . str "always" '' 345Value of systemd's <literal>Restart=</literal> service configuration option. 346If you are using the tmux management system (the default), values other than 347<literal>"no"</literal> and <literal>"always"</literal> may not work properly. 348As a consequence of the <literal>"always"</literal> option, stopping the server 349in-game with the <literal>stop</literal> command will cause the server to automatically restart. 350'' ; 351 352enableReload = mkOpt' types . bool false '' 353Reload server when configuration changes (instead of restart). 354 355This action re-links/copies the declared symlinks/files. You can 356include additional actions (even in-game commands) by setting 357<option>services.minecraft-servers.<name>.extraReload</option>. 358'' ; 359 360extraReload = mkOpt' types . lines "" '' 361Extra commands to run when reloading the service. Only has an 362effect if 363<option>services.minecraft-servers.<name>.enableReload</option> is 364true. 365'' ; 366 367extraStartPre = mkOpt' types . lines "" '' 368Extra commands to run before starting the service. 369'' ; 370 371extraStartPost = mkOpt' types . lines "" '' 372Extra commands to run after starting the service. 373'' ; 374 375extraStopPre = mkOpt' types . lines "" '' 376Extra commands to run before stopping the service. 377'' ; 378 379extraStopPost = mkOpt' types . lines "" '' 380Extra commands to run after stopping the service. 381'' ; 382 383stopCommand = mkOption { 384type = types . nullOr types . str ; 385description = '' 386Console command to run when cleanly stopping the server (ExecStop). 387Defaults to <literal>stop</literal>, which works for most servers. 388For proxies (bungeecord, velocity), you should set 389<literal>end</literal>. 390 391If set to <literal>null</literal>, the server will be stopped by 392systemd without issuing any command. 393'' ; 394default = "stop" ; 395}; 396 397whitelist = mkOption { 398type = types . attrsOf minecraftUUID ; 399default = { }; 400description = '' 401Whitelisted players, only has an effect when 402enabled via <option>services.minecraft-servers.<name>.serverProperties</option> 403by setting <literal>white-list</literal> to <literal>true</literal. 404 405To use a non-declarative whitelist, enable the whitelist and don't fill in this value. 406As long as it is empty, no whitelist file is generated. 407'' ; 408example = literalExpression '' 409{ 410username1 = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; 411username2 = "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy"; 412} 413'' ; 414}; 415 416operators = mkOption { 417type = types . attrsOf ( 418types . coercedTo minecraftUUID ( v :{ uuid = v ; }) ( 419types . submodule { 420options = { 421uuid = mkOption { 422type = minecraftUUID ; 423description = "The operator's UUID" ; 424example = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" ; 425}; 426level = mkOption { 427type = types . ints . between 0 4 ; 428description = "The operator's permission level" ; 429default = 4 ; 430}; 431bypassesPlayerLimit = mkOption { 432type = types . bool ; 433description = "If true, the operator can join the server even if the player limit has been reached" ; 434default = false ; 435}; 436}; 437} 438) 439); 440default = { }; 441description = '' 442Server operators. See <link xlink:href="https://minecraft.wiki/w/Ops.json_format"/>. 443 444To use a non-declarative operator list, don't fill in this value. 445As long as it is empty, no operators file is generated. 446'' ; 447example = literalExpression '' 448{ 449username1 = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; 450username2 = { 451uuid = "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy"; 452level = 3; 453bypassesPlayerLimit = true; 454}; 455} 456'' ; 457}; 458 459bannedPlayers = mkOption { 460type = types . attrsOf ( 461types . coercedTo minecraftUUID ( v :{ uuid = v ; }) ( 462types . submodule { 463options = { 464uuid = mkOption { 465type = minecraftUUID ; 466description = "The banned player's UUID" ; 467example = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" ; 468}; 469created = mkOption { 470type = lib . types . nullOr lib . types . str ; 471description = "The date of the ban" ; 472default = null ; 473example = "2025-12-01 09:00:00 -0500" ; 474}; 475source = mkOption { 476type = lib . types . nullOr lib . types . str ; 477description = "The source of the ban" ; 478default = null ; 479example = "Server" ; 480}; 481expires = mkOption { 482type = lib . types . nullOr lib . types . str ; 483description = "When the ban expires, if ever" ; 484default = null ; 485example = "forever" ; 486}; 487reason = mkOption { 488type = lib . types . nullOr lib . types . str ; 489description = "The reason for the ban, if any." ; 490default = null ; 491example = "Banned by an operator." ; 492}; 493}; 494} 495) 496); 497default = { }; 498description = '' 499Banned players. See <link xlink:href="https://docs.papermc.io/paper/reference/vanilla-data-files/"/>. 500 501To use a non-declarative banned player list, don't fill in this value. 502As long as it is empty, no banned players file is generated. 503'' ; 504example = literalExpression '' 505{ 506username1 = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; 507username2 = { 508uuid = "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy"; 509created = "2025-12-01 09:00:00 -0500"; 510source = "(Unknown)"; 511expires = "forever"; 512reason = "Banned by an operator."; 513}; 514} 515'' ; 516}; 517 518serverProperties = mkOption { 519type = 520with types ; 521attrsOf ( oneOf [ 522bool 523int 524str 525]); 526default = { }; 527example = literalExpression '' 528{ 529server-port = 43000; 530difficulty = 3; 531gamemode = 1; 532max-players = 5; 533motd = "NixOS Minecraft server!"; 534white-list = true; 535enable-rcon = true; 536"rcon.password" = "hunter2"; 537} 538'' ; 539description = '' 540Minecraft server properties for the server.properties file of this server. See 541<link xlink:href="https://minecraft.gamepedia.com/Server.properties#Java_Edition_3"/> 542for documentation on these values. 543 544To use a non-declarative server.properties, don't fill in this value. 545As long as it is empty, no server.properties file is generated. 546'' ; 547}; 548 549allowedSymlinks = mkOption { 550default = [ ]; 551type = with types ; listOf str ; 552example = literalExpression '' 553[ 554"/mnt/worlds" 555] 556'' ; 557description = '' 558Minecraft 1.20+ disallows symlinks inside world directories, unless 559its destinations are allow-listed. /nix/store is allowed by default, 560but you may add more destinations through this option. See 561<link xlink:href="https://help.minecraft.net/hc/en-us/articles/16165590199181"/> 562for more information. 563 564Use lib.mkForce to shadow the default value (i.e. if you want to exclude /nix/store). 565'' ; 566}; 567 568package = mkOption { 569description = "The Minecraft server package to use." ; 570type = types . package ; 571default = pkgs . minecraft-server ; 572defaultText = literalExpression "pkgs.minecraft-server" ; 573example = "pkgs.minecraftServers.vanilla-1_18_2" ; 574}; 575 576jvmOpts = mkOpt' ( 577with types ; coercedTo ( listOf str ) ( lib . concatStringsSep " " ) ( separatedString " " ) 578) "-Xmx2G -Xms1G" "JVM options for this server." ; 579 580path = 581with types ; 582mkOpt' ( listOf ( either path str )) [ ] '' 583Packages added to the Minecraft server's <literal>PATH</literal> environment variable. 584Works as <option>systemd.services.<name>.path</option>. 585'' ; 586 587environment = 588with types ; 589mkOpt' 590( attrsOf ( 591nullOr ( oneOf [ 592str 593path 594package 595]) 596)) 597{ } 598'' 599Environment variables added to the Minecraft server's processes. 600Works as <option>systemd.services.<name>.environment</option>. 601'' ; 602 603symlinks = 604with types ; 605mkOpt' ( attrsOf ( either path configType )) { } '' 606Things to symlink into this server's data directory, in the form of 607a nix package/derivation. Can be used to declaratively manage 608arbitrary files in the server's data directory. 609'' ; 610files = 611with types ; 612mkOpt' ( attrsOf ( either path configType )) { } '' 613Things to copy into this server's data directory. Similar to symlinks, 614but these are actual, writable, files. Useful for configuration files 615that don't behave well when read-only. Directories are copied recursively and 616dereferenced. They will be deleted after the server stops, so any modification 617is discarded. 618 619These files may include placeholders to substitute with values from 620<option>services.minecraft-servers.environmentFile</option> 621(i.e. @variable_name@). 622'' ; 623 624managementSystem = mkOption { 625type = types . submodule ( 626managementSystem . getSubModules 627++ [ 628{ config = mkDefault cfg . managementSystem ; } 629] 630); 631description = '' 632Configuration for the system used to manage this server. Overrides the global configuration on an option-by-option basis. 633'' ; 634default = { }; 635example = options . services . minecraft-servers . managementSystem . example ; 636}; 637}; 638 639config = { 640allowedSymlinks = [ "/nix/store" ]; 641}; 642} 643) 644); 645}; 646}; 647 648config = mkIf cfg . enable ( 649let 650servers = filterAttrs ( _ :cfg :cfg . enable ) cfg . servers ; 651in 652{ 653users = { 654users . minecraft = mkIf ( cfg . user == "minecraft" ) { 655description = "Minecraft server service user" ; 656home = cfg . dataDir ; 657createHome = true ; 658homeMode = "770" ; 659isSystemUser = true ; 660group = "minecraft" ; 661}; 662groups . minecraft = mkIf ( cfg . group == "minecraft" ) { }; 663}; 664 665assertions = [ 666{ 667assertion = cfg . eula ; 668message = 669"You must agree to Mojangs EULA to run minecraft-servers." 670+ " Read https://account.mojang.com/documents/minecraft_eula and" 671+ " set `services.minecraft-servers.eula` to `true` if you agree." ; 672} 673{ 674assertion = 675config . services . minecraft-server . enable -> cfg . dataDir != config . services . minecraft-server . dataDir ; 676message = 677"`services.minecraft-servers.dataDir` and `services.minecraft-server.dataDir` conflict." 678+ " Set one to use a different data directory." ; 679} 680{ 681assertion = 682let 683serverPorts = mapAttrsToList ( name :conf :conf . serverProperties . server-port or 25565 ) ( 684filterAttrs ( _ :cfg :cfg . openFirewall ) servers 685); 686 687counts = map ( port :count ( x :x == port ) serverPorts ) ( unique serverPorts ); 688in 689lib . all ( x :x == 1 ) counts ; 690message = "Multiple servers are set to use the same port. Change one to use a different port." ; 691} 692]; 693 694warnings = lib . optional ( cfg . runDir != options . services . minecraft-servers . runDir . default ) '' 695`runDir` has been deprecated. 696 697Please use `services.minecraft-servers.managementSystem.tmux.socketPath` instead. 698For example, `name: " ${ cfg . runDir } /''${name}.sock"`. 699 700See the changelog file for more information. 701'' ; 702 703networking . firewall = 704let 705toOpen = filterAttrs ( _ :cfg :cfg . openFirewall ) servers ; 706# Minecraft and RCON 707getTCPPorts = 708n :c : 709[ c . serverProperties . server-port or 25565 ] 710++ ( optional ( c . serverProperties . enable-rcon or false ) ( c . serverProperties . "rcon.port" or 25575 )); 711# Query 712getUDPPorts = 713n :c : 714optional ( c . serverProperties . enable-query or false ) ( c . serverProperties . "query.port" or 25565 ); 715in 716{ 717allowedUDPPorts = flatten ( mapAttrsToList getUDPPorts toOpen ); 718allowedTCPPorts = flatten ( mapAttrsToList getTCPPorts toOpen ); 719}; 720 721systemd . tmpfiles . rules = mapAttrsToList ( 722name :_ :"d ' ${ cfg . dataDir } / ${ name } ' 0770 ${ cfg . user } ${ cfg . group } - -" 723) servers ; 724 725systemd . sockets = pipe servers [ 726( filterAttrs ( name :server :server . managementSystem . systemd-socket . enable )) 727( mapAttrs' ( 728name :server :{ 729name = "minecraft-server- ${ name } " ; 730value = { 731requires = [ "minecraft-server- ${ name } .service" ]; 732partOf = [ "minecraft-server- ${ name } .service" ]; 733socketConfig = 734let 735socketConf = server . managementSystem . systemd-socket . stdinSocket ; 736in 737{ 738ListenFIFO = socketConf . path name ; 739SocketMode = socketConf . mode ; 740SocketUser = cfg . user ; 741SocketGroup = cfg . group ; 742RemoveOnStop = true ; 743FlushPending = true ; 744}; 745}; 746} 747)) 748]; 749 750systemd . services = mapAttrs' ( 751name :conf : 752let 753symlinks = normalizeFiles ( 754{ 755"eula.txt" . value = { 756eula = true ; 757}; 758"eula.txt" . format = pkgs . formats . keyValue { }; 759} 760// conf . symlinks 761); 762files = normalizeFiles ( 763{ 764"whitelist.json" . value = mapAttrsToList ( n :v :{ 765name = n ; 766uuid = v ; 767}) conf . whitelist ; 768"ops.json" . value = mapAttrsToList ( n :v :{ 769name = n ; 770uuid = v . uuid ; 771level = v . level ; 772bypassesPlayerLimit = v . bypassesPlayerLimit ; 773}) conf . operators ; 774"banned-players.json" . value = mapAttrsToList ( 775n :v : 776{ 777name = n ; 778uuid = v . uuid ; 779} 780// lib . optionalAttrs ( v . created != null ) { 781created = v . created ; 782} 783// lib . optionalAttrs ( v . source != null ) { 784source = v . source ; 785} 786// lib . optionalAttrs ( v . expires != null ) { 787expires = v . expires ; 788} 789// lib . optionalAttrs ( v . reason != null ) { 790reason = v . reason ; 791} 792) conf . bannedPlayers ; 793"server.properties" . value = conf . serverProperties ; 794"allowed_symlinks.txt" . value = conf . allowedSymlinks ; 795} 796// conf . files 797); 798 799msConfig = managementSystemConfig name conf ; 800 801markManaged = file :"echo ${ file } >> .nix-minecraft-managed" ; 802cleanAllManaged = '' 803if [ -e .nix-minecraft-managed ]; then 804readarray -t to_delete < .nix-minecraft-managed 805rm -rf "''${to_delete[@]}" 806rm .nix-minecraft-managed 807fi 808'' ; 809 810ExecStartPre = 811let 812backup = file :'' 813if [[ -e ${ file } ]]; then 814echo ${ file } "already exists, moving" 815mv ${ file } ${ file } .bak 816fi 817'' ; 818mkSymlinks = concatStringsSep "\n" ( 819mapAttrsToList ( 820n_ :v_ : 821let 822n = escapeShellArg n_ ; 823v = escapeShellArg v_ ; 824in 825'' 826${ backup n } 827mkdir -p "$(dirname ${ n } )" 828 829ln -sf ${ v } ${ n } 830 831${ markManaged n } 832'' 833) symlinks 834); 835 836mkFiles = concatStringsSep "\n" ( 837mapAttrsToList ( 838n_ :v_ : 839let 840n = escapeShellArg n_ ; 841v = escapeShellArg v_ ; 842in 843'' 844${ backup n } 845mkdir -p "$(dirname ${ n } )" 846 847# If it's not a binary, substitute env vars. Else, copy it normally 848if ${ pkgs . file } /bin/file --mime-encoding ${ v } | grep -v '\bbinary$' -q; then 849${ pkgs . gawk } /bin/awk '{ 850for(varname in ENVIRON) 851gsub("@"varname"@", ENVIRON[varname]) 852}' ${ v } > ${ n } 854else 855cp -r --dereference ${ v } -T ${ n } 856chmod +w -R ${ n } 857fi 858 859${ markManaged n } 860'' 861) files 862); 863in 864getExe ( 865pkgs . writeShellApplication { 866name = "minecraft-server- ${ name } -start-pre" ; 867 868excludeShellChecks = [ "SC2016" ]; 869 870text = '' 871${ cleanAllManaged } 872${ mkSymlinks } 873${ mkFiles } 874${ conf . extraStartPre } 875'' ; 876} 877); 878 879ExecStart = getExe ( 880pkgs . writeShellApplication { 881name = "minecraft-server- ${ name } -start" ; 882text = '' 883${ msConfig . hooks . start } 884'' ; 885} 886); 887 888ExecStartPost = getExe ( 889pkgs . writeShellApplication { 890name = "minecraft-server- ${ name } -start-post" ; 891text = '' 892${ msConfig . hooks . postStart } 893${ conf . extraStartPost } 894'' ; 895} 896); 897 898execStopScript = getExe ( 899pkgs . writeShellApplication { 900name = "minecraft-server- ${ name } -stop" ; 901text = '' 902# systemd has no ExecStopPre hook, so we just run it here. 903${ conf . extraStopPre } 904 905${ msConfig . hooks . stop } 906'' ; 907} 908); 909 910ExecStopPost = getExe ( 911pkgs . writeShellApplication { 912name = "minecraft-server- ${ name } -stop-post" ; 913text = '' 914${ cleanAllManaged } 915${ conf . extraStopPost } 916'' ; 917} 918); 919 920ExecReload = getExe ( 921pkgs . writeShellApplication { 922name = "minecraft-server- ${ name } -reload" ; 923text = '' 924${ ExecStopPost } 925${ ExecStartPre } 926${ conf . extraReload } 927'' ; 928} 929); 930in 931{ 932name = "minecraft-server- ${ name } " ; 933value = { 934description = "Minecraft Server ${ name } " ; 935wantedBy = mkIf conf . autoStart [ "multi-user.target" ]; 936requires = optional conf . managementSystem . systemd-socket . enable "minecraft-server- ${ name } .socket" ; 937partOf = optional conf . managementSystem . systemd-socket . enable "minecraft-server- ${ name } .socket" ; 938after = [ 939"network.target" 940] 941++ optional conf . managementSystem . systemd-socket . enable "minecraft-server- ${ name } .socket" ; 942 943enable = conf . enable ; 944 945startLimitIntervalSec = 120 ; 946startLimitBurst = 5 ; 947 948serviceConfig = { 949inherit 950ExecStartPre 951ExecStart 952ExecStartPost 953ExecStopPost 954ExecReload 955; 956ExecStop = " ${ execStopScript } $MAINPID" ; 957 958# the Minecraft server (as of 1.20.6) has a 60s timeout for saving each world. 959# let's let it handle potential lock-ups by itself before resorting to killing it. 960TimeoutStopSec = "1min 15s" ; 961 962Restart = conf . restart ; 963WorkingDirectory = " ${ cfg . dataDir } / ${ name } " ; 964User = cfg . user ; 965Group = cfg . group ; 966EnvironmentFile = mkIf ( cfg . environmentFile != null ) ( toString cfg . environmentFile ); 967 968# Default directory for management sockets 969RuntimeDirectory = "minecraft" ; 970RuntimeDirectoryPreserve = "yes" ; 971 972# Hardening 973CapabilityBoundingSet = [ "" ]; 974DeviceAllow = [ "" ]; 975LockPersonality = true ; 976PrivateDevices = true ; 977PrivateTmp = true ; 978PrivateUsers = true ; 979ProtectClock = true ; 980ProtectControlGroups = true ; 981ProtectHome = true ; 982ProtectHostname = true ; 983ProtectKernelLogs = true ; 984ProtectKernelModules = true ; 985ProtectKernelTunables = true ; 986ProtectProc = "invisible" ; 987RestrictAddressFamilies = [ 988"AF_UNIX" 989"AF_INET" 990"AF_INET6" 991]; 992RestrictNamespaces = true ; 993RestrictRealtime = true ; 994RestrictSUIDSGID = true ; 995SystemCallArchitectures = "native" ; 996UMask = "0007" ; 997} 998// msConfig . serviceConfig ; 999 1000restartIfChanged = ! conf . enableReload ; 1001reloadIfChanged = conf . enableReload ; 1002 1003inherit ( conf ) path environment ; 1004}; 1005} 1006) servers ; 1007} 1008); 1009}