Metadata-Version: 2.5
Name: qodalis-cli-server-plugin-docker
Version: 1.0.0b39
Summary: Docker containers, images, stacks, volumes and networks plugin for Qodalis CLI servers: commands, API, MCP, exec socket and Console page
Project-URL: Homepage, https://github.com/qodalis-solutions/cli-server-python
Project-URL: Repository, https://github.com/qodalis-solutions/cli-server-python
Project-URL: Issues, https://github.com/qodalis-solutions/cli-server-python/issues
Author-email: Nicolae Lupei <nicolae.lupei@qodalis.com>
License-Expression: MIT
License-File: LICENSE
Keywords: cli,containers,docker,plugin,qodalis
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.10
Requires-Dist: fastapi>=0.100.0
Requires-Dist: opentelemetry-api<1.46
Requires-Dist: qodalis-cli-server-abstractions>=1.0.0b39
Provides-Extra: users
Requires-Dist: qodalis-cli-server-plugin-users>=1.0.0b39; extra == 'users'
Description-Content-Type: text/markdown

# qodalis-cli-server-plugin-docker

Docker for the [Qodalis CLI Server (Python)](https://github.com/qodalis-solutions/cli-server-python): containers, images,
compose stacks, volumes and networks of one or more Docker hosts, through the Docker Engine API, from the Qodalis Console
(a Docker page), the web terminal (`docker`), MCP and a REST API, with an interactive exec session in the Console. The
design and the contract shared with the Node and .NET servers is
`web-cli/docs/superpowers/specs/2026-12-04-docker-plugin-design.md`.

```bash
pip install qodalis-cli-server-plugin-docker
```

The plugin is opt-in and has no default endpoint: the Docker socket is root-equivalent, so the server's owner says which
engine to use. Without an `endpoint` the plugin is **needs configuration** (it registers nothing).

## Use

```python
from qodalis_cli import create_cli_server
from qodalis_cli_docker import plugin as docker

result = create_cli_server(CliServerOptions(
    configure=lambda builder: builder.add_plugin(docker, {"endpoint": "unix:///var/run/docker.sock", "protect": ["postgres*"]}),
))
```

or without the plugin loader:

```python
from qodalis_cli_docker import CliDockerBuilder, DockerSettings

plugin = (
    CliDockerBuilder()
    .set_settings(lambda: DockerSettings(endpoint="unix:///var/run/docker.sock", protect=["postgres*"]))
    .set_audit(record)  # optional: an async function of the audit entry (a dict)
    .build()
)
result.mount_plugin(plugin)  # routes, commands, permissions, the Console page, the MCP tools and the exec socket
```

The demo server enables the plugin only when `QCLI_DOCKER_ENDPOINT` is set (its value is the endpoint); it is protected
(users plugin), so the plugin serves signed-in callers; `QCLI_DOCKER_ALLOW_UNPROTECTED=true` turns `allowUnprotected` on.

## Settings

Config provider `docker`, section `settings` (Console Config page, `config set docker.settings.<key> <value>`). They are
read on every call, so a change applies without a restart, except hosts and TLS files, which apply to new connections.

| Key | Type | Default | Meaning |
|---|---|---|---|
| `endpoint` | string, required | none | The default host (named `local`): `unix:///var/run/docker.sock`, `tcp://host:2375`, `tcp://host:2376` (TLS when a certificate is set or the port is 2376), `https://host:2376` |
| `tlsCa`, `tlsCert`, `tlsKey` | string | none | Paths of PEM files for the default host |
| `tlsVerify` | boolean | true | Verify the engine's certificate |
| `hosts` | json | `{}` | More hosts: `{ "<name>": { "endpoint": "...", "tlsCa": "...", "tlsCert": "...", "tlsKey": "...", "tlsVerify": true } }`; names match `^[a-z0-9][a-z0-9-]{0,31}$`, `local` is reserved; invalid entries are dropped and logged |
| `readOnly` | boolean | false | Refuse every change (actions, pulls, exec, removals, prunes, creation) |
| `hide` | string[] | `[]` | Containers nobody sees (404, left out of lists, counts, stacks, events) |
| `protect` | string[] | `[]` | Containers that can be read but not changed (409 `container <name> is protected`) |
| `composeRoots` | string[] | `[]` | The only folders compose files are read from, written to and run from (absolute paths); empty: no compose file is read and no compose feature works |
| `composeCommand` | string | `docker compose` | The compose CLI: words split like a shell line, run without a shell (`docker-compose` works too) |
| `composeHosts` | string[] | `["local"]` | The hosts compose may change; write, `up`, compose `down` and delete on another host are 409 `compose is not enabled for host <name>` (the Engine API way of `down` for a stack without a file works on any host) |
| `composeEnv` | string[] | `[]` | Names of the server's environment variables the compose CLI may see (for `${VAR}` in compose files); names starting with `DOCKER_` or `COMPOSE_` are ignored |
| `composeTimeoutSeconds` | number 10-3600 | 900 | Time limit of one compose `up` (`down` has 120 s) |
| `allowUnprotected` | boolean | false | Serve callers that are not signed in (a server without the users plugin's protection); off: see the first rule below |
| `timeoutSeconds` | number 1-120 | 15 | Timeout of one Engine API call (not of streams, pulls or exec) |

A pattern of `hide` / `protect` is a container name with `*` wildcards (`postgres*`, case-sensitive, matched against the
name without the leading `/`), or `label:<key>` / `label:<key>=<value>`. Every route takes `?host=<name>`, every command
`--host <name>`; an unknown name is 404 / `Error: unknown Docker host: <name>`.

## Permissions

| Permission | Allows |
|---|---|
| `docker:read` | See containers, images, stacks, volumes, networks, logs and stats |
| `docker:manage` | Start, stop and restart containers and stacks, pull images |
| `docker:exec` | Run commands inside containers (REST, terminal, MCP and the exec socket) |
| `docker:admin` | Remove containers and images, prune, create and remove volumes and networks, take stacks down |

On a protected server the route gate maps GET to the first permission and other methods to the second of each path:
`/api/v1/qcli/docker` `docker:read` / `docker:manage`, `/exec` `docker:exec`, `/admin` `docker:admin`. The exec socket needs
`docker:exec` (the plugin checks it itself); the root command `docker` needs `docker:read` and each sub-command adds its own.

## REST API (`/api/v1/qcli/docker`)

Errors are `{ "error": "<text>" }`: 400 invalid input or an ambiguous container reference, 403 `the Docker plugin is
read-only` or `the Docker plugin needs a protected server (sign-in); see its allowUnprotected setting`, 404 unknown host,
container, image, volume, network, stack or operation, 409 `container <name> is protected` or the engine's own conflict,
502 `cannot reach Docker at <host>: <message>`, 504 an exec that did not finish. A container reference is a full id, an id
prefix of at least 3 characters or a name.

| Route | Permission | Answer |
|---|---|---|
| `GET /hosts` | read | `{ hosts, readOnly }` (each host probed with a 3 s timeout) |
| `GET /info`, `/df` | read | engine info; disk usage with reclaimable sizes |
| `GET /events?since=&limit=` | read | `{ host, events }`, newest first |
| `GET /containers?all=&stack=`, `/containers/{id}` | read | containers sorted by name; one with its detail (command, masked environment, mounts, networks) |
| `GET /containers/{id}/logs?tail=&since=&timestamps=` | read | `{ host, lines }`, oldest first |
| `GET /stats?ids=` | read | CPU, memory, network, block I/O and pids (two samples per container) |
| `GET /compose` | read | `{ available, version?, roots, error? }`: whether the compose CLI answers (`version --short`, 5 s, cached 60 s) |
| `GET /images`, `/stacks`, `/stacks/{name}`, `/volumes[/{name}]`, `/networks[/{id}]` | read | lists and details; a stack has `composeFile` (the path found by the rule) and the state `down` when only its folder exists |
| `GET /operations`, `/operations/{id}` | read | the last 50 operations (pulls, stack updates), newest first |
| `POST /containers/{id}/start\|stop\|restart\|kill\|pause\|unpause` | manage | `{ ok, container }` |
| `POST /images/pull` `{ image }` | manage | 202 `{ operation }`; the pull runs in the background |
| `POST /stacks/{name}/start\|stop\|restart` | manage | `{ ok, results }` per container (a protected one is reported, the rest run) |
| `POST /stacks/{name}/pull` | manage | 202 `{ operation }` |
| `POST /exec/{id}` `{ command, user?, workdir?, timeoutSeconds? }` | exec | `{ exitCode, stdout, stderr, truncated }` (1 MB per stream; 504 on timeout) |
| `DELETE /admin/containers/{id}?force=&volumes=`, `POST /admin/containers/prune` | admin | `{ ok }`; `{ removed, reclaimedBytes }` (hidden and protected containers are never pruned) |
| `DELETE /admin/images/{id}?force=`, `POST /admin/images/prune` `{ all? }` | admin | `{ ok, untagged, deleted }`; `{ removed, reclaimedBytes }` |
| `POST /admin/volumes`, `DELETE /admin/volumes/{name}?force=`, `POST /admin/volumes/prune` | admin | 201 `{ volume }`; `{ ok }`; `{ removed, reclaimedBytes }` |
| `POST /admin/networks`, `DELETE /admin/networks/{id}`, `POST /admin/networks/prune` | admin | 201 `{ network }`; `{ ok }` (a built-in network is 409); `{ removed }` |
| `POST /admin/stacks/{name}/down` body `{ volumes? }` | admin | a stack with a compose file: `compose down` (`--volumes`), 120 s; without a file the Engine API way: stops and removes the containers, then the stack's networks; refused whole (409) with a protected container |
| `PUT /admin/stacks/{name}/compose` body `{ content }` | admin | writes the stack's compose file after `config --quiet` accepted it; `{ stack, composeFile }` |
| `POST /admin/stacks/{name}/up` body `{ pull?, file? }` | admin | 202 `{ operation }` (kind `stack-up`, with the CLI's `log`) |
| `DELETE /admin/stacks/{name}/compose` | admin | removes the file of a stack that is down |

`stacks start` starts the stack's existing containers; creating and updating stacks is the Compose feature below (the
Engine API has no compose).

A pull publishes `docker:operation` on the event bus (data: the operation, audience `docker:read`) on each state change
and at most once a second while its progress changes.

## Exec socket

`WS /ws/v1/qcli/docker/exec?host=&container=&cmd=&user=&cols=&rows=&ticket=` (also `/ws/qcli/docker/exec`): an
interactive session with a TTY. `cmd` defaults to `/bin/sh -c 'command -v bash >/dev/null 2>&1 && exec bash || exec sh'`.
The messages are those of `/ws/v1/qcli/shell`: the client sends `{ "type": "stdin", "data" }` and
`{ "type": "resize", "cols", "rows" }`; the server `{ "type": "ready", "shell", "os" }` (`shell` is a short label: `sh` for
the default shell, else the first word of `cmd`), `{ "type": "stdout", "data" }`, `{ "type": "exit", "code" }` and
`{ "type": "error", "message" }`. Closing the socket ends the exec. Hidden and protected containers, read-only mode, an
unknown host or container, a container that is not running and an unreachable engine are refused with ONE message
`{ "type": "error", "message" }` (the text of the matching REST error) and a normal close (1000), because a browser cannot
read the status of a refused upgrade. The server's own origin check applies (a foreign origin is closed with 4403 `origin
not allowed`); a protected server closes with 4401 `unauthorized` (no or a used ticket) or 4403 `forbidden` (no
`docker:exec`), like the shell socket. `docker exec -it <container> [command...]` in a web terminal that can run sessions
(`sessions: true` in the request) answers with a `session` block that points at this socket (the container, `cmd`, `user`);
`docker exec <container>` without a command does too.

## Terminal commands

Output v2 (typed tables, status tones, key-value panels, progress); `--host <name>` everywhere, `--json` where data is
printed (the route's answer indented by 2); destructive commands ask first (`--yes`, `-y`).

| Command | Permission | Notes |
|---|---|---|
| `docker` | read | the hosts, a summary of the default host, the sub-commands |
| `docker hosts` | read | name, endpoint, state, version, containers |
| `docker ps [--all] [--stack <name>]` | read | running containers unless `--all`; a row opens `docker inspect` |
| `docker inspect <container>` | read | panels: container, ports, mounts, networks, environment |
| `docker logs <container> [--tail <n>] [--since <10m\|2h\|ISO>] [--timestamps] [--follow]` | read | `--follow` streams until stopped (streaming terminals) |
| `docker stats [container] [--watch]` | read | `--watch` refreshes the table every 2 s |
| `docker start\|stop\|restart\|kill\|pause\|unpause <container...>` | manage | one line per container; exit 1 when any failed |
| `docker rm <container...> [--force] [--volumes] [--yes]` | admin | asks first |
| `docker exec [options] <container> [<command...>]` | exec | options `-i`, `-t`, `-it`, `--interactive`, `--tty`, `--user`/`-u`, `--workdir`/`-w`, `--timeout <s>`, `--host` go BEFORE the container (as in the docker CLI); everything after the container is the command, flags included, taken from the raw line and split like a shell line: `docker exec web ls -la /`, `docker exec -u root web sh -c "echo a; exit 3"`. Output: stdout, then stderr (warning); the command's exit code |
| `docker images`, `docker images prune [--all] [--yes]` | read; admin | |
| `docker pull <image>` | manage | progress until done |
| `docker rmi <image...> [--force] [--yes]` | admin | asks first |
| `docker stacks`, `stacks show <name>` | read | the compose file is shown when it can be read; a folder with a compose file and no containers is listed as `down` |
| `docker stacks start\|stop\|restart\|pull <name>` | manage | |
| `docker stacks up <name> [--file <path>] [--pull]` | admin | compose up; a progress block labelled with the last output line, the log as a code block when it fails |
| `docker stacks down <name> [--volumes] [--yes]` | admin | asks first |
| `docker stacks rm <name> [--yes]` | admin | deletes the compose file of a stack that is down; asks first |
| `docker compose ...` | | `compose` is an alias of `stacks` (`docker compose up shop`) |
| `docker volumes`, `volumes inspect <name>` | read | |
| `docker volumes create <name> [--driver <d>]`, `rm <name...> [--force] [--yes]`, `prune [--yes]` | admin | |
| `docker networks`, `networks inspect <name>` | read | |
| `docker networks create <name> [--driver <d>] [--internal] [--subnet <cidr>]`, `rm <name...> [--yes]`, `prune [--yes]` | admin | |
| `docker system info`, `system df`, `system events [--since <1h>] [--follow]` | read | |

## Compose

Stacks can be created, updated and removed from their compose file. This runs the `docker compose` CLI on the machine
the server runs on (the Engine API cannot do it), so **the CLI must be installed there**, for example in the server's own
container image, and the files must be under `composeRoots`: no root, no compose feature (every route answers 409 with the
text of `GET /compose`).

- Settings: `composeRoots` (the only folders files are read from, written to and run from; absolute paths only),
  `composeCommand` (default `docker compose`; `docker-compose` works, except on a TLS host) and `composeTimeoutSeconds` (900).
- Compose runs on the server's machine and **resolves `env_file`, build contexts, file secrets and `include`s on the server's disk**
  (and sends them to the engine), so compose is on for the host `local` only unless `composeHosts` lists more hosts.
- The file of stack `<name>` is the first of: the stack's `com.docker.compose.project.config_files` label (when the host is
  a unix socket and it passes the checks of the roots), `<root>/<name>/compose.yaml`, `compose.yml`, `docker-compose.yml`,
  `docker-compose.yaml` (the folder `<root>/<name>` must be a real folder directly under the root, not a link). Every path is
  checked the same way: absolute, `.yml`/`.yaml`, real path under a root, regular file, at most 256 KB. A folder directly
  under a root with one of those files and a valid name (`^[a-z0-9][a-z0-9_-]{0,62}$`) is a stack even without containers:
  it is listed with the state `down` (at most 200 folders per root); a project that has containers, hidden ones too, is never
  `down`, and a project whose containers are all hidden does not exist (`GET /stacks/<name>` is 404).
- `PUT .../compose` checks the content with `<composeCommand> --project-name=<name> --file=<temp file in the same folder> config --quiet`
  (a failure is 400 with compose's message, the temp file's path replaced by `compose.yaml`; nothing changes), then renames
  the temp file over the target: the existing file (it keeps the file's mode; a new file is 0644), or
  `<first existing root>/<name>/compose.yaml` (the folder is created, and removed again when the write fails). The target and
  its folder are never links.
- `POST .../up` is an operation of kind `stack-up` (`--project-name=<name> --file=<real path> up -d --remove-orphans`,
  `--pull always` with `pull`, in the file's folder, killed at `composeTimeoutSeconds`). `file` only serves a stack with no
  file by the rule. Its `log` holds the last 200 lines of the CLI's output (stdout and stderr merged, ANSI codes stripped,
  lines cut at 2000 characters); `message` is the last line. The `log` and `message` of a `stack-up` are shown only to
  `docker:admin` (`GET /operations`, `GET /operations/{id}` and the `docker:operation` event, personalised per socket; the
  others get `log: []` and no `message`), because compose output can quote values. One stack has at most one running `up`
  (409), it counts towards the 5 running operations, and `down`, a write and a delete of that stack are 409
  `stack <name> is already being updated` meanwhile. At most 5 other compose processes (checks, `down`) run at once.
  `down` with a file is `compose down` (`--volumes` with `volumes`), 120 s, 504 on timeout; `volumes` without a file is 400
  `volumes needs a compose file`.
- The CLI is started without a shell from an argument list, with the host's connection always as docker's global flags, the
  default socket included (`--host`, `--tlsverify --tlscacert --tlscert --tlskey`; `docker-compose` gets `DOCKER_HOST`), so a
  docker context or `DOCKER_HOST` of the server can never pick another engine. Its environment is minimal: `PATH`, `HOME`,
  `USER`, `LANG`, `TMPDIR`, the names in `composeEnv`, and `COMPOSE_INTERACTIVE_NO_CLI=1`, `COMPOSE_MENU=false`, `NO_COLOR=1`.
  Its output is never interpreted, only shown. The running processes are killed (with their process group) at the time limit
  and when the plugin stops. The audit of a failed write or `up` says `compose exited with code <n>`, never compose's message.
- `up` and compose `down` are refused (409) when the stack has a protected container (`container <name> is protected`) or
  a hidden one (`stack <name> has containers this plugin may not change`). Changes are audited (`docker.stack.up`,
  `docker.stack.down`, `docker.stack.compose.write`, `docker.stack.compose.remove`; the content is not recorded).
- The demo reads `QCLI_DOCKER_COMPOSE_ROOTS` (comma separated).

## MCP tools

The commands are MCP tools like every command (with their permissions); besides them the provider `docker` offers
structured tools returning the REST shapes: `docker_list_containers`, `docker_inspect_container`, `docker_logs`,
`docker_stats`, `docker_list_images`, `docker_list_stacks`, `docker_system_info` (`docker:read`, read-only hint),
`docker_start`, `docker_stop`, `docker_restart` (`docker:manage`) and `docker_exec` (`docker:exec`, destructive hint).
The structured provider has no remove or prune tool.

## Rules that hold for routes, commands, the socket and MCP alike

- Sign-in: the Docker socket is root-equivalent, so unless `allowUnprotected` is on a call without a signed-in caller (a
  server that is not protected) is refused everywhere: routes 403 `the Docker plugin needs a protected server (sign-in);
  see its allowUnprotected setting`, commands the same text after `Error: `, MCP tools the same error, the exec socket
  closes 4401 `login required`. The check is one method of the service, `assert_caller`, called once per call.
- `readOnly` refuses every change, including exec. Hidden containers do not exist. Protected containers can be read but
  not changed (actions, rm, exec, prune, stack actions on them).
- Every change is recorded in the server's audit log when it has one: event `docker.<object>.<action>`
  (`docker.container.restart`, `docker.image.pull`, `docker.exec.run`, `docker.exec.session`, `docker.stack.down`,
  `docker.volumes.prune`, ...), `target` `docker:<host>/<kind>/<name>`, `properties` `{ host, ... }`; the command of an exec
  is recorded, its output is not; failures carry `properties.error`, and so do changes refused by read-only mode or
  protection (hidden containers do not exist, so they leave no entry).
- A protected container, running or not, refuses `stacks down` of its stack whole; with hidden containers in the stack,
  `stacks down` leaves them and the stack's networks alone. `networks prune` is done by the plugin (not the engine's
  prune): it removes the unused custom networks and leaves those a hidden or protected container is attached to.
- Hidden containers also stay out of events: an event of another type that names one in its attributes is dropped.
- The exec socket's `exit` message carries the exec's real exit code; the exec of a client that leaves while the session
  starts is ended. An open exec session ends (close 4401 `permission removed`) when its user loses `docker:exec`, and with 4401
  `session ended` when its session ends (logout, revoke, expiry, user disabled); re-checked on every change and every 30 s
  like the shell socket.
- A stack's compose file is the first of the label `com.docker.compose.project.config_files` (only on a unix socket host and
  only when it passes the checks of `composeRoots`) and the file of the root's sub-folder (see Compose). The label is
  written by whoever created the container, so it is never trusted; anything that fails a check is `composeFile: null`.
- Cross-site: with `allowUnprotected`, a change by a caller without a principal (any route but GET, HEAD and OPTIONS, and the exec socket) that carries an `Origin` whose host:port differs from the request's `Host` is refused: 403 / close 4403 `cross-site requests are refused` (an absent Origin passes, `null` counts as cross-site). A principal always needs `docker:exec` on the exec socket, also on a server that is not protected.
- The `log` and `message` of a `stack-up` go to `docker:admin`, and to a caller without a principal only with `allowUnprotected`.
- A timed-out one-off exec (`504`) may keep running in the container: the Engine API cannot kill an exec.
- Pulls: at most 5 run at once (`409 too many operations are running (5 at most)`); a pull whose connection drops or that
  receives nothing for 120 s fails. `GET /stats` takes at most 100 ids (`400 too many ids (100 at most)`) and samples at
  most 10 containers at a time. A log line longer than 16 KB is cut and ends with `…`.
- Error texts never contain file-system paths of TLS files: an unreadable one is `cannot read the TLS files of <host>`.
- Nothing the plugin answers contains TLS key paths, registry credentials or unmasked secret-like environment values
  (names containing password, passwd, secret, token, key, credential or auth show `••••••`).

## Console page

The page is the Console module `@qodalis/console-module-docker` (group Operations, `docker:read`, with an Overview card),
embedded into the wheel by `scripts/copy_console.py` and served at `/qcli/modules/docker`; `set_console_dir(False)` leaves
it out (as does a build without the module: the plugin works without the page).

## Engine client

The plugin talks to the Engine API with a small HTTP/1.1 client on `asyncio` streams (unix socket, TCP, TLS; chunked
streams and the connection upgrade of an exec), not with `aiodocker` or `httpx`: it has no dependency besides FastAPI, and
the streams it needs (logs, events, pulls, a hijacked exec) are controlled byte by byte.

## Tests

`tests/test_docker_*.py` of the server run against a fake Engine API (`tests/docker_fake_engine.py`) fed from
`fixtures/engine/*.json`; `fixtures/README.md` says which engine request maps to which file. The expected `/execute`
answers (`fixtures/expected/commands.v2.jsonl`, `commands.v1.jsonl`) and REST answers (`fixtures/expected/rest/*.json`)
are copied from the Node server (its generator writes them); the Python tests (`tests/test_docker_expected.py`) must
produce the same, byte for byte for the commands.
