Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
name: test

# Checks that need no GPU: file parsers, config handling, queue bookkeeping (tests/run_tests.gd) and the shell scripts.
on:
push:
branches: [main]
paths:
- "project.godot"
- "scripts/**"
- "tests/**"
- "docker/**"
- ".github/workflows/test.yml"
pull_request:
paths:
- "project.godot"
- "scripts/**"
- "tests/**"
- "docker/**"
- ".github/workflows/test.yml"

permissions:
contents: read

concurrency:
group: test-${{ github.ref }}
cancel-in-progress: true

jobs:
test:
runs-on: ubuntu-latest
env:
GODOT_VERSION: 4.7.2-stable
# from SHA512-SUMS.txt of the release
GODOT_SHA512: 9aa00f7a605200940bce3027a567b782f49bd8e940dd06ae9e987bd65aee1b1467edd56ed84fcdcbdd44354bf613bdbb4e5d2913e925850368e150c59ed54c65
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false

- name: Install Godot
run: |
f="Godot_v${GODOT_VERSION}_linux.x86_64.zip"
curl -fsSL -o "$RUNNER_TEMP/$f" "https://github.com/godotengine/godot-builds/releases/download/${GODOT_VERSION}/$f"
echo "$GODOT_SHA512 $RUNNER_TEMP/$f" | sha512sum -c -
unzip -q "$RUNNER_TEMP/$f" -d "$RUNNER_TEMP"
mv "$RUNNER_TEMP/Godot_v${GODOT_VERSION}_linux.x86_64" "$RUNNER_TEMP/godot"

- name: Import the project
run: timeout 300 "$RUNNER_TEMP/godot" --headless --path . --import

- name: Run the checks
run: timeout 300 "$RUNNER_TEMP/godot" --headless --path . -s tests/run_tests.gd

