Engine picker: switch between Docker contexts #16

Closed
opened 2026-11-30 14:39:42 +00:00 by jfro · 1 comment
Owner

Krane uses DOCKER_HOST or /var/run/docker.sock only.

What

  • Read Docker contexts (~/.docker/contexts, current context from ~/.docker/config.json) and offer a picker in the sidebar footer and the tray.
  • Covers rootless Docker, Podman's Docker-compatible socket, and remote hosts (ssh:// / tcp+TLS).
  • Remember the choice; DOCKER_HOST still wins when set.
  • Show which engine is connected (name, version) in the existing engine status area.
Krane uses `DOCKER_HOST` or `/var/run/docker.sock` only. **What** - Read Docker contexts (`~/.docker/contexts`, current context from `~/.docker/config.json`) and offer a picker in the sidebar footer and the tray. - Covers rootless Docker, Podman's Docker-compatible socket, and remote hosts (ssh:// / tcp+TLS). - Remember the choice; `DOCKER_HOST` still wins when set. - Show which engine is connected (name, version) in the existing engine status area.
jfro added this to the v1.0 milestone 2026-11-30 14:47:14 +00:00
Author
Owner

Approach for #16, researched and tested by Nye (Krane team) on a real box. Probe code went to the dev directly.

Krane #16 engine picker: how to build it (Nye, tested Nov 30)

Tested on a real box with bollard 0.20 (features ssh,ssl), rust 1.100. Five engines, each
connected, version(), 5x ping(), and received a live events() message from a container
started through it:

kind host result
default (local) unix:///var/run/docker.sock Docker 26.1.5, API 1.45, events OK
Podman rootless unix:///run/user/1000/podman/podman.sock Podman 5.4.2, API 1.41, events OK
ssh ssh://peak@localhost Docker 26.1.5 via docker system dial-stdio, events OK
tcp + TLS (client cert required) tcp://127.0.0.1:2376 + context tls dir OK; same CA without client cert is refused
tcp plain tcp://127.0.0.1:2375 OK

Rootless Docker ($XDG_RUNTIME_DIR/docker.sock) isn't installed here, but it's the same unix path
as Podman's, so the same code. Probe: issue16-probe.rs (+ Cargo.toml) alongside this file.

