Files
LocalAI/scripts/build/healthcheck.sh
Ettore Di Giacinto e7294b0984 feat(distributed): stop workers listening, and stop them advertising
A worker now opens no listener on a routable interface and states no endpoint at
registration. Backend processes and the file-transfer server bind loopback, and
the frontend reaches both through the tunnel the worker dials. The bind address
is built from loopbackHost, the same constant the tunnel's grpc tag dials, so
"the worker binds where its tunnel dials" is one fact in one place rather than
two literals that can drift.

All three advertisement sites are closed, not one: the registration body,
RegisterNodeRequest, and the per-backend address in the install reply.

That third one was hiding a live bug. stopModelExact refuses a stop whose
ExpectedAddress does not match what the worker recorded for the process. The
worker recorded 127.0.0.1:port; handleBackendInstall reported advertiseHost:port;
the router stored the reported one and sent it straight back. On any worker whose
advertise host was not 127.0.0.1, every acknowledged model stop failed with an
address mismatch. Nothing caught it because the e2e harness set
LOCALAI_ADVERTISE_ADDR=127.0.0.1, which made the rewrite a no-op. Removing the
rewrite makes the two strings the same by construction.

The brief was wrong about two of the four functions it called dead.
effectiveBasePort is the base of the backend port allocator and resolveHTTPAddr
is the file server's bind address; deleting them would have deleted the port
allocator and the file server. Only the two advertise* helpers were dead, and
addr_test.go is rewritten rather than deleted, because the port arithmetic it
pinned still needs pinning.

NodeModel.Address survives with a narrowed meaning and is renamed
WorkerLocalAddress, along with the install reply field that feeds it. The
frontend still has to say WHICH backend process on a worker it means, and the
port in this string is how it says it: it travels as a stream target and the
worker dials its own loopback. The gorm column and the json key stay "address",
so neither a migration nor an API break rides along. Every fall-back to the
node's address is gone. installBackendOnNode now errors when a worker reports
success without naming one, because substituting the now-always-empty node
address would name an empty target, and the worker refuses that as an invalid
stream, which is classified as the worker answering about its backend. That is
the "a present worker reads as something it is not" class this phase forbids.

DistributedModelStore.Range had the same shape and was already wrong: it built
each remote model's client from the node's base gRPC port, never the port a
backend process listens on, so Free and Status went to the wrong place. It uses
the replica's address now.

BackendNode.Address and HTTPAddress are kept but made provably inert: no writer,
no reader that acts on them, and Register force-clears both on re-registration so
an upgraded worker's stale advertisement does not outlive its own upgrade in the
API and the Nodes page. Dropping the columns is a ~90-site edit across the specs,
the e2e suite, the MCP dto and the UI; it is recorded as a follow-up rather than
folded in here.

A persistent tunnel 401 still does not trigger re-registration, and now for a
reason rather than a deferral. Register CLEARS the node's replica rows, so
re-registering on a 401 would delete a live worker's rows on every retry, and
under the name collision that causes the 401 the two workers would take turns
doing it forever: a credential failure causing model reclamation. It also cannot
fix the named cause, since a collision is indistinguishable from a restart. The
401 log now names both causes and says nothing can reach this worker, which is
true only now that it has no listener.

The container healthcheck did not break the way the brief expected, since the
listener still exists on loopback and the probe runs inside the container. It did
have a real #10987 defect that this change makes the common case: it read
LOCALAI_SERVE_ADDR only, while effectiveBasePort reads LOCALAI_ADDR first, so a
worker on a non-default base port was probed on 50050 and reported unhealthy
while working. It follows the same precedence now.

Docs, the compose file and the e2e harness are updated in step: no inbound rule
or published port is needed for a worker, the two advertise variables are gone,
the remaining address variables are read for their port only, the
firewall-the-file-transfer-port warning is narrowed to the LOCALAI_HTTP_ADDR
opt-out, and the upgrade-order note no longer claims the worker still listens.
The Nodes page showed node.address, which is now always blank, so it shows the
node id instead.

Eight mutations, all red on a named spec, including reverting the loopback bind,
re-adding the address to the registration body, restoring both node-address
fall-backs, dropping the force-clear, storing the endpoint's address again, and
un-fixing the healthcheck. One of them caught a defect in a spec I had just
written: it asserted 200 where the endpoint returns 201, which went unnoticed
because core/http/endpoints/localai is not on the task's verify list. It is run
here.

Assisted-by: Claude Opus 5 [claude-code]
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>
2026-09-20 03:05:34 +00:00

147 lines
6.4 KiB
Bash
Executable File

