Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(selfhost): fail fast when an installer host port is already in use (#11024)
linzch35efd46c1de5d
diff --git a/scripts/install.ps1 b/scripts/install.ps1index 5627a9a25c..85834d77d9 100644--- a/scripts/install.ps1+++ b/scripts/install.ps1@@ -84,6 +84,81 @@ function Get-ComposePublishedPort {return $published}+# Host port the compose file is configured to publish for a service, resolved by+# Compose itself (`docker compose config`) so it follows the same+# environment-over-.env precedence as `up`. Only used by the occupied-port+# preflight below; $null when Compose cannot resolve it, in which case the+# preflight is skipped and `up` behaves as before. Must be called from the+# installation directory.+function Get-ComposeConfiguredPort {+ param(+ [Parameter(Mandatory = $true)][string]$Service,+ [Parameter(Mandatory = $true)][int]$ContainerPort+ )++ try {+ $output = docker compose -f docker-compose.selfhost.yml config --format json 2>$null+ if ($LASTEXITCODE -ne 0 -or -not $output) {+ return $null+ }+ $config = ($output -join "`n") | ConvertFrom-Json+ foreach ($mapping in @($config.services.$Service.ports)) {+ $published = "$($mapping.published)"+ if ([int]$mapping.target -eq $ContainerPort -and $published -match '^[0-9]+$') {+ return $published+ }+ }+ } catch {+ return $null+ }+ return $null+}++# True when something already accepts connections on 127.0.0.1:<port>, the+# address the self-host stack publishes on.+function Test-HostPortInUse {+ param([Parameter(Mandatory = $true)][int]$Port)++ $client = New-Object System.Net.Sockets.TcpClient+ try {+ $attempt = $client.BeginConnect("127.0.0.1", $Port, $null, $null)+ if (-not $attempt.AsyncWaitHandle.WaitOne(1000)) {+ return $false+ }+ $client.EndConnect($attempt)+ return $true+ } catch {+ return $false+ } finally {+ $client.Close()+ }+}++# Fail before pulling and starting anything when a host port the stack needs is+# already taken, instead of letting Docker abort halfway through `up -d` with+# "port is already allocated" (#883). A port this installation's own running+# stack already publishes is not a conflict: re-running the installer to+# upgrade recreates those containers in place.+function Assert-SelfHostPortsAvailable {+ $checks = @(+ @{ Service = "backend"; ContainerPort = 8080; Setting = "PORT=<free port> in $InstallDir\.env (or BACKEND_PORT / API_PORT / SERVER_PORT if you already set one of those)" }+ @{ Service = "frontend"; ContainerPort = 3000; Setting = "FRONTEND_PORT=<free port> in $InstallDir\.env" }+ )++ foreach ($check in $checks) {+ $port = Get-ComposeConfiguredPort -Service $check.Service -ContainerPort $check.ContainerPort+ if (-not $port) {+ continue+ }+ if ((Get-ComposePublishedPort -Service $check.Service -ContainerPort $check.ContainerPort) -eq $port) {+ continue+ }+ if (Test-HostPortInUse -Port ([int]$port)) {+ Write-Fail "Port $port is already in use on this machine, so the Multica $($check.Service) cannot be published on it.`n Stop whatever is listening there (see: netstat -ano | findstr :$port),`n or pick another port: set $($check.Setting)`n and re-run the installer."+ }+ }+}+function Get-LatestVersion {try {$release = Invoke-RestMethod -Uri "https://api.github.com/repos/multica-ai/multica/releases/latest" -ErrorAction Stop@@ -439,6 +514,8 @@ function Install-Server {Write-Ok "Using existing .env"}+ Assert-SelfHostPortsAvailable+Write-Info "Pulling official Multica images..."Pull-OfficialSelfHostImagesWrite-Info "Starting Multica services (this may take a few minutes on first run)..."diff --git a/scripts/install.ps1.test.ps1 b/scripts/install.ps1.test.ps1index d82eef456e..e0da6408fa 100644--- a/scripts/install.ps1.test.ps1+++ b/scripts/install.ps1.test.ps1@@ -195,12 +195,37 @@ function Get-StubFrontendPort {}# Stand in for the external commands the installer shells out to.+$script:StubStackUp = $falsefunction docker {$global:LASTEXITCODE = 0$args_ = @($args)if ($args_.Count -ge 1 -and $args_[0] -eq "info") { return }if ($args_.Count -ge 1 -and $args_[0] -eq "compose") {+ if ($args_ -contains "up") {+ $script:StubStackUp = $true+ return+ }+ if ($args_ -contains "config") {+ # Opt-in, so the port matrix never probes real host ports.+ if (-not $env:MULTICA_TEST_COMPOSE_CONFIG) {+ $global:LASTEXITCODE = 1+ return+ }+ $config = @{+ services = @{+ backend = @{ ports = @(@{ mode = "ingress"; host_ip = "127.0.0.1"; target = 8080; published = "$(Get-StubBackendPort)"; protocol = "tcp" }) }+ frontend = @{ ports = @(@{ mode = "ingress"; host_ip = "127.0.0.1"; target = 3000; published = "$(Get-StubFrontendPort)"; protocol = "tcp" }) }+ }+ }+ return (($config | ConvertTo-Json -Depth 6) -split "`n")+ }if ($args_ -contains "port") {+ # Nothing is published until `up`, unless the case models this+ # installation's own stack already running (an upgrade re-run).+ if (-not $script:StubStackUp -and -not $env:MULTICA_TEST_STACK_RUNNING) {+ $global:LASTEXITCODE = 1+ return+ }if ($args_ -contains "backend") { return "127.0.0.1:$(Get-StubBackendPort)" }if ($args_ -contains "frontend") { return "127.0.0.1:$(Get-StubFrontendPort)" }$global:LASTEXITCODE = 1@@ -231,7 +256,11 @@ function Test-Docker { }Start-LocalInstall'@ | Set-Content -Path $runnerScript -Encoding UTF8-foreach ($case in $cases) {+# Runs install.ps1 for one case in a child process and returns its exit code,+# rendered output and probe log. Ambient environment comes from $case.Env only.+function Invoke-InstallerCase {+ param([hashtable]$Case)+$workDir = Join-Path ([System.IO.Path]::GetTempPath()) ("multica-ps1-" + [guid]::NewGuid().ToString("N"))New-Item -ItemType Directory -Path (Join-Path $workDir ".git") -Force | Out-Null@@ -244,9 +273,9 @@ foreach ($case in $cases) {"JWT_SECRET=change-me-in-production""POSTGRES_PASSWORD=multica")- if ($case.Mutation) {- foreach ($key in $case.Mutation.Keys) {- $value = $case.Mutation[$key]+ if ($Case.Mutation) {+ foreach ($key in $Case.Mutation.Keys) {+ $value = $Case.Mutation[$key]$envLines = $envLines | ForEach-Object {if ($_ -match "^#?\s*$key=") { "$key=$value" } else { $_ }}@@ -262,12 +291,12 @@ foreach ($case in $cases) {# Control the ambient environment explicitly so a CI runner's own PORT# cannot leak into the matrix. Absent must mean absent: an empty string is a# different input, and the chain treats it as "set but no value".- $portVars = @("PORT", "BACKEND_PORT", "API_PORT", "SERVER_PORT", "FRONTEND_PORT")+ $caseVars = @("PORT", "BACKEND_PORT", "API_PORT", "SERVER_PORT", "FRONTEND_PORT", "MULTICA_TEST_COMPOSE_CONFIG", "MULTICA_TEST_STACK_RUNNING")$previous = @{}- foreach ($key in $portVars) {+ foreach ($key in $caseVars) {$previous[$key] = [System.Environment]::GetEnvironmentVariable($key)- if ($case.Env.ContainsKey($key)) {- Set-Item -Path "Env:$key" -Value $case.Env[$key]+ if ($Case.Env.ContainsKey($key)) {+ Set-Item -Path "Env:$key" -Value $Case.Env[$key]} else {Remove-Item -Path "Env:$key" -ErrorAction SilentlyContinue}@@ -277,7 +306,7 @@ foreach ($case in $cases) {$output = & $PowerShellPath -NoProfile -File $runnerScript -InstallerPath $InstallerPath -WorkDir $workDir -ProbeLog $probeLog 2>&1$exitCode = $LASTEXITCODE} finally {- foreach ($key in $portVars) {+ foreach ($key in $caseVars) {if ($null -eq $previous[$key]) {Remove-Item -Path "Env:$key" -ErrorAction SilentlyContinue} else {@@ -286,27 +315,86 @@ foreach ($case in $cases) {}}- $rendered = ($output | Out-String)- if ($exitCode -ne 0) {+ $probes = @(Get-Content $probeLog)+ Remove-Item $workDir -Recurse -Force -ErrorAction SilentlyContinue+ return @{ ExitCode = $exitCode; Output = ($output | Out-String); Probes = $probes }+}++function Assert-PublishedPorts {+ param([hashtable]$Case, [hashtable]$Result)++ $rendered = $Result.Output+ if ($Result.ExitCode -ne 0) {Write-Host $rendered- Fail-Test "[$($case.Label)] install.ps1 exited $exitCode"+ Fail-Test "[$($Case.Label)] install.ps1 exited $($Result.ExitCode)"}- $probed = (Get-Content $probeLog | Select-Object -First 1)+ $probed = ($Result.Probes | Select-Object -First 1)$probedPort = if ($probed -match "localhost:(\d+)/health") { $Matches[1] } else { $null }$printedBackend = if ($rendered -match "Backend:\s+http://localhost:(\d+)") { $Matches[1] } else { $null }$printedFrontend = if ($rendered -match "Frontend:\s+http://localhost:(\d+)") { $Matches[1] } else { $null }- if ($probedPort -ne $case.Backend -or $printedBackend -ne $case.Backend -or $printedFrontend -ne $case.Frontend) {+ if ($probedPort -ne $Case.Backend -or $printedBackend -ne $Case.Backend -or $printedFrontend -ne $Case.Frontend) {Write-Host $rendered- Write-Host " compose published: backend=$($case.Backend) frontend=$($case.Frontend)"+ Write-Host " compose published: backend=$($Case.Backend) frontend=$($Case.Frontend)"Write-Host " health check probed: $probedPort"Write-Host " printed: backend=$printedBackend frontend=$printedFrontend"- Fail-Test "[$($case.Label)] installer ports disagree with the port Compose published"+ Fail-Test "[$($Case.Label)] installer ports disagree with the port Compose published"+ }+}++foreach ($case in $cases) {+ Assert-PublishedPorts -Case $case -Result (Invoke-InstallerCase -Case $case)+}++# ---------------------------------------------------------------------------+# 4. A host port that is already taken stops the installer before anything is+# pulled or started, with a fix the user can act on (#883). The port comes+# from Compose's own resolution, so an ambient override is what gets checked.+# ---------------------------------------------------------------------------+$listener = New-Object System.Net.Sockets.TcpListener ([System.Net.IPAddress]::Loopback, 0)+$listener.Start()+try {+ $held = "$($listener.LocalEndpoint.Port)"++ $occupiedCases = @(+ @{ Label = "env-file PORT"; Env = @{ MULTICA_TEST_COMPOSE_CONFIG = "1" }; Mutation = @{ PORT = $held }; Setting = "PORT=<free port>" }+ @{ Label = "ambient PORT beats .env"; Env = @{ MULTICA_TEST_COMPOSE_CONFIG = "1"; PORT = $held }; Mutation = $null; Setting = "PORT=<free port>" }+ @{ Label = "env-file BACKEND_PORT"; Env = @{ MULTICA_TEST_COMPOSE_CONFIG = "1" }; Mutation = @{ BACKEND_PORT = $held }; Setting = "PORT=<free port>" }+ @{ Label = "env-file FRONTEND_PORT"; Env = @{ MULTICA_TEST_COMPOSE_CONFIG = "1" }; Mutation = @{ FRONTEND_PORT = $held }; Setting = "FRONTEND_PORT=<free port>" }+ )+ foreach ($case in $occupiedCases) {+ $result = Invoke-InstallerCase -Case $case+ if ($result.ExitCode -eq 0) {+ Write-Host $result.Output+ Fail-Test "[$($case.Label)] installer must not continue when port $held is already in use"+ }+ if ($result.Output -notmatch [regex]::Escape("Port $held is already in use") -or+ $result.Output -notmatch [regex]::Escape($case.Setting)) {+ Write-Host $result.Output+ Fail-Test "[$($case.Label)] expected an actionable occupied-port error naming $held and $($case.Setting)"+ }+ if ($result.Probes.Count -gt 0 -or $result.Output -match "Starting Multica services") {+ Write-Host $result.Output+ Fail-Test "[$($case.Label)] installer started the stack despite the occupied port"+ }}- Remove-Item $workDir -Recurse -Force -ErrorAction SilentlyContinue+ # Re-running over this installation's own running stack: the port is busy+ # only because Compose already publishes it for us, which is not a conflict.+ $ownStack = @{ Label = "own running stack"; Env = @{ MULTICA_TEST_COMPOSE_CONFIG = "1"; MULTICA_TEST_STACK_RUNNING = "1" }; Mutation = @{ PORT = $held }; Backend = $held; Frontend = "3000" }+ Assert-PublishedPorts -Case $ownStack -Result (Invoke-InstallerCase -Case $ownStack)+} finally {+ $listener.Stop()}+# A free port goes straight through the preflight.+$probe = New-Object System.Net.Sockets.TcpListener ([System.Net.IPAddress]::Loopback, 0)+$probe.Start()+$free = "$($probe.LocalEndpoint.Port)"+$probe.Stop()+$freeCase = @{ Label = "free port"; Env = @{ MULTICA_TEST_COMPOSE_CONFIG = "1" }; Mutation = @{ PORT = $free }; Backend = $free; Frontend = "3000" }+Assert-PublishedPorts -Case $freeCase -Result (Invoke-InstallerCase -Case $freeCase)+Remove-Item $runnerScript -Force -ErrorAction SilentlyContinueWrite-Host "install.ps1 tests passed" -ForegroundColor Greendiff --git a/scripts/install.sh b/scripts/install.shindex 59c8d2999a..6716afc89a 100755--- a/scripts/install.sh+++ b/scripts/install.sh@@ -87,6 +87,72 @@ compose_published_port() {printf "%s" "$published"}+# Host port the compose file is configured to publish for a container port,+# resolved by Compose itself (`docker compose config`) so it follows the same+# environment-over-.env precedence as `up`. Only used by the occupied-port+# preflight below; returns non-zero when Compose cannot resolve it, in which+# case the preflight is skipped and `up` behaves as before. Must be called from+# the installation directory.+compose_configured_port() {+ local container_port=$1 configured++ configured="$(docker compose -f docker-compose.selfhost.yml config --format json 2>/dev/null |+ awk -v target="$container_port" '+ /"target":/ { t = $0; gsub(/[^0-9]/, "", t); next }+ /"published":/ {+ p = $0; gsub(/[^0-9]/, "", p)+ if (t == target && p != "") { print p; exit }+ }+ ' || true)"++ case "$configured" in+ "" | *[!0-9]*) return 1 ;;+ esac++ printf "%s" "$configured"+}++# True when something already accepts connections on 127.0.0.1:<port>, the+# address the self-host stack publishes on. Uses bash's /dev/tcp so no extra+# tool (lsof / ss / netstat) is needed; where that is unavailable the port is+# simply treated as free.+host_port_in_use() {+ (exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null+}++# Fail before pulling and starting anything when a host port the stack needs is+# already taken, instead of letting Docker abort halfway through `up -d` with+# "port is already allocated" (#883). A port this installation's own running+# stack already publishes is not a conflict: re-running the installer to+# upgrade recreates those containers in place.+check_selfhost_ports() {+ local service container_port setting port+ for service in backend frontend; do+ case "$service" in+ backend)+ container_port=8080+ setting="PORT=<free port> in $INSTALL_DIR/.env (or BACKEND_PORT / API_PORT / SERVER_PORT if you already set one of those)"+ ;;+ frontend)+ container_port=3000+ setting="FRONTEND_PORT=<free port> in $INSTALL_DIR/.env"+ ;;+ esac++ port="$(compose_configured_port "$container_port")" || continue+ if [ "$(compose_published_port "$service" "$container_port" || true)" = "$port" ]; then+ continue+ fi++ if host_port_in_use "$port"; then+ fail "Port $port is already in use on this machine, so the Multica $service cannot be published on it.+ Stop whatever is listening there (see: lsof -nP -iTCP:$port -sTCP:LISTEN),+ or pick another port: set $setting+ and re-run the installer."+ fi+ done+}+detect_os() {case "$(uname -s)" inDarwin) OS="darwin" ;;@@ -400,6 +466,8 @@ setup_server() {ok "Using existing .env"fi+ check_selfhost_ports+# Start Docker Composeinfo "Pulling official Multica images..."pull_official_selfhost_imagesdiff --git a/scripts/install.test.sh b/scripts/install.test.shindex d410d05472..5397a3e60d 100644--- a/scripts/install.test.sh+++ b/scripts/install.test.sh@@ -323,11 +323,49 @@ case "${1:-}" insubcommand=""for arg in "$@"; docase "$arg" in- pull | up | port | version | ps | logs | down) subcommand="$arg"; break ;;+ pull | up | port | config | version | ps | logs | down) subcommand="$arg"; break ;;esacdonecase "$subcommand" in+ up) : >.stub-stack-up ;;+ config)+ # Opt-in, so the port matrix above never probes real host ports.+ [ -n "${MULTICA_TEST_COMPOSE_CONFIG:-}" ] || exit 1+ cat <<JSON+{+ "services": {+ "backend": {+ "ports": [+ {+ "mode": "ingress",+ "host_ip": "127.0.0.1",+ "target": 8080,+ "published": "$(_published_backend_port)",+ "protocol": "tcp"+ }+ ]+ },+ "frontend": {+ "ports": [+ {+ "mode": "ingress",+ "host_ip": "127.0.0.1",+ "target": 3000,+ "published": "$(_published_frontend_port)",+ "protocol": "tcp"+ }+ ]+ }+ }+}+JSON+ ;;port)+ # Nothing is published until `up`, unless the test models this+ # installation's own stack already running (an upgrade re-run).+ if [ ! -f .stub-stack-up ] && [ -z "${MULTICA_TEST_STACK_RUNNING:-}" ]; then+ exit 1+ fiservice=""for arg in "$@"; docase "$arg" in@@ -589,12 +627,150 @@ STUBfi}+# ---------------------------------------------------------------------------+# --with-server: a host port that is already taken must stop the installer+# before anything is pulled or started, with a fix the user can act on (#883).+# The port comes from Compose's own resolution, so an ambient override is+# checked rather than the .env value.+# ---------------------------------------------------------------------------+_HELD_PORT=""+_HELD_PORT_PID=""++# Starts a real listener on 127.0.0.1 and sets _HELD_PORT / _HELD_PORT_PID.+_hold_port() {+ local port_file="$1/held-port"+ rm -f "$port_file"+ python3 -c '+import os, socket, sys, time+s = socket.socket()+s.bind(("127.0.0.1", 0))+s.listen(16)+s.settimeout(0.5)+with open(sys.argv[1] + ".tmp", "w") as f:+ f.write(str(s.getsockname()[1]))+os.rename(sys.argv[1] + ".tmp", sys.argv[1])+deadline = time.time() + 120+while time.time() < deadline:+ try:+ conn, _ = s.accept()+ conn.close()+ except socket.timeout:+ pass+' "$port_file" >/dev/null 2>&1 &+ _HELD_PORT_PID=$!+ for _ in $(seq 1 50); do+ [ -s "$port_file" ] && break+ sleep 0.1+ done+ _HELD_PORT="$(cat "$port_file")"+}++_release_port() {+ if [ -n "$_HELD_PORT_PID" ]; then+ kill "$_HELD_PORT_PID" 2>/dev/null || true+ wait "$_HELD_PORT_PID" 2>/dev/null || true+ _HELD_PORT_PID=""+ _HELD_PORT=""+ fi+}++# A port nothing listens on: bind an ephemeral one, then let it go.+_free_port() {+ python3 -c '+import socket+s = socket.socket()+s.bind(("127.0.0.1", 0))+print(s.getsockname()[1])+s.close()+'+}++test_with_server_refuses_ports_already_in_use() {+ if ! command -v python3 >/dev/null 2>&1; then+ echo "skipping occupied-port tests: python3 not available" >&2+ return 0+ fi++ local tmp held+ tmp="$(mktemp -d)"+ trap '_release_port; rm -rf "$tmp"' RETURN+ _hold_port "$tmp"+ held="$_HELD_PORT"++ # label | .env mutation (sed) | ambient env | expected setting in the message+ local cases="env-file PORT|s/^PORT=8080/PORT=$held/||PORT=<free port>+ambient PORT beats .env||PORT=$held|PORT=<free port>+env-file BACKEND_PORT|s/^# BACKEND_PORT=8080/BACKEND_PORT=$held/||PORT=<free port>+env-file FRONTEND_PORT|s/^FRONTEND_PORT=3000/FRONTEND_PORT=$held/||FRONTEND_PORT=<free port>"++ local label mutation ambient setting+ while IFS='|' read -r label mutation ambient setting; do+ [ -n "$label" ] || continue++ rm -rf "$tmp/server" "$tmp/stub-bin"+ _setup_server_sandbox "$tmp"+ cp "$tmp/server/.env.example" "$tmp/server/.env"+ if [ -n "$mutation" ]; then+ sed "$mutation" "$tmp/server/.env" >"$tmp/server/.env.new"+ mv "$tmp/server/.env.new" "$tmp/server/.env"+ fi++ local -a extra=(MULTICA_TEST_COMPOSE_CONFIG=1)+ [ -z "$ambient" ] || extra+=("$ambient")+ if _run_with_server "$tmp" "${extra[@]}" >/dev/null 2>&1; then+ echo "[$label] installer must not continue when port $held is already in use" >&2+ cat "$tmp/install.out" >&2 || true+ return 1+ fi+ if ! grep -q "Port $held is already in use" "$tmp/install.err" ||+ ! grep -qF "$setting" "$tmp/install.err"; then+ echo "[$label] expected an actionable occupied-port error naming $held and $setting" >&2+ cat "$tmp/install.err" >&2 || true+ return 1+ fi+ if [ -f "$tmp/server/.stub-stack-up" ]; then+ echo "[$label] installer started the stack despite the occupied port" >&2+ return 1+ fi+ done <<<"$cases"+}++test_with_server_port_preflight_allows_free_and_own_ports() {+ if ! command -v python3 >/dev/null 2>&1; then+ echo "skipping occupied-port tests: python3 not available" >&2+ return 0+ fi++ local tmp held free+ tmp="$(mktemp -d)"+ trap '_release_port; rm -rf "$tmp"' RETURN++ # A free port goes straight through.+ free="$(_free_port)"+ _setup_server_sandbox "$tmp"+ sed "s/^PORT=8080/PORT=$free/" "$tmp/server/.env.example" >"$tmp/server/.env"+ _run_with_server "$tmp" MULTICA_TEST_COMPOSE_CONFIG=1 || return 1+ _require_server_ports "$tmp" "free port" "$free" "3000" || return 1++ # Re-running over this installation's own running stack: the port is busy+ # only because Compose already publishes it for us, which is not a conflict.+ _hold_port "$tmp"+ held="$_HELD_PORT"+ rm -rf "$tmp/server" "$tmp/stub-bin"+ _setup_server_sandbox "$tmp"+ sed "s/^PORT=8080/PORT=$held/" "$tmp/server/.env.example" >"$tmp/server/.env"+ _run_with_server "$tmp" MULTICA_TEST_COMPOSE_CONFIG=1 MULTICA_TEST_STACK_RUNNING=1 || return 1+ _require_server_ports "$tmp" "own running stack" "$held" "3000" || return 1+}+test_brew_install_failure_falls_back_to_release_binarytest_brew_tap_failure_falls_back_to_release_binarytest_remote_ssh_install_prints_token_login_hinttest_local_install_does_not_print_token_login_hinttest_with_server_uses_compose_published_portstest_with_server_fails_when_compose_port_is_unavailable+test_with_server_refuses_ports_already_in_use+test_with_server_port_preflight_allows_free_and_own_portstest_with_server_fails_when_checkout_does_not_landtest_cli_lookup_failure_does_not_claim_up_to_dateecho "install.sh tests passed"