Files
tidewall/src/server/server_config.gd
T
claudeandClaude Opus 5.5 8eb6e587fb N7: Dedicated server packaging, health endpoint and graceful shutdown
- packaging/server/tidewall-server: a wrapper that turns SIGTERM and SIGINT
  into a clean stop through the server's new --stop-file, since the engine
  can't catch signals. The server tells everyone it shut down, logs its
  statistics and exits 0; the wrapper kills it only after 15 s.
- --config=PATH reads options from a file (packaging/server/server.cfg);
  options after it on the command line win.
- --health-port answers GET /health with JSON (phase, players, tick, uptime)
  on loopback by default. HealthServer is non-blocking and bounded.
- packaging/docker: a debian:13 image that checks the engine against
  tools/engine.sha512, imports the game at build time, runs as an unprivileged
  user, and works with a read-only root and a small /tmp. compose.yaml is
  project and container tidewall-server, read-only, no capabilities.
- packaging/systemd: a hardened unit with a dynamic user.
- make server-package-check: compose up, healthy, non-root, read-only, a real
  headless client joins over UDP into the drop, then SIGTERM stops it cleanly.

This also covers H7 (graceful shutdown on SIGTERM).

Closes #38
Closes #70

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 22:07:24 -05:00

277 lines
9.9 KiB
GDScript