#!/bin/bash
# Docker HEALTHCHECK command for the LocalAI image.
#
# The image is a single artifact that runs several different processes, and they
# do not all serve HTTP on the same port — or at all. A hardcoded
# `curl -f http://localhost:8080/readyz` therefore reported every `local-ai
# worker` container as permanently `unhealthy` (issue #10987), which is worse
# than no healthcheck: a genuinely broken worker and a perfectly good one both
# read `unhealthy`, so the signal carries no information.
#
# The endpoint is derived from the mode the container is actually running plus
# the same env vars that configure the bind address, so a frontend moved off
# 8080 and a worker on a non-default base port are both probed correctly.
#
# Precedence:
# 1. HEALTHCHECK_ENDPOINT, if set — the documented escape hatch, and what
# docker-compose.distributed.yaml has been shipping as a workaround.
# 2. Derived from the running mode.
# 3. The frontend endpoint, when the mode cannot be determined.
#
# Ports are read from environment variables only, which is how containers are
# configured in practice (compose/k8s set LOCALAI_ADDRESS, LOCALAI_ADDR,
# LOCALAI_SERVE_ADDR, ...). If you instead pass the bind address as a CLI flag,
# set HEALTHCHECK_ENDPOINT to match.
set -u
# Detect the arguments local-ai was started with. PID 1 is the usual case
# (entrypoint.sh exec's local-ai, so it inherits PID 1), but `init: true` puts
# docker-init there instead, so fall back to scanning /proc. Reading /proc
# directly avoids depending on ps/pgrep being installed in every image variant.
detect_argv() {
if [ -n "${LOCALAI_HEALTHCHECK_ARGV:-}" ]; then
printf '%s' "$LOCALAI_HEALTHCHECK_ARGV"
return
fi
local cmdline proc pid d
# LOCALAI_HEALTHCHECK_PROC exists so the regression test can point this at a
# fixture tree; nothing in the image sets it.
local procfs="${LOCALAI_HEALTHCHECK_PROC:-/proc}"
# PID 1 first: entrypoint.sh exec's local-ai, so it normally *is* PID 1.
# Only when something else holds PID 1 (`init: true` puts docker-init there)
# do we scan, lowest PID first so the answer is deterministic if a container
# somehow has more than one local-ai process. The healthcheck's own shell is
# skipped: its argv mentions the script path, not a mode.
# Sort on the PID itself rather than the whole path, so 7 comes before 64.
for pid in 1 $(for d in "$procfs"/[0-9]*; do basename "$d"; done | sort -n); do
proc="$procfs/$pid"
[ -r "$proc/cmdline" ] || continue
cmdline=$(tr '\0' ' ' < "$proc/cmdline" 2>/dev/null) || continue
case "$cmdline" in
*healthcheck.sh*) continue ;;
*local-ai*)
printf '%s' "$cmdline"
return
;;
esac
done
}
# Extract the port from a bind address. Accepts ":8080", "0.0.0.0:8080" and
# "host:8080"; prints nothing when there is no port to find.
port_of() {
case "$1" in
*:*) printf '%s' "${1##*:}" ;;
esac
}
# The mode is the first non-flag word after the local-ai binary.
#
# `run` is kong's default command, and it is declared `default:"withargs"` — so
# `local-ai gemma-4 whisper` is the *frontend* with two model arguments, not a
# command called "gemma-4". Unrecognised words must therefore fall through to
# the frontend; treating them as an unknown mode would silently stop probing the
# single most common invocation in the docs.
detect_mode() {
local seen_binary=0 word
for word in $1; do
if [ "$seen_binary" = 0 ]; then
case "$word" in
*local-ai) seen_binary=1 ;;
esac
continue
fi
case "$word" in
-*) continue ;;
*) printf '%s' "$word"; return ;;
esac
done
printf 'run'
}
endpoint="${HEALTHCHECK_ENDPOINT:-}"
if [ -z "$endpoint" ]; then
mode=$(detect_mode "$(detect_argv)")
case "$mode" in
worker)
# The worker's file-transfer server (which also serves /readyz and
# /healthz) binds LOCALAI_HTTP_ADDR when set, otherwise the gRPC
# base port minus one. See Config.resolveHTTPAddr.
#
# The base port comes from LOCALAI_ADDR first and LOCALAI_SERVE_ADDR
# second, which is Config.effectiveBasePort's own order. Reading
# only the second one meant a worker configured with LOCALAI_ADDR
# (the documented knob; LOCALAI_SERVE_ADDR is marked hidden) was
# probed on the default 50050 while its server sat on a different
# port. That is #10987 again: a working worker reporting
# `unhealthy` forever because the probe went somewhere nothing
# binds.
#
# The worker binds loopback, which is where this probe runs: it runs
# inside the container, so no inbound port is needed for it to work.
port=$(port_of "${LOCALAI_HTTP_ADDR:-}")
if [ -z "$port" ]; then
base=$(port_of "${LOCALAI_ADDR:-}")
if [ -z "$base" ]; then
base=$(port_of "${LOCALAI_SERVE_ADDR:-}")
fi
port=$(( ${base:-50051} - 1 ))
fi
endpoint="http://localhost:${port}/readyz"
;;
agent-worker|p2p-worker|chat|models|backends|tts|sound-generation|transcript|util|agent|mcp-server|completion)
# Modes with no HTTP surface of their own — agent-worker and
# p2p-worker are message-bus only, and the rest are one-shot
# commands that exit on their own. Claiming `unhealthy` for a
# process that was never going to bind a port is the same false
# signal as #10987, one mode over.
exit 0
;;
*)
# run / federated / explorer, and anything unrecognised: kong's
# default command is `run`, so a bare `local-ai`, `local-ai --flag`
# and `local-ai <model-name>` are all frontends on the API port.
port=$(port_of "${LOCALAI_ADDRESS:-${ADDRESS:-}}")
endpoint="http://localhost:${port:-8080}/readyz"
;;
esac
fi
# Docker only distinguishes 0 from non-zero; normalise curl's exit codes (22 for
# the 503 a still-preloading frontend returns, 7 for connection refused) to 1 so
# the status is unambiguous in `docker inspect`.
curl -fsS -m 10 "$endpoint" >/dev/null 2>&1 || exit 1
exit 0