1. Reading contexts

  • Config dir: $DOCKER_CONFIG if set, else ~/.docker.
  • Each context: contexts/meta/<sha256(name) hex>/meta.json:
    {"Name":"podman","Metadata":{"Description":"..."},"Endpoints":{"docker":{"Host":"unix:///...","SkipTLSVerify":false}}}
    Use Endpoints.docker.Host; skip entries without a docker endpoint; ignore bad JSON (log it).
    Description is optional (Metadata may be {}).
  • TLS material: contexts/tls/<sha256(name)>/docker/{ca.pem,cert.pem,key.pem} (exists only when the
    context was created with ca=/cert=/key=).
  • default is never on disk. Synthesize it: host unix:///var/run/docker.sock (label "Docker (local)").
  • Current CLI context: $DOCKER_CONTEXT, else currentContext in config.json, else default
    (docker context use default removes the key, so missing = default).
  • Re-read on picker open (cheap; a handful of small files). No file watcher needed.
  • Add sha2 (or hash with what's already in the tree) + serde derive; or parse with serde_json::Value.

2. Connecting each kind (bollard 0.20)

Enable features: bollard = { version = "0.20.0", features = ["ssh", "ssl"] }.
ssl pulls rustls+ring (+native certs); ssh pulls openssh, which shells out to the system
ssh client (needs openssh-client installed at runtime; uses ~/.ssh/config, agent, known_hosts).

match host {
  h if h.starts_with("unix://")  => Docker::connect_with_unix(h, 120, API_DEFAULT_VERSION),
  h if h.starts_with("ssh://")   => Docker::connect_with_ssh(h, 120, API_DEFAULT_VERSION, None),
  h if h.starts_with("tcp://") || h.starts_with("https://") => match tls_dir {
      Some(d) => Docker::connect_with_ssl(h, &d.join("key.pem"), &d.join("cert.pem"), &d.join("ca.pem"), 120, API_DEFAULT_VERSION),
      None    => Docker::connect_with_http(h, 120, API_DEFAULT_VERSION) },
  other => Err(UnsupportedURISchemeError { uri: other.into() }),  // npipe etc: show "unsupported"
}
  • For DOCKER_HOST=tcp:// with DOCKER_TLS_VERIFY / DOCKER_CERT_PATH, use the same ssl branch with
    $DOCKER_CERT_PATH (default ~/.docker). Docker::connect_with_defaults() already does exactly the
    env case (unix/tcp/https/ssh) once the features are on; use it for the DOCKER_HOST path.
  • SkipTLSVerify: true contexts: bollard has no skip-verify switch. List them, mark "not supported".
  • A context with a TLS dir missing one of the three files: connect_with_ssl errors; show that error.
  • Today Krane only does connect_with_local_defaults() (unix only), so DOCKER_HOST=tcp/ssh doesn't
    work at all now; this fixes that too.

Must-do: one shared client, not connect-per-call

Krane calls Docker::connect_with_local_defaults() in ~14 places (docker.rs, window/mod.rs,
window/logs.rs). For unix that's harmless; for ssh every new client launches a new ssh master
process (bollard's SshConnector does launch_master per connection), and each connect would
re-auth (slow, agent prompts). Make one engine::current() -> Docker (Docker is Clone and shares
its pool) behind an RwLock/arc-swap plus a generation counter, and replace every call site.

Must-do: timeouts

A dead tcp host made the docker CLI hang 1m38s before "i/o timeout". Wrap the first
version()/ping() on connect (and the 3 s poll) in tokio::time::timeout(5s) so the UI shows
"engine unreachable" quickly instead of hanging the fetch loop.

Volume sizes

volume_sizes() opens the socket from DOCKER_HOST directly. Point it at the selected engine's
unix path (and skip for ssh/tcp, as it already does for non-unix). Podman's df JSON may differ;
the parser already tolerates missing keys (returns empty), so sizes just disappear there.

3. Precedence and persistence (matches the docker CLI; verified)

  1. DOCKER_HOST set and non-empty -> it wins. Picker shows it as a fixed "DOCKER_HOST (tcp://...)"
    entry, others disabled with a tooltip. (CLI check: DOCKER_HOST + DOCKER_CONTEXT=podman -> Docker.)
  2. else Krane's remembered choice, if that context still exists.
  3. else $DOCKER_CONTEXT, else config.json currentContext, else default.
    Store the choice by context name in $XDG_CONFIG_HOME/krane/settings.json (default
    ~/.config/krane/), {"engine":"podman"}; write via temp file + rename. Don't call
    docker context use (Krane mustn't change the user's shell default). If #18/#19 add a settings file
    first, share it.

4. Switching engine: resetting app state

On select: build the new client, version() with 5 s timeout; on success:

  1. bump ENGINE_GENERATION and swap the shared client;
  2. clear container state + RESOURCES (images/volumes/networks/stats), set ENGINE_CHECKED=false so
    the UI shows "connecting" not stale data from the old engine;
  3. the event watcher (watch_resource_events) and any stats/logs streams must drop: easiest is each
    loop captures the generation at start and breaks when it changes (or select! on a
    watch::Receiver<u64>); then it reconnects with engine::current(). Same for open log windows
    (close them or show "engine changed") and the #11 stats stream;
  4. kick RESOURCE_KICK + container refresh immediately (don't wait the 3 s tick);
  5. update engine status area: context name + version.platform.name/version ("Podman 5.4.2" vs
    "Docker 26.1.5"); tray menu rebuilt.
    On failure: keep the old engine, show the error, don't persist.

5. #14 debug shell (and #20 open-in-terminal) must target the same engine

The terminal runs the docker CLI, which by itself follows DOCKER_HOST / currentContext, not Krane's
choice. Pass the engine explicitly:

  • choice is a context (incl. default): docker --context <name> start -ai <helper>.
    Use --context, not -H <host>: -H tcp://... loses the context's TLS certs.
  • DOCKER_HOST wins: run plain docker ... (env is inherited). Never add --context in that case:
    tested, --context podman beats DOCKER_HOST, so it would hit a different engine than Krane.
  • Also set DOCKER_CONTEXT= in the spawned terminal's env for #20, so docker typed by the user
    hits the same engine.
    Checked the #14 helper on Podman 5.4.2 via the CLI: --pid container:X --network container:X --cap-add SYS_PTRACE works (ps shows target PID 1, /proc/1/root readable).
    For ssh engines the helper runs remotely; docker --context <ssh ctx> start -ai works (dial-stdio).

6. Test plan for review

  • unit tests: meta.json parsing (with/without Description, no docker endpoint, bad JSON), sha dir
    name, currentContext missing/default, precedence table (DOCKER_HOST > saved > DOCKER_CONTEXT >
    config > default), saved context deleted -> fallback.
  • --mock: picker shows a few fake engines (mock data for screenshots).
  • real: I'll re-run the 5-engine setup above against the PR (contexts + stunnel TLS + sshd + podman).

Calls for Jeremy

None needed. Defaults chosen: Krane remembers its own choice (doesn't touch docker context use);
DOCKER_HOST locks the picker; SkipTLSVerify contexts shown as unsupported.

Approach for #16, researched and tested by Nye (Krane team) on a real box. Probe code went to the dev directly. # Krane #16 engine picker: how to build it (Nye, tested Nov 30) Tested on a real box with bollard 0.20 (features `ssh`,`ssl`), rust 1.100. Five engines, each connected, `version()`, 5x `ping()`, and received a live `events()` message from a container started through it: | kind | host | result | |---|---|---| | default (local) | unix:///var/run/docker.sock | Docker 26.1.5, API 1.45, events OK | | Podman rootless | unix:///run/user/1000/podman/podman.sock | Podman 5.4.2, API 1.41, events OK | | ssh | ssh://peak@localhost | Docker 26.1.5 via `docker system dial-stdio`, events OK | | tcp + TLS (client cert required) | tcp://127.0.0.1:2376 + context tls dir | OK; same CA without client cert is refused | | tcp plain | tcp://127.0.0.1:2375 | OK | Rootless Docker ($XDG_RUNTIME_DIR/docker.sock) isn't installed here, but it's the same unix path as Podman's, so the same code. Probe: issue16-probe.rs (+ Cargo.toml) alongside this file. ## 1. Reading contexts - Config dir: `$DOCKER_CONFIG` if set, else `~/.docker`. - Each context: `contexts/meta/<sha256(name) hex>/meta.json`: `{"Name":"podman","Metadata":{"Description":"..."},"Endpoints":{"docker":{"Host":"unix:///...","SkipTLSVerify":false}}}` Use `Endpoints.docker.Host`; skip entries without a docker endpoint; ignore bad JSON (log it). Description is optional (Metadata may be `{}`). - TLS material: `contexts/tls/<sha256(name)>/docker/{ca.pem,cert.pem,key.pem}` (exists only when the context was created with ca=/cert=/key=). - `default` is never on disk. Synthesize it: host `unix:///var/run/docker.sock` (label "Docker (local)"). - Current CLI context: `$DOCKER_CONTEXT`, else `currentContext` in `config.json`, else `default` (`docker context use default` *removes* the key, so missing = default). - Re-read on picker open (cheap; a handful of small files). No file watcher needed. - Add `sha2` (or hash with what's already in the tree) + `serde` derive; or parse with serde_json::Value. ## 2. Connecting each kind (bollard 0.20) Enable features: `bollard = { version = "0.20.0", features = ["ssh", "ssl"] }`. `ssl` pulls rustls+ring (+native certs); `ssh` pulls `openssh`, which shells out to the system `ssh` client (needs openssh-client installed at runtime; uses ~/.ssh/config, agent, known_hosts). ```rust match host { h if h.starts_with("unix://") => Docker::connect_with_unix(h, 120, API_DEFAULT_VERSION), h if h.starts_with("ssh://") => Docker::connect_with_ssh(h, 120, API_DEFAULT_VERSION, None), h if h.starts_with("tcp://") || h.starts_with("https://") => match tls_dir { Some(d) => Docker::connect_with_ssl(h, &d.join("key.pem"), &d.join("cert.pem"), &d.join("ca.pem"), 120, API_DEFAULT_VERSION), None => Docker::connect_with_http(h, 120, API_DEFAULT_VERSION) }, other => Err(UnsupportedURISchemeError { uri: other.into() }), // npipe etc: show "unsupported" } ``` - For DOCKER_HOST=tcp:// with DOCKER_TLS_VERIFY / DOCKER_CERT_PATH, use the same ssl branch with `$DOCKER_CERT_PATH` (default ~/.docker). `Docker::connect_with_defaults()` already does exactly the env case (unix/tcp/https/ssh) once the features are on; use it for the DOCKER_HOST path. - `SkipTLSVerify: true` contexts: bollard has no skip-verify switch. List them, mark "not supported". - A context with a TLS dir missing one of the three files: connect_with_ssl errors; show that error. - Today Krane only does `connect_with_local_defaults()` (unix only), so DOCKER_HOST=tcp/ssh doesn't work at all now; this fixes that too. ### Must-do: one shared client, not connect-per-call Krane calls `Docker::connect_with_local_defaults()` in ~14 places (docker.rs, window/mod.rs, window/logs.rs). For unix that's harmless; for ssh every new client launches a new ssh master process (bollard's SshConnector does `launch_master` per connection), and each connect would re-auth (slow, agent prompts). Make one `engine::current() -> Docker` (Docker is Clone and shares its pool) behind an `RwLock`/arc-swap plus a generation counter, and replace every call site. ### Must-do: timeouts A dead tcp host made the docker CLI hang 1m38s before "i/o timeout". Wrap the first `version()`/`ping()` on connect (and the 3 s poll) in `tokio::time::timeout(5s)` so the UI shows "engine unreachable" quickly instead of hanging the fetch loop. ### Volume sizes `volume_sizes()` opens the socket from `DOCKER_HOST` directly. Point it at the selected engine's unix path (and skip for ssh/tcp, as it already does for non-unix). Podman's df JSON may differ; the parser already tolerates missing keys (returns empty), so sizes just disappear there. ## 3. Precedence and persistence (matches the docker CLI; verified) 1. `DOCKER_HOST` set and non-empty -> it wins. Picker shows it as a fixed "DOCKER_HOST (tcp://...)" entry, others disabled with a tooltip. (CLI check: DOCKER_HOST + DOCKER_CONTEXT=podman -> Docker.) 2. else Krane's remembered choice, if that context still exists. 3. else `$DOCKER_CONTEXT`, else config.json `currentContext`, else `default`. Store the choice by context *name* in `$XDG_CONFIG_HOME/krane/settings.json` (default ~/.config/krane/), `{"engine":"podman"}`; write via temp file + rename. Don't call `docker context use` (Krane mustn't change the user's shell default). If #18/#19 add a settings file first, share it. ## 4. Switching engine: resetting app state On select: build the new client, `version()` with 5 s timeout; on success: 1. bump `ENGINE_GENERATION` and swap the shared client; 2. clear container state + RESOURCES (images/volumes/networks/stats), set ENGINE_CHECKED=false so the UI shows "connecting" not stale data from the old engine; 3. the event watcher (`watch_resource_events`) and any stats/logs streams must drop: easiest is each loop captures the generation at start and breaks when it changes (or `select!` on a `watch::Receiver<u64>`); then it reconnects with `engine::current()`. Same for open log windows (close them or show "engine changed") and the #11 stats stream; 4. kick `RESOURCE_KICK` + container refresh immediately (don't wait the 3 s tick); 5. update engine status area: context name + `version.platform.name`/`version` ("Podman 5.4.2" vs "Docker 26.1.5"); tray menu rebuilt. On failure: keep the old engine, show the error, don't persist. ## 5. #14 debug shell (and #20 open-in-terminal) must target the same engine The terminal runs the docker CLI, which by itself follows DOCKER_HOST / currentContext, not Krane's choice. Pass the engine explicitly: - choice is a context (incl. `default`): `docker --context <name> start -ai <helper>`. Use `--context`, not `-H <host>`: `-H tcp://...` loses the context's TLS certs. - DOCKER_HOST wins: run plain `docker ...` (env is inherited). Never add --context in that case: tested, `--context podman` beats DOCKER_HOST, so it would hit a different engine than Krane. - Also set DOCKER_CONTEXT=<name> in the spawned terminal's env for #20, so `docker` typed by the user hits the same engine. Checked the #14 helper on Podman 5.4.2 via the CLI: `--pid container:X --network container:X --cap-add SYS_PTRACE` works (ps shows target PID 1, /proc/1/root readable). For ssh engines the helper runs remotely; `docker --context <ssh ctx> start -ai` works (dial-stdio). ## 6. Test plan for review - unit tests: meta.json parsing (with/without Description, no docker endpoint, bad JSON), sha dir name, currentContext missing/`default`, precedence table (DOCKER_HOST > saved > DOCKER_CONTEXT > config > default), saved context deleted -> fallback. - --mock: picker shows a few fake engines (mock data for screenshots). - real: I'll re-run the 5-engine setup above against the PR (contexts + stunnel TLS + sshd + podman). ## Calls for Jeremy None needed. Defaults chosen: Krane remembers its own choice (doesn't touch `docker context use`); DOCKER_HOST locks the picker; SkipTLSVerify contexts shown as unsupported.
jfro closed this issue 2026-11-30 19:51:50 +00:00
Sign in to join this conversation.
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
jfro/krane#16
No description provided.