## Command-line configuration for a headless server.
##
## tools/godot.sh -- --server [--listen] [--port=N] [--seed=N] [--players=N] [--bots=N]
## [--bot-difficulty=mixed|easy|normal|hard] [--ticks=N]
## [--unthrottled] [--log-every=N] [--matches=N] [--world-hash-every=N]
## [--name=NAME] [--list=HOST[:PORT]]... [--no-lan]
## [--health-port=N] [--health-bind=ADDRESS] [--stop-file=PATH]
## [--config=PATH]
##
## `--config` reads options from a file, one per line, written without the leading
## dashes: `port = 24650`, or a bare `listen` for a switch. Blank lines and lines
## starting with # are skipped. Options after `--config` on the command line win.
## See packaging/server/server.cfg.
##
## `--health-port` answers `GET /health` over HTTP on that TCP port (HealthServer), on
## `--health-bind`, loopback by default. `--stop-file` makes the server stop cleanly,
## telling everyone connected, as soon as that file exists: the packaging's wrapper
## creates it on SIGTERM, which the engine itself can't catch.
##
## With `--listen` the server takes network players on UDP `--port`, waits in the lobby
## for the first of them, and with any `--bots` above 0 fills each match's empty places
## with bots. Without it the match starts at once with `--players` idle slots.
##
## A listening server answers LAN discovery on its port plus one unless `--no-lan`,
## and registers with each `--list` server (see ListServer) under `--name`.
##
## Unknown or malformed arguments are errors, so a typo can't silently run the wrong
## match. See `parse()`.
class_name ServerConfig
extends RefCounted
const DEFAULT_PORT: int = 24650
## The `--fault` names `HeadlessServer` understands. They exist so tools/smoke.sh can
## prove a script error really produces a non-zero exit.
const FAULTS: Array[String] = ["", "script-error"]
## True when `--server` was given.
var server: bool = false
## The match seed. `has_seed` is false when none was given and the server must pick one.
var match_seed: int = 0
var has_seed: bool = false
## True when `--listen` was given: take network players on `port`.
var listen: bool = false
## UDP port a listening server uses.
var port: int = DEFAULT_PORT
## Idle player slots, for a server that isn't listening.
var players: int = 0
var bots: int = 0
## Every bot's difficulty, as an index into Tuning.BOT_DIFFICULTIES, or -1 to mix them.
var bot_difficulty: int = -1
## Ticks to run before exiting. 0 runs until the process is stopped.
var ticks: int = 0
## Stops after this many matches have ended. 0 doesn't stop for matches.
var matches: int = 0
## On the simulation ticks from each multiple of this many up to the snapshot interval
## (never tick 0, which lasts the whole lobby), logs NetWorld.world_hash() of the match's
## world, so a soak test can compare it with its clients' copies. 0 turns it off.
var world_hash_every: int = 0
## Runs ticks back to back instead of at the real tick rate. For tests and smoke runs.
var unthrottled: bool = false
## Logs a progress line every this many ticks. 0 turns progress lines off.
var log_every: int = 0
var fault: String = ""
## The name shown in server lists.
var server_name: String = NetDiscovery.DEFAULT_SERVER_NAME
## List servers to register with: {"host", "port"}. Hosts may be names.
var lists: Array[Dictionary] = []
## Answer LAN discovery. On by default for a listening server.
var lan: bool = true
## TCP port for the health endpoint; 0 for none.
var health_port: int = 0
var health_bind: String = "127.0.0.1"
## A file whose appearance asks the server to stop; empty for none.
var stop_file: String = ""
## Human-readable problems found while parsing. Empty when the config is usable.
var errors: Array[String] = []
## Parses arguments. Arguments before `--server` are ignored unless `--server` is absent,
## in which case nothing is parsed and `server` stays false.
static func parse(args: PackedStringArray) -> ServerConfig:
var config: ServerConfig = ServerConfig.new()
var start: int = args.find("--server")
if start < 0:
return config
config.server = true
for index: int in range(start + 1, args.size()):
var arg: String = args[index]
if arg.begins_with("--config="):
for from_file: String in config._read_file(arg.substr("--config=".length())):
config._parse_one(from_file)
else:
config._parse_one(arg)
config._validate()
return config
func is_valid() -> bool:
return errors.is_empty()
## The values that matter for reproducing a run, for the start log line.
func to_dictionary() -> Dictionary:
return {
"seed": match_seed,
"listen": listen,
"port": port,
"players": players,
"bots": bots,
"bot_difficulty": "mixed" if bot_difficulty < 0 else String(Tuning.BOT_DIFFICULTIES[bot_difficulty]["name"]),
"ticks": ticks,
"matches": matches,
"unthrottled": unthrottled,
"name": server_name,
"lan": lan and listen,
"lists": lists.size(),
}
func _parse_one(arg: String) -> void:
if arg == "--unthrottled":
unthrottled = true
return
if arg == "--listen":
listen = true
return
if arg == "--no-lan":
lan = false
return
var parts: PackedStringArray = arg.split("=", true, 1)
if parts.size() != 2 or not arg.begins_with("--"):
errors.append("unknown argument '%s'" % arg)
return
var key: String = parts[0]
var value: String = parts[1]
match key:
"--seed":
if _check_int(key, value):
match_seed = value.to_int()
has_seed = true
"--port":
if _check_int(key, value):
port = value.to_int()
"--players":
if _check_int(key, value):
players = value.to_int()
"--bots":
if _check_int(key, value):
bots = value.to_int()
"--ticks":
if _check_int(key, value):
ticks = value.to_int()
"--log-every":
if _check_int(key, value):
log_every = value.to_int()
"--matches":
if _check_int(key, value):
matches = value.to_int()
"--world-hash-every":
if _check_int(key, value):
world_hash_every = value.to_int()
"--bot-difficulty":
var found: bool = value == "mixed"
for index: int in Tuning.BOT_DIFFICULTIES.size():
if Tuning.BOT_DIFFICULTIES[index]["name"] == value:
bot_difficulty = index
found = true
if not found:
errors.append("--bot-difficulty must be mixed, easy, normal or hard, got '%s'" % value)
"--fault":
fault = value
"--health-port":
if _check_int(key, value):
health_port = value.to_int()
"--health-bind":
if not value.is_valid_ip_address():
errors.append("--health-bind needs an IP address, got '%s'" % value)
else:
health_bind = value
"--stop-file":
stop_file = value
"--name":
server_name = NetDiscovery.clean_server_name(value)
"--list":
var target: Dictionary = parse_host_port(value, NetDiscovery.DEFAULT_LIST_PORT)
if target.is_empty():
errors.append("--list needs HOST or HOST:PORT with a port from 1 to 65535, got '%s'" % value)
else:
lists.append(target)
_:
errors.append("unknown argument '%s'" % arg)
## {"host", "port"} from "HOST" or "HOST:PORT", or empty if it doesn't parse. An
## IPv6 address goes in brackets when it has a port: "[::1]:24660".
static func parse_host_port(text: String, default_port: int) -> Dictionary:
var host: String = text
var port: int = default_port
if text.begins_with("["):
var close: int = text.find("]")
if close < 0:
return {}
host = text.substr(1, close - 1)
var rest: String = text.substr(close + 1)
if not rest.is_empty():
if not rest.begins_with(":") or not rest.substr(1).is_valid_int():
return {}
port = rest.substr(1).to_int()
elif text.count(":") == 1:
var at: int = text.find(":")
host = text.substr(0, at)
if not text.substr(at + 1).is_valid_int():
return {}
port = text.substr(at + 1).to_int()
if host.is_empty() or port < 1 or port > 65535:
return {}
return {"host": host, "port": port}
## The options in a config file, as command-line arguments.
func _read_file(path: String) -> Array[String]:
var args: Array[String] = []
var file: FileAccess = FileAccess.open(path, FileAccess.READ)
if file == null:
errors.append("couldn't read the config file '%s': %s" % [path, error_string(FileAccess.get_open_error())])
return args
var number: int = 0
while not file.eof_reached():
number += 1
var line: String = file.get_line().strip_edges()
if line.is_empty() or line.begins_with("#"):
continue
if line.begins_with("config"):
errors.append("%s:%d: a config file can't include another" % [path, number])
continue
var at: int = line.find("=")
if at < 0:
args.append("--" + line)
else:
args.append("--%s=%s" % [line.substr(0, at).strip_edges(), line.substr(at + 1).strip_edges()])
return args
func _check_int(key: String, value: String) -> bool:
if value.is_valid_int():
return true
errors.append("%s needs a whole number, got '%s'" % [key, value])
return false
func _validate() -> void:
if port < 1 or port > 65535:
errors.append("--port must be between 1 and 65535, got %d" % port)
if players < 0 or bots < 0:
errors.append("--players and --bots can't be negative")
if players + bots > Tuning.SOLO_PLAYERS:
errors.append(
"--players plus --bots is %d, more than the match size of %d"
% [players + bots, Tuning.SOLO_PLAYERS]
)
if listen and players > 0:
errors.append("--players is for a server that isn't listening; with --listen, people join over the network")
if ticks < 0:
errors.append("--ticks can't be negative")
if log_every < 0:
errors.append("--log-every can't be negative")
if matches < 0 or world_hash_every < 0:
errors.append("--matches and --world-hash-every can't be negative")
if world_hash_every > 0 and not listen:
errors.append("--world-hash-every is for a server started with --listen")
if not listen and (not lists.is_empty() or not lan):
errors.append("--list and --no-lan are for a server started with --listen")
if health_port < 0 or health_port > 65535:
errors.append("--health-port must be between 1 and 65535, or 0 for none, got %d" % health_port)
if fault not in FAULTS:
errors.append("unknown --fault '%s'" % fault)