diff --git a/README.md b/README.md index 4ab0b40..6105e43 100644 --- a/README.md +++ b/README.md @@ -212,7 +212,7 @@ See **[docs/DOCKER.md](./docs/DOCKER.md)** for the run command, MCP client confi | `LOCALSTACK_AUTH_TOKEN` (**required**) | The LocalStack Auth Token to use for the MCP server | None | | `LOCALSTACK_HOSTNAME` | Host name of the LocalStack gateway the tools call; in Docker, `host.docker.internal`. The Azure tool always calls `azure.localhost.localstack.cloud` (127.0.0.1), so it needs a local gateway. | `localhost` | | `LOCALSTACK_PORT` | Port of the LocalStack gateway the tools call. | `4566` | -| `MAIN_CONTAINER_NAME` | The explicit LocalStack container name to use for Docker-based tools. When unset, the server auto-detects standard LocalStack containers such as `localstack-main` and `localstack-aws`, then LocalStack Docker images. | Auto-detect | +| `MAIN_CONTAINER_NAME` | Container name for Docker-based tools and the container `start` creates. When unset, `start` uses `localstack-main`; the tools find it, lstk's containers, then LocalStack images ([lstk](#using-lstk)). | Auto-detect | | `LOCALSTACK_IMAGE_NAME` / `IMAGE_NAME` | Docker image the `start` action launches for the AWS stack. `LOCALSTACK_IMAGE_NAME` wins when both are set (beware: bare `IMAGE_NAME` is a common CI variable). | `localstack/localstack-pro:latest` | | `LOCALSTACK_VOLUME_DIR` | Host directory mounted at `/var/lib/localstack` in the LocalStack container. Defaults to the same per-OS cache path the LocalStack CLI used (state carries over); inside Docker it defaults to the `localstack-mcp` named volume. | Per-OS cache dir | | `GATEWAY_LISTEN` | Override the gateway port bindings for `start` (comma-separated `[host]:port`). When set, the implicit `443` binding is skipped. | `:4566,:443` | @@ -239,10 +239,29 @@ Since v0.6.0 the MCP server no longer uses (or requires) the `localstack` CLI. T - `~/.localstack/*.env` config profiles and `DOCKER_FLAGS` are **not** read at start. Pass configuration through the `envVars` argument of the `localstack-management` start action, or set `LOCALSTACK_`-prefixed variables in the MCP server's environment (LocalStack aliases `LOCALSTACK_` to `` natively). - Besides `LOCALSTACK_*`/`PROVIDER_OVERRIDE_*`, only a curated set of common unprefixed config variables is forwarded from the host environment (`DEBUG`, `LS_LOG`, `SERVICES`, `PERSISTENCE`, `EAGER_SERVICE_LOADING`, `ENFORCE_IAM`, `IAM_SOFT_MODE`, `EXTENSION_AUTO_INSTALL`, `APP_INSPECTOR`, `DNS_ADDRESS`, `MAIN_DOCKER_NETWORK`, and the `LAMBDA_*`/`CFN_*`/`SNOWFLAKE_*`/`SF_*` families). - Port 443 is published by default. If something else uses port 443 locally, set `GATEWAY_LISTEN=:4566` to skip it. -- If you previously used `lstk`, note the container the server creates is named `localstack-main` (externally started `localstack-aws` containers are still detected and managed; `restart` preserves their name, image, and volume). +- The container the server creates is named `localstack-main`, not lstk's `localstack-aws`. See [Using lstk](#using-lstk). For AWS Replicator-specific source credentials, you can use the `AWS_REPLICATOR_SOURCE_` prefixed variants instead of the unprefixed variants. Do not mix the prefixed and unprefixed source credential groups; when any `AWS_REPLICATOR_SOURCE_` variable is set, the Replicator tool reads the source configuration only from that group. +### Using lstk + +[lstk](https://docs.localstack.cloud/aws/developer-tools/running-localstack/lstk/) names its container `localstack-{type}`, such as `localstack-aws`, or `localstack-{type}-{tag}` when it runs a pinned tag. The server names the container it creates `localstack-main`. It finds lstk's containers under these names, or under any name by the `cloud.localstack.lstk` label lstk sets. + +To have both tools manage one container, set lstk's [`container_name`](https://docs.localstack.cloud/aws/developer-tools/running-localstack/lstk/configuration/) to `localstack-main`: + +```toml +[[containers]] +type = "aws" +port = "4566" +container_name = "localstack-main" +``` + +Then lstk finds the container by name, whichever tool started it. + +Without that setting, the server still finds and manages lstk's container: `stop` and `status` act on it, `restart` keeps its name, image, volume and lstk's labels (the gateway moves to `LOCALSTACK_PORT`, where the tools reach it), and `start` reports it as a conflict when it holds a port `start` needs. When `LOCALSTACK_PORT` is set, the tools that use Docker (`stop`, `restart`, logs, the deployer and others) act only on a container that publishes that port, or that publishes no ports at all, such as one on the host network. lstk, for its part, falls back to the first running container with a standard LocalStack image that publishes port 4566, so it may find the server's container, or another one when several run. + +The two tools keep state in different directories, even under one container name. lstk uses `/lstk/volume/`, which does not change with `container_name`, and the server uses the LocalStack CLI's `/localstack/volume`. To share state, point one at the other: set `volume` in lstk's config, or `LOCALSTACK_VOLUME_DIR` for the server. + ## Contributing Built on the [XMCP](https://github.com/basementstudio/xmcp) framework, you can add new tools by adding a new file to the `src/tools` directory and documenting it in the `manifest.json` file. diff --git a/docs/DOCKER.md b/docs/DOCKER.md index 0b2be46..4f1fde4 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -134,7 +134,7 @@ that still pass `--add-host s3.host.docker.internal:host-gateway` keep working. | Tools report `LocalStack Not Running` after `start` | Check `LOCALSTACK_HOSTNAME=host.docker.internal` is set and `--add-host` is present (Linux). | | `Auth Token Required` | `LOCALSTACK_AUTH_TOKEN` must be passed through (every tool requires it). | | `Docker Not Available` / daemon unreachable | Ensure `/var/run/docker.sock` is mounted (or pass `DOCKER_HOST` for a non-default daemon). | -| `LocalStack container not found` or `Could not find a running LocalStack container named "localstack-main"` | Set `MAIN_CONTAINER_NAME` if you use a custom LocalStack container name. | +| `LocalStack container not found` or `Could not find a running LocalStack container named "localstack-main"` | The server finds `localstack-main`, `localstack-{type}` and containers lstk started. Set `MAIN_CONTAINER_NAME` for another name ([lstk](../README.md#using-lstk)). | | State disappeared after upgrading the image | Old configs stored state under `$XDG_CACHE_HOME/localstack/volume` — keep that env var, or point `LOCALSTACK_VOLUME_DIR` at the old directory. | | MCP server containers pile up over time | Older images did not exit when the client disconnected. Pull the latest image, then remove strays with `docker ps -aq --filter ancestor=localstack/localstack-mcp-server \| xargs docker rm -f`. | @@ -163,6 +163,24 @@ Use `HARNESS_SKIP` to skip scenarios, for example: HARNESS_SKIP=docs,cloudpods,ephemeral,replicator ``` +`tests/docker/validate-lstk.mjs` checks [lstk](../README.md#using-lstk) interop: lstk +starts the AWS emulator with a pinned tag on port 4577, the server restarts it, and lstk +still finds it. It needs `lstk` on `PATH` and free host ports 443 and 4510-4560. A tag +that exists only locally avoids a second image download: + +```bash +docker tag localstack/localstack-pro:latest localstack/localstack-pro:mcp-ci +LOCALSTACK_AUTH_TOKEN="" \ +node tests/docker/validate-lstk.mjs -- \ + docker run -i --rm \ + -v /var/run/docker.sock:/var/run/docker.sock \ + --add-host host.docker.internal:host-gateway \ + -e LOCALSTACK_AUTH_TOKEN \ + -e LOCALSTACK_HOSTNAME=host.docker.internal \ + -e LOCALSTACK_PORT=4577 \ + localstack/localstack-mcp-server:latest +``` + ## Tool versions in the image Each tool's version is pinned in one file, and Dependabot opens the update PRs once a diff --git a/server.json b/server.json index 15a43d8..d245d77 100644 --- a/server.json +++ b/server.json @@ -124,7 +124,7 @@ "name": "GATEWAY_LISTEN" }, { - "description": "Explicit LocalStack container name for Docker-based tools and the container created by start. Defaults to localstack-main (auto-detection covers common names).", + "description": "Explicit LocalStack container name for Docker-based tools and the container created by start. Defaults to localstack-main; detection also finds containers lstk started, such as localstack-aws.", "isRequired": false, "format": "string", "isSecret": false, diff --git a/src/lib/docker/docker.client.test.ts b/src/lib/docker/docker.client.test.ts index 51cdc3b..61237dc 100644 --- a/src/lib/docker/docker.client.test.ts +++ b/src/lib/docker/docker.client.test.ts @@ -1,4 +1,8 @@ -import { DockerApiClient } from "./docker.client"; +import { + DockerApiClient, + isGatewayPortMismatchError, + isLocalStackContainerNotFoundError, +} from "./docker.client"; import { PassThrough } from "stream"; jest.mock("dockerode", () => { @@ -286,10 +290,324 @@ describe("DockerApiClient", () => { const client = new DockerApiClient(); await expect(client.findLocalStackContainer()).rejects.toThrow( - /Could not find a running LocalStack container named "localstack-main"/i + /Could not find a running LocalStack container named "localstack-main", "localstack-aws", "localstack-snowflake" or "localstack-azure", or a container lstk started/i ); }); + test("findLocalStackContainer matches lstk's per-stack names for images it does not recognize", async () => { + // lstk names containers localstack-{type}; snowflake-next is a preview image lstk + // runs with --image, which the image fallback does not know. + for (const name of ["localstack-snowflake", "localstack-azure"]) { + const mocks = getDockerMocks(); + mocks.listContainers.mockResolvedValueOnce([ + { Id: `${name}-id`, Names: [`/${name}`], Image: "localstack/snowflake-next:latest" }, + ]); + const client = new DockerApiClient(); + await expect(client.findLocalStackContainer()).resolves.toBe(`${name}-id`); + } + }); + + test("findLocalStackContainer matches lstk's names with a pinned tag", async () => { + // lstk names the container localstack-{type}-{tag} when the tag is not "latest". + const mocks = getDockerMocks(); + mocks.listContainers.mockResolvedValueOnce([ + { Id: "other", Names: ["/localstack-gcp"], Image: "localstack/snowflake-next:latest" }, + { + Id: "snow-tagged", + Names: ["/localstack-snowflake-1.4"], + Image: "localstack/snowflake-next:1.4", + Labels: { "cloud.localstack.lstk": "true" }, + }, + ]); + const client = new DockerApiClient(); + await expect(client.findLocalStackContainer()).resolves.toBe("snow-tagged"); + }); + + test("findLocalStackContainer skips Lambda containers named after a tagged lstk container", async () => { + // LocalStack names Lambda containers "-lambda-...", without lstk's label. + const mocks = getDockerMocks(); + mocks.listContainers.mockResolvedValueOnce([ + { + Id: "fn", + Names: ["/localstack-aws-dev-lambda-fn-1234"], + Image: "public.ecr.aws/lambda/python:3.13", + }, + { + Id: "lstk-dev", + Names: ["/localstack-aws-dev"], + Image: "sha256:a4a2ec94512d", + Labels: { "cloud.localstack.lstk": "true" }, + }, + ]); + const client = new DockerApiClient(); + await expect(client.findLocalStackContainer()).resolves.toBe("lstk-dev"); + }); + + test("findLocalStackContainer finds an lstk container with a custom container_name", async () => { + const mocks = getDockerMocks(); + mocks.listContainers.mockResolvedValueOnce([ + { + Id: "custom", + Names: ["/my-ls"], + Image: "registry.example/ls:1", + Labels: { "cloud.localstack.lstk": "true" }, + }, + ]); + const client = new DockerApiClient(); + await expect(client.findLocalStackContainer()).resolves.toBe("custom"); + }); + + test("findLocalStackContainer prefers lstk's latest name over a tagged one", async () => { + const mocks = getDockerMocks(); + mocks.listContainers.mockResolvedValueOnce([ + { + Id: "tagged", + Names: ["/localstack-aws-2026.4"], + Image: "registry.example/ls:1", + Labels: { "cloud.localstack.lstk": "true" }, + }, + { Id: "latest", Names: ["/localstack-aws"], Image: "registry.example/ls:1" }, + ]); + const client = new DockerApiClient(); + await expect(client.findLocalStackContainer()).resolves.toBe("latest"); + }); + + test("listKnownLocalStackContainers returns known names in any state, in detection order", async () => { + const mocks = getDockerMocks(); + const custom = { + Id: "c", + Names: ["/my-ls"], + State: "exited", + Labels: { "cloud.localstack.lstk": "true" }, + }; + mocks.listContainers.mockImplementation(async (opts: any) => + opts.filters?.label ? [custom, byName.find((c) => c.Id === "a")] : byName + ); + const byName: any[] = [ + { Id: "s", Names: ["/localstack-snowflake"], State: "exited" }, + { Id: "x", Names: ["/localstack-mcp-server-1"], State: "running" }, + { Id: "fn", Names: ["/localstack-aws-2026.4-lambda-fn-1"], State: "created" }, + { + Id: "a", + Names: ["/localstack-aws-2026.4"], + State: "running", + Image: "localstack/localstack-pro:2026.4", + Labels: { "cloud.localstack.lstk": "true" }, + Ports: [{ PrivatePort: 4566, PublicPort: 4566, Type: "tcp" }, { PrivatePort: 53 }], + }, + { Id: "m", Names: ["/localstack-main"], State: "created" }, + ]; + const client = new DockerApiClient(); + const found = await client.listKnownLocalStackContainers(); + expect(mocks.listContainers).toHaveBeenCalledWith({ + all: true, + filters: { name: ["localstack-"] }, + }); + expect(mocks.listContainers).toHaveBeenCalledWith({ + all: true, + filters: { label: ["cloud.localstack.lstk=true"] }, + }); + expect(found).toEqual([ + { + id: "m", + name: "localstack-main", + state: "created", + image: undefined, + running: false, + publicPorts: [], + }, + { + id: "a", + name: "localstack-aws-2026.4", + state: "running", + image: "localstack/localstack-pro:2026.4", + running: true, + labels: { "cloud.localstack.lstk": "true" }, + publicPorts: [4566], + }, + { + id: "s", + name: "localstack-snowflake", + state: "exited", + image: undefined, + running: false, + publicPorts: [], + }, + { + id: "c", + name: "my-ls", + state: "exited", + image: undefined, + running: false, + labels: { "cloud.localstack.lstk": "true" }, + publicPorts: [], + }, + ]); + }); + + test("findLocalStackContainer prefers a LocalStack image on the gateway port over a known name off it", async () => { + // The HTTP tools talk to the gateway port (4566), so Docker actions must target the + // container behind it, not lstk's container from another project on 4567. + const mocks = getDockerMocks(); + mocks.listContainers.mockResolvedValueOnce([ + { + Id: "lstk-other-project", + Names: ["/localstack-aws-4.0"], + Image: "localstack/localstack-pro:4.0", + Labels: { "cloud.localstack.lstk": "true" }, + Ports: [{ PrivatePort: 4566, PublicPort: 4567, Type: "tcp" }], + }, + { + Id: "compose", + Names: ["/my-ls"], + Image: "localstack/localstack-pro:latest", + Ports: [{ PrivatePort: 4566, PublicPort: 4566, Type: "tcp" }], + }, + ]); + const client = new DockerApiClient(); + await expect(client.findLocalStackContainer()).resolves.toBe("compose"); + }); + + test("findLocalStackContainer picks the known name on the configured gateway port", async () => { + // lstk in two projects can run localstack-aws on 4566 and localstack-snowflake on 4567. + process.env.LOCALSTACK_PORT = "4567"; + const mocks = getDockerMocks(); + mocks.listContainers.mockResolvedValueOnce([ + { + Id: "aws", + Names: ["/localstack-aws"], + Image: "localstack/localstack-pro:latest", + Ports: [{ PrivatePort: 4566, PublicPort: 4566, Type: "tcp" }], + }, + { + Id: "snow", + Names: ["/localstack-snowflake"], + Image: "localstack/snowflake:latest", + Ports: [{ PrivatePort: 4566, PublicPort: 4567, Type: "tcp" }], + }, + ]); + + const client = new DockerApiClient(); + await expect(client.findLocalStackContainer()).resolves.toBe("snow"); + }); + + test("findLocalStackContainer skips a known container off an explicit LOCALSTACK_PORT", async () => { + // Another lstk project on 4566 must not be stopped or recreated on 4567. + process.env.LOCALSTACK_PORT = "4567"; + const mocks = getDockerMocks(); + mocks.listContainers.mockResolvedValueOnce([ + { + Id: "dev", + Names: ["/localstack-aws-dev"], + Image: "localstack/localstack-pro:latest", + Labels: { "cloud.localstack.lstk": "true" }, + Ports: [{ PrivatePort: 4566, PublicPort: 4566, Type: "tcp" }], + }, + ]); + + const client = new DockerApiClient(); + await expect(client.findLocalStackContainer()).rejects.toThrow( + /none publishes the configured gateway port 4567/i + ); + }); + + test("findLocalStackContainer skips localstack-main off an explicit LOCALSTACK_PORT, even with a custom image", async () => { + process.env.LOCALSTACK_PORT = "4567"; + const mocks = getDockerMocks(); + mocks.listContainers.mockResolvedValueOnce([ + { + Id: "mcp", + Names: ["/localstack-main"], + Image: "registry.example/ls:1", + Ports: [{ PrivatePort: 4566, PublicPort: 4566, Type: "tcp" }], + }, + ]); + + const client = new DockerApiClient(); + await expect(client.findLocalStackContainer()).rejects.toThrow( + /none publishes the configured gateway port 4567/i + ); + }); + + test("findLocalStackContainer finds localstack-main started with GATEWAY_LISTEN on an explicit LOCALSTACK_PORT", async () => { + // GATEWAY_LISTEN=:4567 publishes the gateway as 4567->4567. + process.env.LOCALSTACK_PORT = "4567"; + const mocks = getDockerMocks(); + mocks.listContainers.mockResolvedValueOnce([ + { + Id: "mcp", + Names: ["/localstack-main"], + Image: "localstack/localstack-pro:latest", + Ports: [{ PrivatePort: 4567, PublicPort: 4567, Type: "tcp" }], + }, + ]); + + const client = new DockerApiClient(); + await expect(client.findLocalStackContainer()).resolves.toBe("mcp"); + }); + + test("findLocalStackContainer finds localstack-main on the host network with an explicit LOCALSTACK_PORT", async () => { + process.env.LOCALSTACK_PORT = "4566"; + const mocks = getDockerMocks(); + mocks.listContainers.mockResolvedValueOnce([ + { Id: "mcp", Names: ["/localstack-main"], Image: "localstack/localstack-pro:latest", Ports: [] }, + ]); + + const client = new DockerApiClient(); + await expect(client.findLocalStackContainer()).resolves.toBe("mcp"); + }); + + test("findLocalStackContainer names the containers and their gateway ports when none is on LOCALSTACK_PORT", async () => { + process.env.LOCALSTACK_PORT = "4567"; + const mocks = getDockerMocks(); + mocks.listContainers.mockResolvedValueOnce([ + { + Id: "mcp", + Names: ["/localstack-main"], + Image: "localstack/localstack-pro:latest", + Ports: [ + { PrivatePort: 4566, PublicPort: 4566, Type: "tcp" }, + { PrivatePort: 4566, PublicPort: 4566, Type: "tcp" }, + ], + }, + ]); + + const client = new DockerApiClient(); + const error = await client.findLocalStackContainer().catch((e: Error) => e); + expect(isGatewayPortMismatchError(error)).toBe(true); + expect(isLocalStackContainerNotFoundError(error)).toBe(true); + expect((error as Error).message).toContain('"localstack-main" (gateway on 4566)'); + expect((error as Error).message).toContain("Set LOCALSTACK_PORT"); + }); + + test("findLocalStackContainer keeps a known container on an explicit LOCALSTACK_PORT", async () => { + process.env.LOCALSTACK_PORT = "4567"; + const mocks = getDockerMocks(); + mocks.listContainers.mockResolvedValueOnce([ + { + Id: "tagged", + Names: ["/localstack-aws-mcp-ci"], + Image: "localstack/localstack-pro:mcp-ci", + Labels: { "cloud.localstack.lstk": "true" }, + Ports: [{ PrivatePort: 4566, PublicPort: 4567, Type: "tcp" }], + }, + ]); + + const client = new DockerApiClient(); + await expect(client.findLocalStackContainer()).resolves.toBe("tagged"); + }); + + test("findLocalStackContainer prefers localstack-main over lstk's localstack-aws", async () => { + const mocks = getDockerMocks(); + mocks.listContainers.mockResolvedValueOnce([ + { Id: "lstk", Names: ["/localstack-aws"], Image: "registry.example/ls:1" }, + { Id: "mcp", Names: ["/localstack-main"], Image: "registry.example/ls:1" }, + ]); + + const client = new DockerApiClient(); + await expect(client.findLocalStackContainer()).resolves.toBe("mcp"); + }); + test("stopContainer stops the container via the Docker API", async () => { const mocks = getDockerMocks(); mocks.stop.mockResolvedValueOnce(undefined); @@ -334,6 +652,7 @@ describe("DockerApiClient", () => { Config: { Image: "localstack/localstack-pro:latest", Env: ["MAIN_CONTAINER_NAME=localstack-aws"], + Labels: { "cloud.localstack.lstk": "true" }, }, Mounts: [ { @@ -350,6 +669,7 @@ describe("DockerApiClient", () => { name: "localstack-aws", image: "localstack/localstack-pro:latest", env: ["MAIN_CONTAINER_NAME=localstack-aws"], + labels: { "cloud.localstack.lstk": "true" }, mounts: [ { type: "bind", diff --git a/src/lib/docker/docker.client.ts b/src/lib/docker/docker.client.ts index a4ef3bb..2e8198a 100644 --- a/src/lib/docker/docker.client.ts +++ b/src/lib/docker/docker.client.ts @@ -1,7 +1,13 @@ import { PassThrough } from "stream"; import { createRequire } from "node:module"; import { LOCALSTACK_PORT } from "../../core/config"; -import type { LocalStackContainerSpec } from "../localstack/container-spec.logic"; +import { + configuredContainerName, + KNOWN_CONTAINER_NAMES_DESCRIPTION, + knownContainerNameRank, + LSTK_MANAGED_LABEL, + type LocalStackContainerSpec, +} from "../localstack/container-spec.logic"; export interface ContainerExecResult { stdout: string; @@ -15,6 +21,19 @@ export interface ContainerStateInfo { state: string; image?: string; running: boolean; + /** Host ports the container publishes (only known for a running container). */ + publicPorts: number[]; + labels?: Record; +} + +/** The fields of a Docker container list entry the client reads. */ +interface DockerContainerSummary { + Id: string; + Names?: string[]; + State?: string; + Image?: string; + Labels?: Record; + Ports?: Array<{ PublicPort?: number }>; } /** @@ -106,6 +125,7 @@ export interface ContainerMetadata { image?: string; env?: string[]; mounts?: ContainerMountInfo[]; + labels?: Record; } export class LocalStackContainerNotFoundError extends Error { @@ -115,10 +135,31 @@ export class LocalStackContainerNotFoundError extends Error { } } +/** + * LocalStack containers run, but none publishes the configured LOCALSTACK_PORT. A + * not-found error for callers that only check that, but `stop` and `restart` report it + * instead of "not running", since a container does run. + */ +export class GatewayPortMismatchError extends LocalStackContainerNotFoundError { + constructor(message: string) { + super(message); + this.name = "GatewayPortMismatchError"; + } +} + export function isLocalStackContainerNotFoundError(error: unknown): boolean { return ( error instanceof LocalStackContainerNotFoundError || - (error instanceof Error && error.name === "LocalStackContainerNotFoundError") + (error instanceof Error && + (error.name === "LocalStackContainerNotFoundError" || + error.name === "GatewayPortMismatchError")) + ); +} + +export function isGatewayPortMismatchError(error: unknown): boolean { + return ( + error instanceof GatewayPortMismatchError || + (error instanceof Error && error.name === "GatewayPortMismatchError") ); } @@ -148,12 +189,35 @@ export class DockerApiClient { Ports?: Array<{ PrivatePort?: number; PublicPort?: number; Type?: string }>; }): boolean { const configuredPort = Number(process.env.LOCALSTACK_PORT || LOCALSTACK_PORT); + // Only the host port counts: with GATEWAY_LISTEN=:4567 the gateway listens on + // container port 4567, published as 4567->4567. return (container.Ports || []).some( - (port) => - port.Type === "tcp" && port.PrivatePort === 4566 && port.PublicPort === configuredPort + (port) => port.Type === "tcp" && port.PublicPort === configuredPort ); } + /** + * Whether the tools may reach this container's gateway on LOCALSTACK_PORT. A container + * that publishes no ports, such as one on the host network, cannot be ruled out. + */ + private mayServeConfiguredGatewayPort(container: { + Ports?: Array<{ PrivatePort?: number; PublicPort?: number; Type?: string }>; + }): boolean { + const published = (container.Ports || []).some((port) => port.PublicPort !== undefined); + return !published || this.publishesConfiguredGatewayPort(container); + } + + private describeGatewayPorts(container: { + Names?: string[]; + Ports?: Array<{ PrivatePort?: number; PublicPort?: number; Type?: string }>; + }): string { + const name = this.normalizeContainerName(container.Names?.[0]) || "unnamed"; + const gateway = (container.Ports || []).find( + (port) => port.Type === "tcp" && port.PrivatePort === 4566 && port.PublicPort !== undefined + ); + return gateway ? `"${name}" (gateway on ${gateway.PublicPort})` : `"${name}"`; + } + private hasLocalStackImage(container: { Image?: string }): boolean { return /^(?:[^/]+\/)?localstack\/(?:localstack(?:-pro)?|snowflake|localstack-azure(?:-alpha)?)(?::|@|$)/.test( container.Image || "" @@ -191,12 +255,51 @@ export class DockerApiClient { ); } - private findByKnownLocalStackName( + /** The container's first name that the server recognizes, and its detection rank. */ + private knownName(container: { + Names?: string[]; + Labels?: Record; + }): { name: string; rank: number } | undefined { + return (container.Names || []) + .map((n) => this.normalizeContainerName(n)) + .map((name) => ({ name, rank: knownContainerNameRank(name, container.Labels) })) + .filter((entry): entry is { name: string; rank: number } => entry.rank !== undefined) + .sort((a, b) => a.rank - b.rank)[0]; + } + + /** Containers under a known name, in detection order (see `knownContainerNameRank`). */ + private sortByKnownName }>( containers: T[] - ): T | undefined { - return ["localstack-main", "localstack-aws"] - .map((name) => containers.find((c) => this.matchesConfiguredContainerName(c, name))) - .find(Boolean); + ): Array<{ container: T; name: string }> { + return containers + .map((container) => ({ container, known: this.knownName(container) })) + .filter( + (entry): entry is { container: T; known: { name: string; rank: number } } => + entry.known !== undefined + ) + .sort((a, b) => a.known.rank - b.known.rank) + .map(({ container, known }) => ({ container, name: known.name })); + } + + /** + * The running container under a known LocalStack name. Several can run at once, for + * example lstk in two projects whose `.lstk/config.toml` set different ports, or a + * `localstack-main` beside them. When more than one runs, the one publishing the + * configured gateway port wins; otherwise detection order. + */ + private findByKnownLocalStackName< + T extends { + Names?: string[]; + Labels?: Record; + Ports?: Array<{ PrivatePort?: number; PublicPort?: number; Type?: string }>; + }, + >(containers: T[]): T | undefined { + const known = this.sortByKnownName(containers).map(({ container }) => container); + if (known.length > 1) { + const byGatewayPort = known.find((c) => this.publishesConfiguredGatewayPort(c)); + if (byGatewayPort) return byGatewayPort; + } + return known[0]; } async findLocalStackContainer(): Promise { @@ -206,36 +309,46 @@ export class DockerApiClient { Id: string; Names?: string[]; Image?: string; + Labels?: Record; Ports?: Array<{ PrivatePort?: number; PublicPort?: number; Type?: string }>; }>; - const explicitName = ( - process.env.MAIN_CONTAINER_NAME || - process.env.LOCALSTACK_MAIN_CONTAINER_NAME || - "" - ).trim(); - const configuredName = explicitName || "localstack-main"; + const explicitName = configuredContainerName(process.env); if (explicitName) { const byConfiguredName = (running || []).find((c) => - this.matchesConfiguredContainerName(c, configuredName) + this.matchesConfiguredContainerName(c, explicitName) ); if (byConfiguredName) return byConfiguredName.Id as string; } if (!explicitName) { - const byKnownName = this.findByKnownLocalStackName(running || []); - if (byKnownName) return byKnownName.Id as string; - + const explicitPort = Boolean(process.env.LOCALSTACK_PORT?.trim()); + const knownNames = this.findByKnownLocalStackName(running || []); + // With LOCALSTACK_PORT set, a known container must publish that port. Otherwise + // stop and restart could act on another project's container, such as an lstk + // container on 4566, and restart would move it to LOCALSTACK_PORT. + const byKnownName = + knownNames && (!explicitPort || this.mayServeConfiguredGatewayPort(knownNames)) + ? knownNames + : undefined; const localstackImages = (running || []).filter((c) => this.hasLocalStackImage(c)); const byGatewayPort = localstackImages.find((c) => this.publishesConfiguredGatewayPort(c)); + // A known container off the gateway port loses to a LocalStack image on it: the + // HTTP tools talk to the gateway port, so Docker actions must target that container. + if (byKnownName && !this.publishesConfiguredGatewayPort(byKnownName) && byGatewayPort) { + return byGatewayPort.Id as string; + } + if (byKnownName) return byKnownName.Id as string; if (byGatewayPort) return byGatewayPort.Id as string; - const explicitPort = Boolean(process.env.LOCALSTACK_PORT?.trim()); - if (explicitPort && localstackImages.length > 0) { - throw new LocalStackContainerNotFoundError( - `Found running LocalStack containers, but none publishes the configured gateway port ${process.env.LOCALSTACK_PORT}. ` + - `Set MAIN_CONTAINER_NAME to the container name to use.` + if (explicitPort && (knownNames || localstackImages.length > 0)) { + const found = [...new Set([knownNames, ...localstackImages].filter(Boolean))] + .map((c) => this.describeGatewayPorts(c!)) + .join(", "); + throw new GatewayPortMismatchError( + `Found running LocalStack containers (${found}), but none publishes the configured gateway port ${process.env.LOCALSTACK_PORT}. ` + + `Set LOCALSTACK_PORT to the gateway port of the container to use, or MAIN_CONTAINER_NAME to its name.` ); } @@ -248,8 +361,9 @@ export class DockerApiClient { } } + const lookedFor = explicitName ? `"${explicitName}"` : KNOWN_CONTAINER_NAMES_DESCRIPTION; throw new LocalStackContainerNotFoundError( - `Could not find a running LocalStack container named "${configuredName}". ` + + `Could not find a running LocalStack container named ${lookedFor}. ` + `Set MAIN_CONTAINER_NAME to your container name if it is custom.` ); } @@ -262,6 +376,7 @@ export class DockerApiClient { name: this.normalizeContainerName(inspect?.Name), image: inspect?.Config?.Image, env: inspect?.Config?.Env, + labels: inspect?.Config?.Labels || undefined, mounts: (inspect?.Mounts || []).map( (mount: { Type?: string; Name?: string; Source?: string; Destination?: string }) => ({ type: mount.Type, @@ -578,21 +693,58 @@ export class DockerApiClient { (this.docker.listContainers as any)({ all: true, filters: { name: [name] } }), 10000, "Docker container list" - )) as Array<{ Id: string; Names?: string[]; State?: string; Image?: string }>; + )) as Array; const match = (containers || []).find((container) => this.matchesConfiguredContainerName(container, name) ); if (!match) return null; + return this.toStateInfo(match, name); + } + + private toStateInfo(container: DockerContainerSummary, name: string): ContainerStateInfo { return { - id: match.Id, + id: container.Id, name, - state: match.State || "unknown", - image: match.Image, - running: match.State === "running", + state: container.State || "unknown", + image: container.Image, + running: container.State === "running", + labels: container.Labels, + publicPorts: (container.Ports || []) + .map((port) => port.PublicPort) + .filter((port): port is number => typeof port === "number"), }; } + /** + * Containers in any state that the server recognizes (`localstack-main` and lstk's + * containers, see `knownContainerNameRank`), in detection order. Ignores + * MAIN_CONTAINER_NAME; callers that honor it look the configured name up directly. + * Two filtered lists, merged: names containing `localstack-`, and lstk's label (an + * lstk container with a custom name has no common prefix). + */ + async listKnownLocalStackContainers(): Promise { + const list = (filters: Record) => + this.withDockerRequestTimeout( + (this.docker.listContainers as any)({ all: true, filters }) as Promise< + DockerContainerSummary[] + >, + 10000, + "Docker container list" + ); + const [byName, byLabel] = await Promise.all([ + list({ name: ["localstack-"] }), + list({ label: [`${LSTK_MANAGED_LABEL}=true`] }), + ]); + const unique = new Map(); + for (const container of [...(byName || []), ...(byLabel || [])]) { + unique.set(container.Id, container); + } + return this.sortByKnownName([...unique.values()]).map(({ container, name }) => + this.toStateInfo(container, name) + ); + } + /** Remove a container, tolerating it already being gone. */ async removeContainer(containerId: string, requestTimeoutMs = 60000): Promise { const container = this.docker.getContainer(containerId); diff --git a/src/lib/localstack/container-spec.logic.test.ts b/src/lib/localstack/container-spec.logic.test.ts index 3990cea..15177b8 100644 --- a/src/lib/localstack/container-spec.logic.test.ts +++ b/src/lib/localstack/container-spec.logic.test.ts @@ -2,6 +2,9 @@ import { buildLocalStackContainerSpec, detectAiAgent, parseGatewayListen, + isStackContainerName, + knownContainerNameRank, + lstkContainerStack, resolveContainerName, resolveImage, resolveVolume, @@ -77,6 +80,93 @@ describe("resolveContainerName", () => { test("defaults to localstack-main and honors MAIN_CONTAINER_NAME", () => { expect(resolveContainerName({})).toBe("localstack-main"); expect(resolveContainerName({ MAIN_CONTAINER_NAME: "my-ls" })).toBe("my-ls"); + expect(resolveContainerName({ LOCALSTACK_MAIN_CONTAINER_NAME: "ls2" })).toBe("ls2"); + }); +}); + +describe("lstk container names", () => { + // lstk's ContainerConfig.defaultName (internal/config/containers.go): + // "localstack-{type}", or "localstack-{type}-{tag}" when the tag is not "latest". + const lstk = { "cloud.localstack.lstk": "true" }; + + test("recognizes lstk's latest names without a label", () => { + expect(lstkContainerStack("localstack-aws")).toBe("aws"); + expect(lstkContainerStack("localstack-snowflake")).toBe("snowflake"); + expect(lstkContainerStack("localstack-azure")).toBe("azure"); + }); + + test("recognizes a tagged name only with lstk's label", () => { + expect(lstkContainerStack("localstack-aws-2026.4", lstk)).toBe("aws"); + expect(lstkContainerStack("localstack-snowflake-1.2.3", lstk)).toBe("snowflake"); + expect(lstkContainerStack("localstack-azure-2026.4", lstk)).toBe("azure"); + // LocalStack names Lambda containers after its own container, so the same shape + // without lstk's label is not an emulator. + expect(lstkContainerStack("localstack-aws-dev-lambda-fn-1234")).toBeUndefined(); + expect(lstkContainerStack("localstack-aws-2026.4")).toBeUndefined(); + }); + + test("ignores names lstk does not derive", () => { + for (const name of [ + "localstack-main", + "localstack", + "localstack-awsx", + "localstack-aws-", + "my-localstack-aws", + "localstack-gcp", + ]) { + expect(lstkContainerStack(name, lstk)).toBeUndefined(); + } + }); + + test("ranks localstack-main, lstk's names by stack (latest first), then custom lstk names", () => { + const containers: Array<[string, Record | undefined]> = [ + ["my-ls", lstk], + ["localstack-azure-2026.4", lstk], + ["localstack-aws-2026.4", lstk], + ["localstack-snowflake", undefined], + ["localstack-aws", undefined], + ["localstack-main", undefined], + ["localstack-azure", undefined], + ]; + const ranked = [...containers] + .sort(([a, la], [b, lb]) => knownContainerNameRank(a, la)! - knownContainerNameRank(b, lb)!) + .map(([name]) => name); + expect(ranked).toEqual([ + "localstack-main", + "localstack-aws", + "localstack-aws-2026.4", + "localstack-snowflake", + "localstack-azure", + "localstack-azure-2026.4", + "my-ls", + ]); + expect(knownContainerNameRank("my-ls")).toBeUndefined(); + expect(knownContainerNameRank("localstack-main-lambda-fn-1234")).toBeUndefined(); + expect(knownContainerNameRank("localstack-aws-dev-lambda-fn-1234")).toBeUndefined(); + }); +}); + +describe("isStackContainerName", () => { + test("accepts localstack-main and the stack's labeled lstk names when nothing is configured", () => { + const lstk = { "cloud.localstack.lstk": "true" }; + expect(isStackContainerName({}, "aws", "localstack-main")).toBe(true); + expect(isStackContainerName({}, "aws", "localstack-aws", lstk)).toBe(true); + expect(isStackContainerName({}, "snowflake", "localstack-snowflake", lstk)).toBe(true); + // Without lstk's label, lstk did not create it (for example a compose service). + expect(isStackContainerName({}, "aws", "localstack-aws")).toBe(false); + expect( + isStackContainerName({}, "aws", "localstack-aws-2026.4", { "cloud.localstack.lstk": "true" }) + ).toBe(true); + expect(isStackContainerName({}, "aws", "localstack-aws-dev-lambda-fn-1234")).toBe(false); + expect(isStackContainerName({}, "aws", "localstack-snowflake")).toBe(false); + expect(isStackContainerName({}, "azure", "localstack-aws")).toBe(false); + }); + + test("accepts only the configured name when MAIN_CONTAINER_NAME is set", () => { + const env = { MAIN_CONTAINER_NAME: " my-ls " }; + expect(isStackContainerName(env, "azure", "my-ls")).toBe(true); + expect(isStackContainerName(env, "azure", "localstack-main")).toBe(false); + expect(isStackContainerName(env, "azure", "localstack-azure")).toBe(false); }); }); @@ -212,6 +302,14 @@ describe("buildLocalStackContainerSpec", () => { expect(spec.HostConfig.PortBindings["443/tcp"][0].HostIp).toBe("0.0.0.0"); }); + test("a recreate keeps the original container's labels", () => { + const spec = buildLocalStackContainerSpec( + baseInput({ labelsOverride: { "cloud.localstack.lstk": "true" } }) + ); + expect(spec.Labels).toEqual({ "cloud.localstack.lstk": "true" }); + expect(buildLocalStackContainerSpec(baseInput()).Labels).toBeUndefined(); + }); + test("LOCALSTACK_PORT changes only the host side of the gateway mapping", () => { const spec = buildLocalStackContainerSpec(baseInput({ hostEnv: { LOCALSTACK_PORT: "4567" } })); expect(spec.HostConfig.PortBindings["4566/tcp"]).toEqual([ diff --git a/src/lib/localstack/container-spec.logic.ts b/src/lib/localstack/container-spec.logic.ts index d71afe2..08e493e 100644 --- a/src/lib/localstack/container-spec.logic.ts +++ b/src/lib/localstack/container-spec.logic.ts @@ -14,7 +14,6 @@ * only in the port bindings, never inside the container */ -export const DEFAULT_CONTAINER_NAME = "localstack-main"; export const DEFAULT_AWS_IMAGE = "localstack/localstack-pro:latest"; export const DEFAULT_SNOWFLAKE_IMAGE = "localstack/snowflake:latest"; export const DEFAULT_AZURE_IMAGE = "localstack/localstack-azure:latest"; @@ -91,6 +90,70 @@ const AI_AGENT_DETECTORS: Array<[string, string[]]> = [ export type LocalStackStack = "aws" | "snowflake" | "azure"; +/** The name the start action gives a new container when MAIN_CONTAINER_NAME is unset. */ +export const DEFAULT_CONTAINER_NAME = "localstack-main"; + +/** Stacks in the order their lstk names are preferred during detection. */ +const LSTK_STACKS: readonly LocalStackStack[] = ["aws", "snowflake", "azure"]; + +/** + * lstk's derived container name: `localstack-{type}` for the `latest` tag, else + * `localstack-{type}-{tag}` (`ContainerConfig.defaultName` in lstk's + * `internal/config/containers.go`). The server does not create containers under these + * names, but finds and manages ones lstk started. + */ +const LSTK_CONTAINER_NAME = /^localstack-(aws|snowflake|azure)(?:-([A-Za-z0-9_.-]+))?$/; + +/** + * The label lstk puts on every container it creates (`managedLabelKey` in lstk's + * `internal/runtime/docker.go`). A name alone cannot tell a tagged lstk container + * (`localstack-aws-dev`) from the Lambda containers LocalStack starts under its own + * name plus a suffix (`localstack-aws-dev-lambda-...`), so names other than the exact + * ones below count only with this label. + */ +export const LSTK_MANAGED_LABEL = "cloud.localstack.lstk"; + +export type ContainerLabels = Record | undefined; + +/** How the known names are described to users, for example in "not found" errors. */ +export const KNOWN_CONTAINER_NAMES_DESCRIPTION = + `"${DEFAULT_CONTAINER_NAME}", "localstack-aws", "localstack-snowflake" or ` + + `"localstack-azure", or a container lstk started under another name`; + +function isLstkManaged(labels: ContainerLabels): boolean { + return labels?.[LSTK_MANAGED_LABEL] === "true"; +} + +/** + * The stack an lstk container belongs to, judged by its name: `localstack-{type}`, or + * `localstack-{type}-{tag}` when lstk's label is present. Undefined otherwise. + */ +export function lstkContainerStack( + name: string, + labels?: ContainerLabels +): LocalStackStack | undefined { + const match = LSTK_CONTAINER_NAME.exec(name); + if (!match || (match[2] && !isLstkManaged(labels))) return undefined; + return match[1] as LocalStackStack; +} + +/** + * Detection order of a container when MAIN_CONTAINER_NAME is unset: lower wins. + * `localstack-main` first, then lstk's names by stack (the `latest` name before a + * tagged one), then any other container lstk started (a custom `container_name`). + * Undefined for a container the server does not recognize. + */ +export function knownContainerNameRank(name: string, labels?: ContainerLabels): number | undefined { + if (name === DEFAULT_CONTAINER_NAME) return 0; + const stack = lstkContainerStack(name, labels); + if (stack) { + const tagged = name !== `localstack-${stack}`; + return 1 + LSTK_STACKS.indexOf(stack) * 2 + (tagged ? 1 : 0); + } + if (isLstkManaged(labels)) return 1 + LSTK_STACKS.length * 2; + return undefined; +} + export type VolumeResolution = { type: "bind"; source: string } | { type: "volume"; name: string }; export interface GatewayListenEntry { @@ -111,6 +174,8 @@ export interface ContainerSpecInput { /** Overrides for restart-in-place recreation: reuse the original container's identity. */ imageOverride?: string; containerNameOverride?: string; + /** Labels of the original container to keep, such as lstk's. */ + labelsOverride?: Record; } export interface PortBindingEntry { @@ -124,6 +189,7 @@ export interface LocalStackContainerSpec { Image: string; Env: string[]; ExposedPorts: Record>; + Labels?: Record; HostConfig: { AutoRemove: boolean; PortBindings: Record>; @@ -151,14 +217,41 @@ export function stackFromImage(image?: string): LocalStackStack | undefined { return "aws"; } -export function resolveContainerName(hostEnv: Record): string { +/** The container name the user configured (MAIN_CONTAINER_NAME), or undefined. */ +export function configuredContainerName( + hostEnv: Record +): string | undefined { return ( hostEnv.MAIN_CONTAINER_NAME?.trim() || hostEnv.LOCALSTACK_MAIN_CONTAINER_NAME?.trim() || - DEFAULT_CONTAINER_NAME + undefined ); } +/** The name for a new container: the configured one, else `localstack-main`. */ +export function resolveContainerName(hostEnv: Record): string { + return configuredContainerName(hostEnv) || DEFAULT_CONTAINER_NAME; +} + +/** + * Whether a stopped container belongs to the stack, so `stop` may remove it: the + * configured name, else `localstack-main` and the stack's lstk containers. lstk's names + * need lstk's label here even without a tag: removing is riskier than detecting, and a + * `localstack-aws` without the label was not created by lstk (for example a compose + * service), so it is not ours to clean up. + */ +export function isStackContainerName( + hostEnv: Record, + stack: LocalStackStack, + name: string, + labels?: ContainerLabels +): boolean { + const configured = configuredContainerName(hostEnv); + if (configured) return name === configured; + if (name === DEFAULT_CONTAINER_NAME) return true; + return isLstkManaged(labels) && lstkContainerStack(name, labels) === stack; +} + function parsePort(text: string, context: string): number { const port = Number(text); if (!Number.isInteger(port) || port < 1 || port > 65535) { @@ -497,6 +590,9 @@ export function buildLocalStackContainerSpec(input: ContainerSpecInput): LocalSt Image: image, Env: buildEnv(input, ports, name), ExposedPorts: exposedPorts, + ...(input.labelsOverride && Object.keys(input.labelsOverride).length > 0 + ? { Labels: input.labelsOverride } + : {}), HostConfig: { AutoRemove: true, PortBindings: portBindings, diff --git a/src/lib/localstack/localstack.utils.test.ts b/src/lib/localstack/localstack.utils.test.ts index 84de421..e3b69b1 100644 --- a/src/lib/localstack/localstack.utils.test.ts +++ b/src/lib/localstack/localstack.utils.test.ts @@ -67,6 +67,7 @@ function mockDockerClient(overrides: Record = {}) { const client = { ping: jest.fn().mockResolvedValue(undefined), findContainerByNameAnyState: jest.fn().mockResolvedValue(null), + listKnownLocalStackContainers: jest.fn().mockResolvedValue([]), findLocalStackContainer: jest.fn().mockResolvedValue("container-123"), inspectContainer: jest .fn() @@ -330,6 +331,134 @@ describe("localstack.utils", () => { expect(client.createAndStartContainer).not.toHaveBeenCalled(); }); + test("reports a conflict when an lstk container runs under its own name", async () => { + // lstk names the container localstack-aws, so the localstack-main name check alone + // would miss it; both publish the gateway port. + const { client } = mockDockerClient({ + listKnownLocalStackContainers: jest.fn().mockResolvedValue([ + { + id: "aws-1", + name: "localstack-aws", + state: "running", + running: true, + image: "localstack/localstack-pro:latest", + publicPorts: [4566, 443], + }, + ]), + }); + const getStatus = jest.fn().mockResolvedValue({ isRunning: false }); + + const result = await launchRuntime({ + ...launchDefaults, + stack: "snowflake", + processLabel: "Snowflake emulator", + getStatus, + dockerClient: client, + }); + const text = result.content[0].text; + expect(text).toContain('named "localstack-aws"'); + expect(text).toContain("action: stop"); + expect(client.createAndStartContainer).not.toHaveBeenCalled(); + }); + + test("reports a conflict when lstk runs a pinned tag on the gateway port", async () => { + // lstk appends the tag to the name when it is not "latest". + const { client } = mockDockerClient({ + listKnownLocalStackContainers: jest.fn().mockResolvedValue([ + { + id: "aws-tagged", + name: "localstack-aws-2026.4", + state: "running", + running: true, + image: "localstack/localstack-pro:2026.4", + publicPorts: [4566, 443], + }, + ]), + }); + const getStatus = jest.fn().mockResolvedValue({ isRunning: false }); + + const result = await launchRuntime({ ...launchDefaults, getStatus, dockerClient: client }); + const text = result.content[0].text; + expect(text).toContain('named "localstack-aws-2026.4"'); + expect(text).toContain( + "it runs the AWS emulator too and holds ports 443, 4566 that this start needs" + ); + expect(text).toContain("`lstk stop`"); + expect(client.createAndStartContainer).not.toHaveBeenCalled(); + }); + + test("reports a conflict when lstk's Azure container holds the gateway port", async () => { + const { client } = mockDockerClient({ + listKnownLocalStackContainers: jest.fn().mockResolvedValue([ + { + id: "old-1", + name: "localstack-azure", + state: "running", + running: true, + image: "localstack/localstack-pro:latest", + publicPorts: [4566], + }, + ]), + }); + const getStatus = jest.fn().mockResolvedValue({ isRunning: false }); + + const result = await launchRuntime({ ...launchDefaults, getStatus, dockerClient: client }); + expect(result.content[0].text).toContain('named "localstack-azure"'); + expect(client.createAndStartContainer).not.toHaveBeenCalled(); + }); + + test("starts beside another stack's container that publishes other ports", async () => { + // lstk runs stacks side by side on their own ports; only a shared host port conflicts. + const { client } = mockDockerClient({ + listKnownLocalStackContainers: jest.fn().mockResolvedValue([ + { + id: "aws-1", + name: "localstack-aws", + state: "running", + running: true, + image: "localstack/localstack-pro:latest", + publicPorts: [5566], + }, + ]), + }); + const getStatus = jest + .fn() + .mockResolvedValueOnce({ isRunning: false }) + .mockResolvedValue({ isRunning: true, isReady: true }); + + const result = await launchRuntime({ + ...launchDefaults, + stack: "snowflake", + processLabel: "Snowflake emulator", + getStatus, + dockerClient: client, + }); + expect(result.content[0].text).toContain("started successfully"); + expect(client.createAndStartContainer.mock.calls[0][0].name).toBe("localstack-main"); + }); + + test("leaves stopped containers of other names alone", async () => { + const { client } = mockDockerClient({ + listKnownLocalStackContainers: jest.fn().mockResolvedValue([ + { + id: "lstk-stopped", + name: "localstack-aws", + state: "exited", + running: false, + publicPorts: [], + }, + ]), + }); + const getStatus = jest + .fn() + .mockResolvedValueOnce({ isRunning: false }) + .mockResolvedValue({ isRunning: true, isReady: true }); + + const result = await launchRuntime({ ...launchDefaults, getStatus, dockerClient: client }); + expect(result.content[0].text).toContain("started successfully"); + expect(client.removeContainer).not.toHaveBeenCalled(); + }); + test("names an Azure container as the Azure emulator in the conflict message", async () => { const { client } = mockDockerClient({ findContainerByNameAnyState: jest.fn().mockResolvedValue({ @@ -617,6 +746,33 @@ describe("localstack.utils", () => { }); }); + test("keeps an lstk container's labels", () => { + // A tagged or custom lstk name counts only with lstk's label. The gateway port is + // not kept: the server's tools reach the gateway on LOCALSTACK_PORT only. + expect( + deriveRecreateOverrides( + { + id: "x", + name: "localstack-aws-2026.4", + image: "localstack/localstack-pro:2026.4", + labels: { + "cloud.localstack.lstk": "true", + "cloud.localstack.lstk.image-override": "true", + maintainer: "LocalStack Team", + }, + }, + "aws" + ) + ).toEqual({ + imageOverride: "localstack/localstack-pro:2026.4", + containerNameOverride: "localstack-aws-2026.4", + labelsOverride: { + "cloud.localstack.lstk": "true", + "cloud.localstack.lstk.image-override": "true", + }, + }); + }); + test("returns undefined when the previous image is a different stack (deliberate switch)", () => { expect( deriveRecreateOverrides({ id: "x", image: "localstack/snowflake:latest" }, "aws") diff --git a/src/lib/localstack/localstack.utils.ts b/src/lib/localstack/localstack.utils.ts index 17e2ef4..1114854 100644 --- a/src/lib/localstack/localstack.utils.ts +++ b/src/lib/localstack/localstack.utils.ts @@ -15,7 +15,9 @@ import { } from "../docker/docker.client"; import { buildLocalStackContainerSpec, + LSTK_MANAGED_LABEL, resolveContainerName, + type LocalStackContainerSpec, resolveVolume, stackFromImage, type LocalStackStack, @@ -337,6 +339,7 @@ export interface LaunchRuntimeOptions { imageOverride?: string; containerNameOverride?: string; volumeOverride?: VolumeResolution; + labelsOverride?: Record; /** Injectable for tests. */ dockerClient?: DockerApiClient; pollIntervalMs?: number; @@ -352,23 +355,65 @@ function tailLines(text: string, lines: number): string { return allLines.slice(-lines).join("\n"); } -function conflictResponse(processLabel: string, containerName: string, image?: string) { +/** Host ports a container spec publishes. */ +function specHostPorts(spec: LocalStackContainerSpec): Set { + return new Set( + Object.values(spec.HostConfig.PortBindings) + .flat() + .map((binding) => Number(binding.HostPort)) + ); +} + +const EMULATOR_LABELS: Record = { + aws: "the AWS emulator", + snowflake: "the Snowflake emulator", + azure: "the Azure emulator", +}; + +/** + * A running container blocks this start. `sharedPorts` lists the host ports it holds + * that this start would bind, when the conflict is about ports rather than the name. + */ +function conflictResponse( + processLabel: string, + startingStack: LocalStackStack, + containerName: string, + image?: string, + sharedPorts?: number[] +) { const stack = stackFromImage(image); - const otherStack = - stack === "snowflake" - ? "the Snowflake emulator" - : stack === "azure" - ? "the Azure emulator" - : "another LocalStack stack (likely the AWS emulator)"; + const owner = + stack === undefined + ? "it belongs to another LocalStack stack (likely the AWS emulator)" + : stack === startingStack + ? `it runs ${EMULATOR_LABELS[stack]} too` + : `it belongs to ${EMULATOR_LABELS[stack]}`; + const ports = sharedPorts?.length + ? ` and holds port${sharedPorts.length > 1 ? "s" : ""} ${formatPorts(sharedPorts)} that this start needs` + : ""; return ResponseBuilder.error( "LocalStack container already running", `Starting ${processLabel} failed because a LocalStack container named "${containerName}"${ image ? ` (image: ${image})` : "" - } is already running — it belongs to ${otherStack}. ` + - `Stop it first with the localstack-management tool (action: stop), then retry this start.` + } is already running — ${owner}${ports}. ` + + `Stop it first with the localstack-management tool (action: stop), or with \`lstk stop\` ` + + `if lstk started it, then retry this start.` ); } +/** Ports as a short list, folding consecutive runs: `443, 4510-4559`. */ +function formatPorts(ports: number[]): string { + const sorted = [...new Set(ports)].sort((a, b) => a - b); + const runs: string[] = []; + for (let i = 0; i < sorted.length; i++) { + let j = i; + while (j + 1 < sorted.length && sorted[j + 1] === sorted[j] + 1) j++; + runs.push(i === j ? `${sorted[i]}` : `${sorted[i]}-${sorted[j]}`); + i = j; + } + return runs.join(", "); +} + /** * Start a LocalStack runtime flavor directly through the Docker Engine API (no * localstack/lstk CLI involved) and poll until it becomes available. @@ -472,21 +517,36 @@ async function launchRuntimeInner( serverVersion: SERVER_VERSION, imageOverride: options.imageOverride, containerNameOverride: options.containerNameOverride, + labelsOverride: options.labelsOverride, }); // Fail fast (or clean up) when the container name is taken. A running container is // an actionable conflict; a stopped one is a stale leftover we remove ourselves. + // lstk names its containers `localstack-{type}[-{tag}]`, so a running container under + // another known name is a conflict too when it publishes a host port this start + // binds. One on other ports (lstk in another project on its own `port`) may keep + // running. // Short timeouts: this is pre-start housekeeping — a hung daemon should surface // as an error in seconds, not block the start for two minutes. try { const existing = await docker.findContainerByNameAnyState(spec.name); if (existing) { if (existing.running) { - return conflictResponse(processLabel, spec.name, existing.image); + return conflictResponse(processLabel, stack, spec.name, existing.image); } await docker.removeContainer(existing.id, 10000); await docker.waitForRemoval(existing.id, 10000); } + const boundHostPorts = specHostPorts(spec); + for (const other of await docker.listKnownLocalStackContainers()) { + if (other.name === spec.name) continue; + const sharedPorts = other.running + ? other.publicPorts.filter((port) => boundHostPorts.has(port)) + : []; + if (sharedPorts.length > 0) { + return conflictResponse(processLabel, stack, other.name, other.image, sharedPorts); + } + } } catch (error) { return ResponseBuilder.error( "Docker lookup failed", @@ -515,7 +575,7 @@ async function launchRuntimeInner( containerId = await docker.createAndStartContainer(spec); } catch (error) { if (error instanceof LocalStackContainerConflictError) { - return conflictResponse(processLabel, spec.name); + return conflictResponse(processLabel, stack, spec.name); } return ResponseBuilder.error( `Failed to start ${processLabel}`, @@ -633,14 +693,17 @@ export interface RecreateOverrides { imageOverride?: string; containerNameOverride?: string; volumeOverride?: VolumeResolution; + labelsOverride?: Record; } /** * Derive start overrides from a container we are about to recreate, so an - * externally-provisioned runtime (custom name/image/volume) is not silently replaced + * externally-provisioned runtime (custom name/image/volume, lstk's labels) is not + * silently replaced * by the defaults — that would strand its state. Reuse only applies when the previous * image matches the requested stack (restarting with a different `service` deliberately - * switches stacks). + * switches stacks). The gateway is published on LOCALSTACK_PORT, not the original + * container's port: the server's HTTP tools only reach it there. */ export function deriveRecreateOverrides( metadata: ContainerMetadata | undefined, @@ -663,6 +726,13 @@ export function deriveRecreateOverrides( overrides.volumeOverride = { type: "volume", name: volumeMount.name }; } + // Keep lstk's labels, so the recreated container still counts as lstk's (its name + // may be tagged or custom, which detection accepts only with the label). + const lstkLabels = Object.fromEntries( + Object.entries(metadata.labels || {}).filter(([key]) => key.startsWith(LSTK_MANAGED_LABEL)) + ); + if (Object.keys(lstkLabels).length > 0) overrides.labelsOverride = lstkLabels; + return overrides; } diff --git a/src/tools-tests/localstack-management.test.ts b/src/tools-tests/localstack-management.test.ts index 5404fca..335fcad 100644 --- a/src/tools-tests/localstack-management.test.ts +++ b/src/tools-tests/localstack-management.test.ts @@ -78,28 +78,95 @@ describe("localstack-management", () => { expect(text(result)).not.toMatch(/Snowflake emulator health check did not pass/); }); - test("stop removes a stale stopped container holding the LocalStack name", async () => { + test("stop removes stale stopped containers holding this stack's names", async () => { const { LocalStackContainerNotFoundError } = jest.requireActual("../lib/docker/docker.client"); const removeContainer = jest.fn().mockResolvedValue(undefined); const waitForRemoval = jest.fn().mockResolvedValue(undefined); + const stopped = (id: string, name: string) => ({ + id, + name, + state: "exited", + running: false, + publicPorts: [], + labels: name === "localstack-main" ? undefined : { "cloud.localstack.lstk": "true" }, + }); mockDocker({ findLocalStackContainer: jest .fn() .mockRejectedValue(new LocalStackContainerNotFoundError("none running")), - findContainerByNameAnyState: jest.fn().mockResolvedValue({ - id: "stale-1", - name: "localstack-main", - state: "exited", - running: false, - }), + listKnownLocalStackContainers: jest.fn().mockResolvedValue([ + stopped("stale-main", "localstack-main"), + stopped("stale-aws", "localstack-aws"), + stopped("stale-snow", "localstack-snowflake"), + stopped("stale-snow-tag", "localstack-snowflake-1.4"), + // A Lambda container LocalStack named after its own container: no lstk label. + { ...stopped("fn", "localstack-snowflake-1.4-lambda-fn-1"), labels: undefined }, + ]), removeContainer, waitForRemoval, }); - const result = await localstackManagement({ action: "stop", service: "aws" } as any); - expect(removeContainer).toHaveBeenCalledWith("stale-1"); - expect(waitForRemoval).toHaveBeenCalledWith("stale-1"); - expect(text(result)).toContain("Removed stopped LocalStack container"); + const result = await localstackManagement({ action: "stop", service: "snowflake" } as any); + expect(removeContainer.mock.calls.map(([id]) => id)).toEqual([ + "stale-main", + "stale-snow", + "stale-snow-tag", + ]); + expect(waitForRemoval).toHaveBeenCalledWith("stale-snow-tag"); + expect(text(result)).toContain( + 'Removed stopped LocalStack containers "localstack-main", "localstack-snowflake", "localstack-snowflake-1.4"' + ); + }); + + test("stop leaves running containers and other stacks' stopped containers alone", async () => { + const { LocalStackContainerNotFoundError } = jest.requireActual("../lib/docker/docker.client"); + const removeContainer = jest.fn().mockResolvedValue(undefined); + mockDocker({ + findLocalStackContainer: jest + .fn() + .mockRejectedValue(new LocalStackContainerNotFoundError("none running")), + listKnownLocalStackContainers: jest.fn().mockResolvedValue([ + { + id: "snow", + name: "localstack-snowflake", + state: "exited", + running: false, + publicPorts: [], + }, + { + id: "aws", + name: "localstack-aws-2026.4", + state: "running", + running: true, + publicPorts: [5566], + }, + ]), + removeContainer, + }); + mockedGetStatus.mockResolvedValue({ isRunning: false, isReady: false }); + + await localstackManagement({ action: "stop", service: "aws" } as any); + expect(removeContainer).not.toHaveBeenCalled(); + }); + + test("stop looks only under MAIN_CONTAINER_NAME when it is set", async () => { + process.env.MAIN_CONTAINER_NAME = "my-ls"; + const { LocalStackContainerNotFoundError } = jest.requireActual("../lib/docker/docker.client"); + const findContainerByNameAnyState = jest.fn().mockResolvedValue(null); + const listKnownLocalStackContainers = jest.fn().mockResolvedValue([]); + mockDocker({ + findLocalStackContainer: jest + .fn() + .mockRejectedValue(new LocalStackContainerNotFoundError("none running")), + findContainerByNameAnyState, + listKnownLocalStackContainers, + }); + mockedGetStatus.mockResolvedValue({ isRunning: false, isReady: false }); + + await localstackManagement({ action: "stop", service: "aws" } as any); + expect(findContainerByNameAnyState).toHaveBeenCalledTimes(1); + expect(findContainerByNameAnyState).toHaveBeenCalledWith("my-ls"); + expect(listKnownLocalStackContainers).not.toHaveBeenCalled(); }); test("stop reports nothing to do when no container exists and the gateway is down", async () => { @@ -116,6 +183,32 @@ describe("localstack-management", () => { expect(text(result)).toMatch(/not running — no container to stop/); }); + test.each(["stop", "restart"])( + "%s reports a container off LOCALSTACK_PORT instead of 'not running'", + async (action) => { + const { GatewayPortMismatchError } = jest.requireActual("../lib/docker/docker.client"); + const removeContainer = jest.fn(); + mockDocker({ + findLocalStackContainer: jest + .fn() + .mockRejectedValue( + new GatewayPortMismatchError( + 'Found running LocalStack containers ("localstack-main" (gateway on 4566)), but none publishes the configured gateway port 4567.' + ) + ), + listKnownLocalStackContainers: jest.fn().mockResolvedValue([]), + removeContainer, + }); + mockedGetStatus.mockResolvedValue({ isRunning: false, isReady: false }); + + const result = await localstackManagement({ action, service: "aws" } as any); + expect(result.isError).toBe(true); + expect(text(result)).toMatch(/gateway on 4566.*configured gateway port 4567/); + expect(removeContainer).not.toHaveBeenCalled(); + expect(launchRuntime).not.toHaveBeenCalled(); + } + ); + test("requires the auth token", async () => { delete process.env.LOCALSTACK_AUTH_TOKEN; const result = await localstackManagement({ action: "status", service: "aws" } as any); diff --git a/src/tools/localstack-management.ts b/src/tools/localstack-management.ts index cab5aae..149fb6e 100644 --- a/src/tools/localstack-management.ts +++ b/src/tools/localstack-management.ts @@ -5,14 +5,19 @@ import { getLocalStackStatus, getSnowflakeEmulatorStatus, launchRuntime, - resolveContainerName, } from "../lib/localstack/localstack.utils"; import { DockerApiClient, + isGatewayPortMismatchError, isLocalStackContainerNotFoundError, type ContainerMetadata, } from "../lib/docker/docker.client"; -import { stackFromImage, type VolumeResolution } from "../lib/localstack/container-spec.logic"; +import { + configuredContainerName, + isStackContainerName, + stackFromImage, + type VolumeResolution, +} from "../lib/localstack/container-spec.logic"; import { runPreflights, requireProFeature, @@ -96,7 +101,7 @@ export default async function localstackManagement({ case "start": return await handleStart({ envVars, service }); case "stop": - return await handleStop(); + return await handleStop({ service }); case "restart": return await handleRestart({ envVars, service }); case "status": @@ -114,6 +119,7 @@ interface StartOverrides { imageOverride?: string; containerNameOverride?: string; volumeOverride?: VolumeResolution; + labelsOverride?: Record; } /** Best-effort look at the running LocalStack container (null when none/undetectable). */ @@ -196,7 +202,7 @@ async function handleStart({ // Handle stop action — stop the detected container via the Docker API. Also cleans up // stopped/stale containers occupying a LocalStack name, so start's conflict advice // ("stop it first") always has a working recovery path. -async function handleStop() { +async function handleStop({ service }: { service: Service }) { const dockerClient = new DockerApiClient(); let containerId: string; try { @@ -208,16 +214,32 @@ async function handleStop() { `Could not inspect Docker containers: ${error instanceof Error ? error.message : String(error)}` ); } + if (isGatewayPortMismatchError(error)) { + return ResponseBuilder.error("LocalStack container not on LOCALSTACK_PORT", (error as Error).message); + } - // No RUNNING container found — check for a stale stopped one holding the name. + // No RUNNING container found — check for stale stopped ones holding this stack's name. try { - const stale = await dockerClient.findContainerByNameAnyState( - resolveContainerName(process.env) - ); - if (stale && !stale.running) { - await dockerClient.removeContainer(stale.id); - await dockerClient.waitForRemoval(stale.id); - return ResponseBuilder.markdown(`🛑 Removed stopped LocalStack container "${stale.name}".`); + const configured = configuredContainerName(process.env); + const candidates = configured + ? [await dockerClient.findContainerByNameAnyState(configured)] + : await dockerClient.listKnownLocalStackContainers(); + const removed: string[] = []; + for (const stale of candidates) { + if ( + stale && + !stale.running && + isStackContainerName(process.env, service, stale.name, stale.labels) + ) { + await dockerClient.removeContainer(stale.id); + await dockerClient.waitForRemoval(stale.id); + removed.push(`"${stale.name}"`); + } + } + if (removed.length > 0) { + return ResponseBuilder.markdown( + `🛑 Removed stopped LocalStack container${removed.length > 1 ? "s" : ""} ${removed.join(", ")}.` + ); } } catch { // fall through to the gateway-based reporting below @@ -271,6 +293,9 @@ async function handleRestart({ }` ); } + if (isGatewayPortMismatchError(error)) { + return ResponseBuilder.error("LocalStack container not on LOCALSTACK_PORT", (error as Error).message); + } const status = await getLocalStackStatus(); if (status.isRunning) { return ResponseBuilder.error( diff --git a/tests/docker/validate-lstk.mjs b/tests/docker/validate-lstk.mjs new file mode 100644 index 0000000..5fca3e0 --- /dev/null +++ b/tests/docker/validate-lstk.mjs @@ -0,0 +1,195 @@ +#!/usr/bin/env node +/** + * Checks that the server manages a container lstk started: lstk starts the AWS emulator + * with a pinned tag (so its container is `localstack-aws-`), the server restarts + * it, and lstk still finds it afterwards. + * + * Usage: + * node tests/docker/validate-lstk.mjs -- [args...] + * + * The server command must pass LOCALSTACK_PORT= to the server, so its + * tools reach the gateway lstk publishes. Needs `lstk` on PATH, LOCALSTACK_AUTH_TOKEN, + * and free host ports 443 and 4510-4560 (lstk always publishes them). + * + * Env knobs: + * HARNESS_LSTK_TAG Image tag lstk runs (default "mcp-ci"). A tag that exists only + * locally works: lstk falls back to the local image when the pull fails. + * HARNESS_LSTK_PORT Gateway port lstk publishes (default 4577). + */ + +import { execFileSync, spawn } from "node:child_process"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const argv = process.argv.slice(2); +const sep = argv.indexOf("--"); +if (sep === -1 || sep === argv.length - 1) { + console.error("Usage: node validate-lstk.mjs -- [args...]"); + process.exit(2); +} + +const TAG = process.env.HARNESS_LSTK_TAG || "mcp-ci"; +const PORT = process.env.HARNESS_LSTK_PORT || "4577"; +const NAME = `localstack-aws-${TAG}`; +const LSTK_LABEL = "cloud.localstack.lstk"; + +const configDir = mkdtempSync(join(tmpdir(), "lsmcp-lstk-")); +const configPath = join(configDir, "config.toml"); +writeFileSync(configPath, `[[containers]]\ntype = "aws"\ntag = "${TAG}"\nport = "${PORT}"\n`); + +// ---- helpers ---------------------------------------------------------------- +function run(cmd, args, timeoutMs = 300000) { + try { + const out = execFileSync(cmd, args, { + encoding: "utf8", + timeout: timeoutMs, + stdio: ["ignore", "pipe", "pipe"], + env: { ...process.env, LSTK_STARTUP_TIMEOUT: "180s" }, + }); + return { ok: true, out }; + } catch (error) { + return { ok: false, out: `${error.stdout || ""}${error.stderr || ""}${error.message}` }; + } +} +const lstk = (...args) => run("lstk", ["--config", configPath, ...args]); + +function inspect(name) { + const r = run("docker", ["inspect", name], 30000); + if (!r.ok) return undefined; + return JSON.parse(r.out)[0]; +} + +const results = []; +function record(name, ok, detail) { + results.push({ name, ok }); + console.log(`\n${ok ? "✅ PASS" : "❌ FAIL"} ${name}`); + if (detail) console.log(" " + String(detail).replace(/\n/g, "\n ").slice(0, 1200)); +} + +// ---- MCP stdio client ------------------------------------------------------- +const child = spawn(argv[sep + 1], argv.slice(sep + 2), { stdio: ["pipe", "pipe", "pipe"] }); +const pending = new Map(); +const serverLog = []; +let buf = ""; +let nextId = 1; +child.stdout.on("data", (chunk) => { + buf += chunk.toString(); + let nl; + while ((nl = buf.indexOf("\n")) !== -1) { + const line = buf.slice(0, nl).trim(); + buf = buf.slice(nl + 1); + if (!line) continue; + let msg; + try { + msg = JSON.parse(line); + } catch { + continue; + } + const waiter = msg.id !== undefined && pending.get(msg.id); + if (!waiter) continue; + pending.delete(msg.id); + if (msg.error) waiter.reject(new Error(JSON.stringify(msg.error))); + else waiter.resolve(msg.result); + } +}); +child.stderr.on("data", (c) => serverLog.push(c.toString().trimEnd())); + +function rpc(method, params, timeoutMs) { + const id = nextId++; + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + pending.delete(id); + reject(new Error(`timeout after ${timeoutMs}ms waiting for ${method}`)); + }, timeoutMs); + pending.set(id, { + resolve: (r) => (clearTimeout(timer), resolve(r)), + reject: (e) => (clearTimeout(timer), reject(e)), + }); + child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n"); + }); +} +async function callTool(name, args, timeoutMs) { + const res = await rpc("tools/call", { name, arguments: args }, timeoutMs); + const text = (res?.content || []).map((c) => c.text || "").join("\n"); + return { text, isError: res?.isError === true || text.trimStart().startsWith("❌") }; +} + +// ---- scenario --------------------------------------------------------------- +async function main() { + const started = lstk("start"); + const before = inspect(NAME); + record( + `lstk start runs ${NAME}`, + started.ok && before?.State?.Running && before.Config.Labels?.[LSTK_LABEL] === "true", + started.out.slice(-600) + ); + if (!before?.State?.Running) return; + + await rpc( + "initialize", + { + protocolVersion: "2024-11-05", + capabilities: {}, + clientInfo: { name: "ls-mcp-lstk-validator", version: "1.0.0" }, + }, + 60000 + ); + child.stdin.write( + JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized", params: {} }) + "\n" + ); + + const restart = await callTool("localstack-management", { action: "restart" }, 300000); + record("localstack-management restart succeeds", !restart.isError, restart.text.slice(0, 600)); + + const after = inspect(NAME); + const gateway = after?.HostConfig?.PortBindings?.["4566/tcp"]?.[0]?.HostPort; + record( + "the recreated container keeps lstk's name, image and label, on LOCALSTACK_PORT", + Boolean(after?.State?.Running) && + after.Id !== before.Id && + after.Config.Image === before.Config.Image && + after.Config.Labels?.[LSTK_LABEL] === "true" && + gateway === PORT, + `id changed: ${after?.Id !== before.Id}, image: ${after?.Config?.Image}, ` + + `label: ${after?.Config?.Labels?.[LSTK_LABEL]}, gateway host port: ${gateway}` + ); + + const status = lstk("status"); + record( + "lstk status finds the restarted container", + status.ok && !/not running/i.test(status.out), + status.out.slice(-400) + ); + + const stopped = lstk("stop"); + record( + "lstk stop stops the restarted container", + stopped.ok && !inspect(NAME)?.State?.Running, + stopped.out.slice(-400) + ); +} + +function finish(code) { + try { + child.stdin.end(); + child.kill("SIGTERM"); + } catch {} + run("docker", ["rm", "-f", NAME], 60000); + const failed = results.filter((r) => !r.ok); + console.log("\n" + "=".repeat(64)); + console.log(`SUMMARY: ${results.length - failed.length} passed, ${failed.length} failed`); + if (failed.length || code) { + console.log("\n--- recent server stderr (last 25 lines) ---"); + console.log(serverLog.slice(-25).join("\n")); + } + console.log("=".repeat(64)); + process.exit(code || (failed.length || results.length === 0 ? 1 : 0)); +} + +main() + .then(() => finish(0)) + .catch((e) => { + console.error("\nHARNESS ERROR:", e.message); + finish(1); + });