build(server): separate dev and beta snapshot deployments

This commit is contained in:
Flechazo committed 2026-11-12 17:39:25 +08:00
1 parent dec353c3a2
commit 7d3b670896
5 files changed
+228 -17

No files matched your search

+33 -17
View File
@@ -1,6 +1,7 @@
#!/bin/sh
# bd2-host.sh: everything a Docker host does for bd2server, in one place.
#
# --target dev|beta COMMAND selects an isolated host configuration.
# setup [SOURCE] first install and deploy local source (safe to rerun)
# setup --image REF first install and deploy a Docker image
# install [SOURCE] prepare directories, secrets, a Compose template and the
@@ -17,7 +18,20 @@
set -eu
umask 077
TARGET=
CONFIG=/etc/bd2/host.conf
case "${1:-}" in
--target)
[ "$#" -ge 3 ] || { printf '%s\n' 'usage: bd2-host.sh --target dev|beta COMMAND [ARGS]' >&2; exit 2; }
TARGET=$2
case "$TARGET" in
dev) CONFIG=/etc/bd2/host.conf ;;
beta) CONFIG=/etc/bd2/hosts/beta.conf ;;
*) printf '%s\n' 'target must be dev or beta' >&2; exit 2 ;;
esac
[ -f "$CONFIG" ] || { printf 'missing target configuration: %s\n' "$CONFIG" >&2; exit 2; }
shift 2 ;;
esac
load_config() {
BD2_DIR=/opt/bd2
@@ -49,6 +63,12 @@ load_config() {
[ -n "$COMPOSE_FILE" ] || COMPOSE_FILE=$BD2_DIR/compose.yaml
UPDATES=$DATA_DIR/updates
SELF=$BD2_DIR/bd2-host.sh
UNIT=bd2-docker-update
TARGET_ARGS=
if [ "$TARGET" = beta ]; then
UNIT=bd2-beta-docker-update
TARGET_ARGS=' --target beta'
fi
}
log() { printf 'bd2-host: %s\n' "$*"; }
@@ -107,20 +127,16 @@ resolve_image() {
docker image inspect --format '{{.Id}}' "$1"
}
# build_image COMMIT prints the immutable image ID built from a fresh
# worktree, so ignored local files never enter the build context.
# Published automatic updates build only committed files, without a checkout.
build_image() {
build_dir=$(mktemp -d) || die 'cannot create a build directory'
# COPY keeps file modes and the image runs as an unprivileged user, so
# check out with a normal umask instead of this script's private 077.
if ! (umask 022 && git -C "$SOURCE_DIR" -c core.hooksPath=/dev/null worktree add --quiet --detach "$build_dir/source" "$1"); then
rmdir "$build_dir"
die "cannot check out $1"
archive=$(mktemp) || die 'cannot create a source archive'
if ! git -C "$SOURCE_DIR" archive --format=tar "$1" >"$archive"; then
rm -f "$archive"
die "cannot archive $1"
fi
built=$(docker build --quiet --label "org.opencontainers.image.revision=$1" -t "bd2server:$1" \
-f "$build_dir/source/Dockerfile.server" "$build_dir/source") || built=
git -C "$SOURCE_DIR" worktree remove --force "$build_dir/source" >/dev/null 2>&1 || true
rmdir "$build_dir" 2>/dev/null || true
-f Dockerfile.server - <"$archive") || built=
rm -f "$archive"
printf '%s\n' "$built" | grep -Eq '^sha256:[0-9a-f]{64}$' || die "building $1 failed"
printf '%s\n' "$built"
}
@@ -234,7 +250,7 @@ cmd_install() {
if [ "$(readlink -f "$0")" != "$(readlink -f "$SELF" 2>/dev/null || true)" ]; then
install -m 700 -o root -g root "$0" "$SELF"
fi
cat >/etc/systemd/system/bd2-docker-update.service <<EOF
cat >/etc/systemd/system/$UNIT.service <<EOF
[Unit]
Description=Switch bd2server to the image it requested
After=network-online.target docker.service
@@ -246,12 +262,12 @@ StartLimitBurst=3
[Service]
Type=oneshot
UMask=0077
ExecStart=$SELF handoff
ExecStart=$SELF$TARGET_ARGS handoff
# Builds can exceed the default oneshot timeout.
TimeoutStartSec=30min
TimeoutStopSec=30
EOF
cat >/etc/systemd/system/bd2-docker-update.path <<EOF
cat >/etc/systemd/system/$UNIT.path <<EOF
[Unit]
Description=Watch for bd2server image update requests
@@ -259,14 +275,14 @@ Description=Watch for bd2server image update requests
# PathExists also catches requests written while this host was down.
PathExists=$UPDATES/docker-request.json
PathExists=$UPDATES/docker-request.processing.json
Unit=bd2-docker-update.service
Unit=$UNIT.service
[Install]
WantedBy=multi-user.target
EOF
chmod 644 /etc/systemd/system/bd2-docker-update.service /etc/systemd/system/bd2-docker-update.path
chmod 644 /etc/systemd/system/$UNIT.service /etc/systemd/system/$UNIT.path
systemctl daemon-reload
systemctl enable --now bd2-docker-update.path >/dev/null
systemctl enable --now "$UNIT.path" >/dev/null
log "installed in $BD2_DIR"
}
+46
View File
@@ -0,0 +1,46 @@
bd2.flechazo.xin {
import security_common
header {
Cross-Origin-Resource-Policy "same-origin"
Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=(), usb=()"
Strict-Transport-Security "max-age=31536000; includeSubDomains"
}
request_body {
max_size 1MB
}
@api path /game/* /auth/* /client/* /admin /admin/* /StateCheckInfoJson /logs /readyz /healthz /livez
handle @api {
reverse_proxy 127.0.0.1:8085 {
header_up X-Real-IP {http.request.remote.host}
header_up X-Forwarded-For {http.request.remote.host}
}
}
handle /releases/* {
@downloads path /releases/downloads/* /releases/files/*
header @downloads Cache-Control "no-store"
respond @downloads "Downloads will open at public beta." 403
@write not method GET HEAD
respond @write 405
reverse_proxy 127.0.0.1:8085 {
header_up X-Real-IP {http.request.remote.host}
header_up X-Forwarded-For {http.request.remote.host}
}
}
handle /data/latest.json {
@write not method GET HEAD
respond @write 405
header Cache-Control "no-cache"
rewrite * /latest.json
root * /opt/bd2-site-generated
file_server
}
handle {
@write not method GET HEAD
respond @write 405
header Content-Security-Policy "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
@data path /data/* /assets/*
header @data Cache-Control "no-cache"
root * /opt/bd2-site/site
file_server
}
}
+25
View File
@@ -0,0 +1,25 @@
name: bd2-beta
services:
server:
image: ${BD2_SERVER_IMAGE:?bd2-host.sh deploy selects the image}
command: [serve, --listen, 0.0.0.0:8080, --data-dir, /app/data]
restart: unless-stopped
env_file: [/opt/bd2-beta/.env]
ports:
- "127.0.0.1:8085:8080"
- "8445:8444/tcp"
- "8445:8444/udp"
volumes:
- /opt/bd2-beta/data:/app/data
- /opt/bd2-beta/tls:/app/tls:ro
read_only: true
tmpfs: ["/tmp:rw,noexec,nosuid,nodev,size=256m"]
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
pids_limit: 256
mem_limit: 1536m
cpus: 1.5
logging:
driver: json-file
options: {max-size: "10m", max-file: "3"}
stop_grace_period: 90s
+4
View File
@@ -0,0 +1,4 @@
BD2_DIR=/opt/bd2-beta
SOURCE_URL=https://git.sighs.cc/Flechazo/bd2.git
COMPOSE_FILE=/opt/bd2-beta/compose.yaml
READY_PORT=8080
+120
View File
@@ -0,0 +1,120 @@
#Requires -Version 7.4
[CmdletBinding()]
param(
[Parameter(Mandatory)][ValidateSet('dev', 'beta')][string]$Target,
[ValidateSet('deploy', 'status', 'rollback')][string]$Action = 'deploy',
[string]$SourceRoot = (Resolve-Path (Join-Path $PSScriptRoot '../..')).Path,
[string]$ConfigPath = (Join-Path $PSScriptRoot 'deploy.local.json'),
[string]$PatchFile,
[switch]$Wait
)
$ErrorActionPreference = 'Stop'
if ($PatchFile) {
if ($Target -ne 'dev' -or $Action -ne 'deploy') { throw 'Temporary source patches are restricted to dev deployments' }
$PatchFile = (Resolve-Path -LiteralPath $PatchFile).Path
}
$settings = Get-Content -LiteralPath $ConfigPath -Raw | ConvertFrom-Json
$destination = $settings.targets.$Target
if (!$destination) { throw "Missing deployment target '$Target' in $ConfigPath" }
if ($destination.host -notmatch '^[a-zA-Z0-9_.-]+@[a-zA-Z0-9_.:-]+$') { throw 'Invalid SSH destination' }
if ($destination.hostScript -notmatch '^/[a-zA-Z0-9_./-]+$') { throw 'Invalid remote deployment script path' }
$keyPath = (Resolve-Path -LiteralPath $destination.identityFile).Path
$sshOptions = @('-o', 'BatchMode=yes', '-o', 'ConnectTimeout=10', '-i', $keyPath)
function Invoke-Ssh([string]$Command) {
& ssh @sshOptions $destination.host $Command
if ($LASTEXITCODE -ne 0) { throw "SSH command failed ($LASTEXITCODE)" }
}
if ($Action -ne 'deploy') {
Invoke-Ssh "sudo $($destination.hostScript) --target $Target $Action"
return
}
$SourceRoot = (Resolve-Path -LiteralPath $SourceRoot).Path
$paths = & git -C $SourceRoot -c core.quotepath=false ls-files --cached --others --exclude-standard
if ($LASTEXITCODE -ne 0) { throw 'Cannot enumerate local source files' }
$paths = @($paths | Where-Object {
($_ -match '^go/(cmd|internal|seed)/' -and $_ -notmatch '(^|/)(\.cache|logs|data)/' -and $_ -notmatch '_test\.go$') -or
$_ -in @('go/go.mod', 'go/go.sum', 'Dockerfile.server', 'Dockerfile.server.dockerignore', 'tools/server/bd2-docker-entrypoint.sh', 'tools/server/bd2-host.sh', 'tools/server/compose.yaml') -or
$_ -match '^schedules/'
})
$paths += @('versions.json', 'CHANGELOG.md', 'CHANGELOG.md.sig', 'UPDATE_FINGERPRINT.json')
$id = [Guid]::NewGuid().ToString('N')
$remote = "/tmp/bd2-deploy-$Target-$id"
$archive = Join-Path ([IO.Path]::GetTempPath()) "bd2-deploy-$id.tar.gz"
$runner = Join-Path ([IO.Path]::GetTempPath()) "bd2-deploy-$id.sh"
try {
$stream = [IO.File]::Create($archive)
$gzip = [IO.Compression.GZipStream]::new($stream, [IO.Compression.CompressionLevel]::Fastest, $false)
$writer = [System.Formats.Tar.TarWriter]::new($gzip, $false)
try {
if ($PatchFile) {
$entry = [System.Formats.Tar.PaxTarEntry]::new([System.Formats.Tar.TarEntryType]::RegularFile, '.bd2-deploy.patch')
$entry.Mode = [IO.UnixFileMode]420
$entry.DataStream = [IO.File]::OpenRead($PatchFile)
try { $writer.WriteEntry($entry) } finally { $entry.DataStream.Dispose() }
}
foreach ($relative in ($paths | Sort-Object -Unique)) {
if ($relative.Contains('..') -or [IO.Path]::IsPathRooted($relative)) { throw "Invalid source path: $relative" }
$full = Join-Path $SourceRoot $relative
if (!(Test-Path -LiteralPath $full -PathType Leaf)) { continue }
if ((Get-Item -LiteralPath $full).LinkType) { throw "Source links are not allowed: $relative" }
$entry = [System.Formats.Tar.PaxTarEntry]::new([System.Formats.Tar.TarEntryType]::RegularFile, $relative.Replace('\', '/'))
$entry.Mode = [IO.UnixFileMode]420
if ($relative.EndsWith('.sh')) {
$unixText = [IO.File]::ReadAllText($full).Replace("`r`n", "`n")
$entry.DataStream = [IO.MemoryStream]::new([Text.UTF8Encoding]::new($false).GetBytes($unixText))
} else {
$entry.DataStream = [IO.File]::OpenRead($full)
}
try { $writer.WriteEntry($entry) } finally { $entry.DataStream.Dispose() }
}
} finally { $writer.Dispose() }
# Current uncommitted source; Linux shell newlines are normalized in the archive only.
$script = @"
#!/bin/sh
set -eu
source_dir=$remote
log=$remote.log
result=$remote.result
cleanup() { code=`$?; printf '%s\n' "`$code" >"`$result"; rm -rf -- '$remote'; rm -f -- '$remote.tar.gz' '$remote.sh'; }
trap cleanup EXIT
trap 'exit 143' HUP INT TERM
mkdir -m 755 "`$source_dir"
tar -xzf '$remote.tar.gz' -C "`$source_dir"
if [ -f "`$source_dir/.bd2-deploy.patch" ]; then
cd "`$source_dir"
patch --batch --fuzz=0 -p1 < .bd2-deploy.patch
rm .bd2-deploy.patch
fi
sh "`$source_dir/tools/server/bd2-host.sh" --target $Target install "`$source_dir"
set +e
'$($destination.hostScript)' --target $Target deploy "`$source_dir"
code=`$?
printf '%s\n' "`$code" >"`$result"
exit "`$code"
"@
[IO.File]::WriteAllText($runner, $script.Replace("`r", ''), [Text.UTF8Encoding]::new($false))
& scp @sshOptions -q $archive "$($destination.host):$remote.tar.gz"
if ($LASTEXITCODE -ne 0) { throw 'Source upload failed' }
& scp @sshOptions -q $runner "$($destination.host):$remote.sh"
if ($LASTEXITCODE -ne 0) { throw 'Deployment runner upload failed' }
Invoke-Ssh "sudo sh -c 'nohup sh $remote.sh >$remote.log 2>&1 </dev/null & echo deployment_pid=`$!'"
Write-Host "Temporary deployment started: $Target"
Write-Host "Log: ssh $($destination.host) sudo tail -f $remote.log"
if ($Wait) {
$deadline = [DateTime]::UtcNow.AddMinutes(30)
do {
Start-Sleep -Seconds 5
$state = & ssh @sshOptions $destination.host "sudo sh -c 'if test -f $remote.result; then cat $remote.result; else echo running; fi'"
if ($LASTEXITCODE -ne 0) { throw 'Cannot read deployment state; deployment continues on the host' }
if ($state -ne 'running') { break }
} while ([DateTime]::UtcNow -lt $deadline)
Invoke-Ssh "sudo tail -n 50 $remote.log"
if ($state -eq 'running') { throw 'Deployment is still running; inspect the printed remote log' }
if ($state -ne '0') { throw "Deployment failed ($state); remote log retained" }
Invoke-Ssh "sudo $($destination.hostScript) --target $Target status"
Invoke-Ssh "sudo rm -f -- $remote.log $remote.result"
}
} finally {
[IO.File]::Delete($archive)
[IO.File]::Delete($runner)
}