- name: Check the shell scripts
run: shellcheck -S warning docker/*.sh

- name: Check the compose example
working-directory: docker
run: |
# the files the example expects next to it are created by the operator
touch db_password
docker compose -f compose.watch.yaml config -q
22 changes: 18 additions & 4 deletions docker/compose.watch.yaml
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
# Resident map updater: ONE container for every map listed in ./maps.json (shape: docker/maps.example.json).
# Separate compose project, it does not touch the game stack:
# cd <dir with this file> && docker compose pull && docker compose up -d
# Needs next to this file: data/ (output of `build-data`), maps.json, state/ (writable: keeps what was seen and queued).
# Needs next to this file: data/ (output of `build-data`), maps.json, state/ (writable: keeps what was seen and queued),
# db_password (the database user's password, readable by the uid below and nobody else).
#
# Unprivileged: read-only root, no capabilities, 1 CPU at the lowest share, only the iGPU render node, world directories
# read-only. Renders only below --max-load, at most --max-megas mega tiles per batch, closest to a player first.
services:
watch:
image: ghcr.io/toro-server/toro-renderer:latest
command: ["watch", "--config", "/config/maps.json", "--state-dir", "/state"]
network_mode: host # the database is published on 127.0.0.1:4000
networks: [database]
restart: unless-stopped
user: "1002:1002" # any uid that may use the render node
group_add: ["993", "1001"] # gid of `render` (iGPU), gid that may read the world files
Expand All @@ -20,13 +21,26 @@ services:
security_opt: ["no-new-privileges:true"]
cpus: 1.0
cpu_shares: 32
mem_limit: 1536m
# The kernel charges the iGPU's buffers to this cgroup as shmem: about 1.2 GB while drawing, on top of about 400 MB of
# anonymous memory. A limit below that total gets the container OOM-killed over and over (every 70 s or so at 1536m).
mem_limit: 3g
pids_limit: 256
environment:
HOME: /tmp
# DYNMAP_DB_PASSWORD: ... # only when the database user has a password
secrets: [db_password]
volumes:
- ./data:/data:ro
- ./maps.json:/config/maps.json:ro
- ./state:/state
- /srv/minecraft/worlds:/worlds:ro # the directory holding the region folders named in maps.json

networks:
# An existing Docker network where the database answers as "tidb" (see "db" in maps.json).
# Named by the game stack's compose file; set DB_NETWORK if yours differs.
database:
external: true
name: ${DB_NETWORK:-minecraft-network}

secrets:
db_password:
file: ./db_password
3 changes: 2 additions & 1 deletion docker/entrypoint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ set -eu

export HOME=/tmp
export XDG_RUNTIME_DIR=/tmp/xdg
mkdir -p -m 700 "$XDG_RUNTIME_DIR"
mkdir -p "$XDG_RUNTIME_DIR"
chmod 700 "$XDG_RUNTIME_DIR"

export WLR_BACKENDS=headless
export WLR_LIBINPUT_NO_DEVICES=1
Expand Down
2 changes: 1 addition & 1 deletion docker/maps.example.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"db": { "host": "127.0.0.1", "port": 4000, "user": "root", "database": "dynmap" },
"db": { "host": "tidb", "port": 4000, "user": "renderer", "password_file": "/run/secrets/db_password", "database": "dynmap" },
"live": "wss://map.example.net/up/ws",
"maps": [
{ "id": 1, "region": "/worlds/overworld/region", "persp": "iso_SE_30_hires", "zoom_max": 12 },
Expand Down
17 changes: 13 additions & 4 deletions docker/run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
# CONFIG maps.json mounted read-only at /config/maps.json
# ONLINE_FILE proxy presence file mounted at /online.txt (use with run --online-file /online.txt)
# EXTRA_GROUPS space separated gids that may read the world files
# NETWORK docker network (default: host for run/zoom, none otherwise)
# NETWORK docker network (default: $DB_NETWORK or minecraft-network for run/zoom/watch, none otherwise)
# DB_PASSWORD_FILE file with the database password, mounted read-only at /run/secrets/db_password
# DYNMAP_DB_PASSWORD the password itself: passed by name, so its value stays off the docker command line
# IMAGE, CPUS, MEMORY
set -euo pipefail

Expand All @@ -22,7 +24,7 @@ RENDER_GID=$(getent group render | cut -d: -f3)
mkdir -p "$OUT_DIR" "$STATE_DIR"

case "${1:-}" in
run|zoom|watch) NETWORK=${NETWORK:-host} ;;
run|zoom|watch) NETWORK=${NETWORK:-${DB_NETWORK:-minecraft-network}} ;;
*) NETWORK=${NETWORK:-none} ;;
esac

Expand All @@ -31,14 +33,21 @@ MOUNTS=(-v "$DATA_DIR:/data:ro" -v "$OUT_DIR:/out" -v "$STATE_DIR:/state")
[ -n "${CONFIG:-}" ] && MOUNTS+=(-v "$CONFIG:/config/maps.json:ro")
[ -n "${ONLINE_FILE:-}" ] && MOUNTS+=(-v "$ONLINE_FILE:/online.txt:ro")

DB_ARGS=()
if [ -n "${DB_PASSWORD_FILE:-}" ]; then
MOUNTS+=(-v "$DB_PASSWORD_FILE:/run/secrets/db_password:ro")
DB_ARGS+=(-e DYNMAP_DB_PASSWORD_FILE=/run/secrets/db_password)
fi
[ -n "${DYNMAP_DB_PASSWORD:-}" ] && DB_ARGS+=(-e DYNMAP_DB_PASSWORD)

GROUPS_ARGS=(--group-add "$RENDER_GID")
for g in ${EXTRA_GROUPS:-}; do GROUPS_ARGS+=(--group-add "$g"); done

exec docker run --rm --name toro-renderer --network "$NETWORK" \
--user "$(id -u):$(id -g)" "${GROUPS_ARGS[@]}" \
--device /dev/dri/renderD128 \
--cpus "${CPUS:-1}" --cpu-shares 32 --memory "${MEMORY:-1g}" --pids-limit 256 \
--cpus "${CPUS:-1}" --cpu-shares 32 --memory "${MEMORY:-3g}" --pids-limit 256 \
--read-only --tmpfs /tmp:size=256m,exec \
--cap-drop ALL --security-opt no-new-privileges \
-e GODOT_RENDERING_METHOD="${GODOT_RENDERING_METHOD:-mobile}" -e DYNMAP_DB_PASSWORD="${DYNMAP_DB_PASSWORD:-}" \
-e GODOT_RENDERING_METHOD="${GODOT_RENDERING_METHOD:-mobile}" "${DB_ARGS[@]}" \
"${MOUNTS[@]}" "$IMAGE" "$@"
1 change: 1 addition & 0 deletions docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ godot --path . -s scripts/main.gd -- <コマンド> [--オプション 値] [--
| --- | --- | --- |
| `--config FILE` | `/config/maps.json`(あれば) | マップ設定 |
| `--db-host`, `--db-port` | 設定の `db`、無ければ `127.0.0.1:4000` | データベース |
| `--db-user` | 設定の `db.user`(既定なし) | データベースのユーザー。パスワードは環境変数かファイルから読む([運用](operations.md)) |
| `--rate N` | 8000000 | 書き込みと blob 読み出しで共有するバイト/秒の上限。0 で無制限 |
| `--dry-run` | | データベースへ書かない |
| `--live URL` | 設定の `live` | プレイヤー位置の WebSocket。`off` で無効 |
Expand Down
47 changes: 40 additions & 7 deletions docs/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,16 @@
```
`docker/run.sh` が使う環境変数: `WORLD_DIR`(`/world` に読み取り専用)、`DATA_DIR`(`/data`)、`OUT_DIR`(`/out`)、
`STATE_DIR`(`/state`)、`CONFIG`(`/config/maps.json`)、`ONLINE_FILE`(`/online.txt`)、`EXTRA_GROUPS`、`NETWORK`、
`IMAGE`、`CPUS`、`MEMORY`。`run` と `zoom` では既定でホストのネットワークを使う(DB が `127.0.0.1` で公開されているため)。
`DB_PASSWORD_FILE`(`/run/secrets/db_password`)、`IMAGE`、`CPUS`、`MEMORY`。`run`、`zoom`、`watch` では既定で
`DB_NETWORK`(無ければ `minecraft-network`)の Docker ネットワークに入る。それ以外は通信なし。

## マップ設定

`run` と `watch` は 1 つの JSON からマップを読む(雛形: [docker/maps.example.json](../docker/maps.example.json))。

```json
{
"db": { "host": "127.0.0.1", "port": 4000, "user": "root", "database": "dynmap" },
"db": { "host": "tidb", "port": 4000, "user": "renderer", "password_file": "/run/secrets/db_password", "database": "dynmap" },
"live": "wss://map.example.net/up/ws",
"maps": [
{ "id": 30002, "region": "/worlds/flat/region", "persp": "iso_SE_30_hires", "zoom_max": 7 }
Expand All @@ -41,10 +42,25 @@

- `id` は Dynmap の MapID。マップの Dynmap ワールド名(`main` など)は `dynmap_Maps` から引く。
- `persp` は 4 つの視点名のいずれか。`zoom_max` は作る zoom の段数。`mega`(既定 8)、`min_y`(-64)、`max_y`(320)も指定できる。
- `live` を省くとプレイヤー位置を使わない。
- DB にパスワードがある場合は環境変数 `DYNMAP_DB_PASSWORD` に入れる(設定ファイルに書かない)。
- `live` を省くとプレイヤー位置を使わない。`wss://` だけを受け付ける(`ws://` はこのマシンの中の接続先だけ)。それ以外の URL では
接続せず、`run` は「プレイヤーの有無が分からない」ものとして待つ。
- 設定ファイルは `/config/maps.json` にあれば自動で読む。それ以外は `--config FILE`。

### データベースの接続先とパスワード

- `db.user` は必須(既定はない)。`--db-host`、`--db-port`、`--db-user` で上書きできる。
- パスワードは環境変数かファイルから読む。コマンドラインでは受け取らず、設定ファイルの `password` も無視する。優先順は
`DYNMAP_DB_PASSWORD`、`DYNMAP_DB_PASSWORD_FILE` が指すファイル、`db.password_file` が指すファイル。読めないファイルを指定した
場合は、パスワードなしで試さずに接続を断念する。
- 接続は TLS を使わない。同じ Docker ネットワークの中だけで使う。
- レンダラーに要る権限はタイルの表だけなので、専用のユーザーを作る。

```sql
CREATE USER 'renderer'@'%' IDENTIFIED BY '<生成した値>';
GRANT SELECT, INSERT, UPDATE, DELETE ON dynmap.dynmap_Tiles TO 'renderer'@'%';
GRANT SELECT ON dynmap.dynmap_Maps TO 'renderer'@'%';
```

## マップ全体のジョブ(`run`)

```
Expand Down Expand Up @@ -85,6 +101,10 @@ docker compose -f docker/compose.watch.yaml up -d

レンダラーは起動したまま使い回す。歩き回っただけで保存済みの地形が変わらなければ、何も再描画しない。

描き始める前に試行回数を状態ファイルへ記録し、終わったら消す。回数が残っているメガタイルは、プロセスがその途中で止まったもの
なので、1 つずつ描き直し、3 回失敗したら待ち行列から外す(チャンクがまた変わると入り直す)。同じ場所で落ち続けて再起動を
繰り返すことを防ぐ。データベースのエラーは数えず、制限なしに再試行する。

初回の起動時は、その時点以降の変更だけを見る(`since` は起動時刻から)。停止中に起きた変更も、領域ファイルの時刻から
拾える。

Expand All @@ -107,12 +127,25 @@ docker compose -f docker/compose.watch.yaml up -d

## 本番運用の安全策

- コンテナ: CPU 1 個を最低の共有度で、`nice 19`、`ionice idle`、メモリ 1〜1.5 GB、ルートとワールドは読み取り専用、
ケーパビリティなし、一時ファイルは tmpfs(SSD へ書かない)
- コンテナ: CPU 1 個を最低の共有度で、`nice 19`、`ionice idle`、ルートとワールドは読み取り専用、ケーパビリティなし、一時ファイルは
tmpfs(SSD へ書かない)。ホストのネットワークは使わず、データベースのある Docker ネットワークにだけ入る
- メモリ: `watch` は 3 GB。内蔵 GPU のバッファが shmem としてコンテナの cgroup に計上される(描画中で約 1.2 GB、ほかに無名メモリが
約 400 MB)ので、1.5 GB では OOM で落ち続ける
- 入力の検査: 領域ファイル、NBT、jar は外から来るデータとして扱う。チャンクごとの展開は 64 MiB まで、NBT の深さは 128 段まで、値は
200 万個まで、パレットとデータの長さも確かめる。合わないチャンクは無いものとして描き、既存のタイルは消さない
- 負荷が上限を超える間は描画しない。`run` ではさらに、誰かがオンラインの間も待つ
- TiDB: `(MapID,x,y,zoom) IN (...)` の点参照のみ。書き込みは `--rate`(既定 8 MB/s)で制限し、ハッシュが同じタイルは書かず、
空のタイルは行を削除する。全レベル走査をするのは `--zoom-all` だけ
- メモリ: 1 バッチ分の画像(メガタイル × 8 個 ≒ 数十 MB)と、チャンクキャッシュ(バッチ後に解放)だけを持つ
- メモリ(プロセスの中): 1 バッチ分の画像(メガタイル × 8 個 ≒ 数十 MB)と、チャンクキャッシュ(バッチ後に解放)だけを持つ

## 試験

GPU の要らない部分(ファイルの解析、設定、待ち行列)は `tests/run_tests.gd` で確かめる。GitHub Actions の `test` でも動く。

```
godot --headless --path . --import
godot --headless --path . -s tests/run_tests.gd
```

## なぜコンテナに Wayland コンポジタがあるのか

Expand Down
6 changes: 3 additions & 3 deletions scripts/cmd/context.gd
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ class_name Context
extends RefCounted
## What the database-backed commands (run, watch, zoom) share: config file, tile store, quiet-gate and live player feed.
##
## Common options: --config FILE (default /config/maps.json when present), --db-host/--db-port, --rate BYTES/S,
## Common options: --config FILE (default /config/maps.json when present), --db-host/--db-port/--db-user, --rate BYTES/S,
## --dry-run, --live URL (WebSocket of the map site, default from the config; --live off disables), --max-load N,
## --max-players N (< 0 ignores players), --online-file FILE, --stale-after S.

Expand All @@ -19,8 +19,8 @@ static func create(args_: Args, default_max_load: float, default_max_players: in
var cfg_path := args_.text("config", "/config/maps.json" if FileAccess.file_exists("/config/maps.json") else "")
c.cfg = MapDef.load_config(cfg_path)
var db := MapDef.db_config(args_, c.cfg)
if OS.get_environment("DYNMAP_DB_PASSWORD") != "":
db["password"] = OS.get_environment("DYNMAP_DB_PASSWORD")
if db.get("password", "") == "" and not db.has("error"):
Term.say("warning: no database password configured (DYNMAP_DB_PASSWORD or password_file)")
c.store.configure(db)
c.store.rate = args_.number("rate", 8_000_000.0)
c.store.dry_run = args_.flag("dry-run")
Expand Down
40 changes: 36 additions & 4 deletions scripts/cmd/jar_reader.gd
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,23 @@ extends RefCounted
## Reads a .jar/.zip from memory with a name index built once. (ZIPReader.read_file walks the central directory for every
## call, ~0.2 s each on a jar with 40k entries.) Deflated entries are inflated by wrapping the raw stream into a gzip
## container - the zip directory already holds the CRC32 and the size gzip wants in its trailer.
##
## The archive is input from outside: entry names that could leave the output directory are not indexed, offsets are checked
## against the file, and declared sizes are limited (they decide how much memory is allocated).

const MAX_JAR_BYTES := 1024 * 1024 * 1024
## client jars hold JSON and small textures
const MAX_ENTRY_BYTES := 16 * 1024 * 1024

var _data := PackedByteArray()
var _index := {} # name -> [header offset, compressed size, size, crc32, method]


func open(path: String) -> bool:
_data = FileAccess.get_file_as_bytes(path)
var f := FileAccess.open(path, FileAccess.READ)
if f == null or f.get_length() > MAX_JAR_BYTES:
return false
_data = f.get_buffer(f.get_length())
if _data.size() < 22:
return false
var eocd := -1
Expand All @@ -22,14 +32,30 @@ func open(path: String) -> bool:
var entries := _data.decode_u16(eocd + 10)
var pos := _data.decode_u32(eocd + 16)
for _i in entries:
if _data.decode_u32(pos) != 0x02014B50:
if pos + 46 > _data.size() or _data.decode_u32(pos) != 0x02014B50:
return false
var name_len := _data.decode_u16(pos + 28)
var extra_len := _data.decode_u16(pos + 30)
var comment_len := _data.decode_u16(pos + 32)
var next := pos + 46 + name_len + extra_len + comment_len
if next > _data.size():
return false
var name := _data.slice(pos + 46, pos + 46 + name_len).get_string_from_utf8()
_index[name] = [_data.decode_u32(pos + 42), _data.decode_u32(pos + 20), _data.decode_u32(pos + 24), _data.decode_u32(pos + 16), _data.decode_u16(pos + 10)]
pos += 46 + name_len + extra_len + comment_len
if safe_name(name):
_index[name] = [_data.decode_u32(pos + 42), _data.decode_u32(pos + 20), _data.decode_u32(pos + 24), _data.decode_u32(pos + 16), _data.decode_u16(pos + 10)]
else:
push_warning("jar entry skipped, its name is not a relative path inside the archive: %s" % name)
pos = next
return true


## A relative path without "..", safe to join to an output directory on Linux and Windows.
static func safe_name(name: String) -> bool:
if name == "" or name.begins_with("/") or name.contains("\\") or name.contains(":"):
return false
for part in name.split("/"):
if part == "..":
return false
return true


Expand All @@ -46,7 +72,13 @@ func read(name: String) -> PackedByteArray:
return PackedByteArray()
var e: Array = _index[name]
var header: int = e[0]
if e[1] > MAX_ENTRY_BYTES or e[2] > MAX_ENTRY_BYTES or header + 30 > _data.size():
push_warning("jar entry skipped, sizes out of bounds: %s" % name)
return PackedByteArray()
var start := header + 30 + _data.decode_u16(header + 26) + _data.decode_u16(header + 28)
if start + e[1] > _data.size():
push_warning("jar entry skipped, sizes out of bounds: %s" % name)
return PackedByteArray()
var body := _data.slice(start, start + e[1])
if e[4] == 0:
return body
Expand Down
3 changes: 3 additions & 0 deletions scripts/cmd/render.gd
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ static func run(args: Args) -> int:
iso.next_generation()
tiles = iso.render(rect[0], rect[1], rect[2], rect[3])
print("render rect %s: %.0f ms (%d tiles)" % [rect, (Time.get_ticks_usec() - t0) / 1000.0, tiles.size()])
if tiles.is_empty():
push_error("rect %s was not drawn" % [rect])
continue
var dir := out_dir
if out_dir != "" and rects.size() > 1:
dir = out_dir.path_join("r%d_%d" % [rect[0], rect[1]])
Expand Down
Loading
Loading