diff --git a/CHANGELOG.md b/CHANGELOG.md index 8633acd9..933ee1a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,12 @@ below corresponds to a tag of the same name. SSH session limit, `colab ssh` now says the limit is reached (N of N sessions in use on the runtime) and that the limit depends on the Colab plan. A 429 without a usable limit keeps the previous message. +- **ssh:** `colab status` shows a session as `BUSY (ssh)` instead of `IDLE` + while an interactive `colab ssh` shell is open on it, and `colab log` + records an `ssh_started` event for each shell. +- **ssh:** `colab ssh --proxy-mode` shows the session as `BUSY (ssh(proxy))` + while the bridge is connected, and a `colab ssh -- CMD` run as + `BUSY (ssh(cmd))`; each records an `ssh_proxy_started` event. ### Added diff --git a/docs/01_session_management.md b/docs/01_session_management.md index eceddeaa..91b5d48f 100644 --- a/docs/01_session_management.md +++ b/docs/01_session_management.md @@ -1,5 +1,6 @@ --- log: +2026-12-03: `colab status` also shows a session as BUSY while a live `colab ssh` process holds it, tracked by owner-only lock files (`0600`) under owner-only (`0700`) `ssh-holders/` directories next to `sessions.json` (see `06_ssh_access.md`). 2026-12-02: `colab stop -s ` now falls back to `list_assignments()` and matches by server endpoint when `` is not found in local state, allowing orphaned (`[?]`) assignments to be stopped directly (discussion #309). 2026-12-01: Extracted `assign_runtime` in `session.py` (shared by `colab new` and `colab run`) to translate exhausted `HTTP 502/503/504` and `ReadTimeout` allocation failures into actionable CLI messages (including the browser Colab Terms of Service acceptance hint for first-time/newly entitled accounts, `colab sessions`, and `COLAB_CLI_REQUEST_TIMEOUT`) with exit code 1 instead of raw tracebacks (#273). 2026-11-23: `colab stop -s ` now exits 1 when the named session does not exist (or has already vanished from the backend), delegating missing-session handling to `State.get_session` (#251). @@ -114,7 +115,7 @@ end to end; mocked timeouts alone do not establish backend compatibility. - Format: `{ "session_name": { "token": "...", "backend_url": "...", "hardware": "..." } }` ### 2. Session Status (`colab status`) -- **Session lines**: Local metadata per tracked session — hardware, shape, variant, IDLE/BUSY (from CLI bookkeeping), and optional last-execution detail. Syncs with `GET /tun/m/assignments` to prune stale entries. +- **Session lines**: Local metadata per tracked session — hardware, shape, variant, IDLE/BUSY (from CLI bookkeeping, or from a live `colab ssh` process holding the session; see `06_ssh_access.md`), and optional last-execution detail. Syncs with `GET /tun/m/assignments` to prune stale entries. - **Future**: Real-time VM resource usage (CPU/RAM/GPU) via a kernel diagnostic snippet is still TODO. For account-level compute-unit balance and usage rate, use `colab usage`. ### 3. Stop Session (`colab stop`) diff --git a/docs/06_ssh_access.md b/docs/06_ssh_access.md index b659c5ab..6c7fca30 100644 --- a/docs/06_ssh_access.md +++ b/docs/06_ssh_access.md @@ -1,5 +1,6 @@ --- log: +2026-12-03: `colab status` now shows a session as busy while any live `colab ssh` process holds it (`BUSY (ssh)` for an interactive shell with `ssh_started` in `colab log`, `BUSY (ssh(cmd))` for `colab ssh -- CMD`, and `BUSY (ssh(proxy))` for `--proxy-mode`, both after a successful handshake with `ssh_proxy_started`). Each holding process keeps an exclusive OS lock on its own empty `0600` file in a `0700` per-session directory under `0700` `ssh-holders/` next to `sessions.json` (and pre-existing holder directories are tightened to `0700`), without writing to `sessions.json`; overlapping sessions stay busy until the last one ends, a refused handshake holds nothing, a killed process drops at the next `colab status` or session removal (`colab stop` / session pruning), and empty per-session directories are removed on `unregister` or session removal. 2026-11-27: Fixed `colab ssh` under Git for Windows' MSYS `ssh` (`/usr/bin/ssh` in Git Bash): ProxyCommand path arguments now use forward slashes on Windows (bash stripped the backslashes, failing with `D:Projects...python.exe: not found`), and `UserKnownHostsFile` is `/dev/null` when `ssh.exe` is an MSYS/Cygwin build (it wrote the host key to a `./nul` file). Native Windows OpenSSH keeps `nul`. Verified live from Git Bash and PowerShell (OpenSSH_for_Windows 9.5), and `integration/repro_windows_ssh/test.py` passed. 2026-11-23: Updated `integration/repro_windows_ssh/test.py` to check cached OAuth2 credentials via the OS `keyring` (`KEYRING_SERVICE_NAME` / `KEYRING_USERNAME`) instead of the removed `TOKEN_CONFIG_PATH`, and added portable import and prerequisite-skip regression tests in `tests/test_windows_ssh.py`. 2026-11-09: `--identity/-i` now accepts either a `.pub` public key or a private key path: `_resolve_pubkey` reads the `.pub` file directly when present before falling back to `_pubkey_from_identity` (`ssh-keygen -y -f`), and `_ssh_base_args` strips `.pub` for `ssh -i` when the sibling private key exists on disk. @@ -128,7 +129,29 @@ session (never creating one); every word from CMD on goes to CMD, flags too. Windows has no SIGHUP, so registration skips it and retains SIGTERM/SIGINT. Forced process termination on Windows can also bypass cleanup; this change does not guarantee teardown after a killed process. -6. **Error handling**: The WebSocket upgrade maps each common HTTP status to an +6. **Session lifecycle**: `colab status` shows a session as busy while any + live `colab ssh` process holds it: an interactive shell holds it from just + before `ssh` starts until it returns, as `BUSY (ssh)`, and logs + `ssh_started` for `colab log`. A `--proxy-mode` bridge holds it from a + successful handshake until it ends, as `BUSY (ssh(proxy))`, and logs + `ssh_proxy_started`; a refused handshake (for example HTTP 429) holds + nothing. A `-- CMD` run's ProxyCommand child holds it the same way, as + `BUSY (ssh(cmd))`. The shell's own `--proxy-mode` child also holds the + session (and logs `ssh_proxy_started`); status prefers `ssh`, then + `ssh(cmd)`, then `ssh(proxy)`. Overlapping sessions each hold it, so the + session stays busy until the last one ends. Each holding process keeps an + exclusive OS lock on its own empty `0600` file in a `0700` per-session + directory (named by a hash of the session name) under `0700` `ssh-holders/` + next to `sessions.json` (and pre-existing holder directories are tightened + to `0700`). The OS releases that lock however the process ends, so a session + killed with `kill -9`, a bridge ended by a signal without `--rm`, or one + that OpenSSH for Windows terminates drops at the next `colab status` or when + the session is removed (`colab stop` or session pruning), which also removes + empty per-session directories (on Windows the OS may release the lock a + moment later). Where the filesystem offers no file locking, busy state is not + tracked. A `running` label set by `exec`, `repl` or `run` is shown first. + `colab ssh` never reads any of this to decide whether to connect. +7. **Error handling**: The WebSocket upgrade maps each common HTTP status to an actionable message: | Status | Meaning surfaced to the user | @@ -141,7 +164,7 @@ session (never creating one); every word from CMD on goes to CMD, flags too. | 502 | Runtime `sshd` unreachable — runtime may be unhealthy | | other / none | Raw status or a network-check hint | -7. **Remote command**: `-- CMD` resolves an existing session and runs CMD as +8. **Remote command**: `-- CMD` resolves an existing session and runs CMD as described under Remote command. Its ProxyCommand child (mode `cmd`) only resolves the session too, so neither process creates a runtime. diff --git a/src/colab_cli/commands/session.py b/src/colab_cli/commands/session.py index 27177cad..3ee66bc4 100644 --- a/src/colab_cli/commands/session.py +++ b/src/colab_cli/commands/session.py @@ -32,7 +32,7 @@ shape_display_label, ) from colab_cli.utils import get_status_code -from colab_cli.state import SessionState +from colab_cli.state import SessionState, ssh_busy_label from colab_cli.runtime import ColabRuntime @@ -335,7 +335,13 @@ def sessions_command(): def _print_status_for(s: SessionState) -> None: """Print one session's status line plus optional last-execution detail.""" - status = f"BUSY ({s.running})" if s.running else "IDLE" + from colab_cli.common import state + + if s.running: + status = f"BUSY ({s.running})" + else: + busy = ssh_busy_label(state.store.ssh_holders.labels(s.name)) + status = f"BUSY ({busy})" if busy else "IDLE" typer.echo( _format_session_line( name=s.name, diff --git a/src/colab_cli/commands/ssh.py b/src/colab_cli/commands/ssh.py index cbf6a42b..c84e269d 100644 --- a/src/colab_cli/commands/ssh.py +++ b/src/colab_cli/commands/ssh.py @@ -47,14 +47,14 @@ import subprocess import sys import threading -from typing import Callable, Optional +from typing import Callable, Iterator, Optional from urllib.parse import urlparse import uuid from colab_cli.auth import AuthProvider from colab_cli.client import COLAB_CLIENT_AGENT_HEADER from colab_cli.commands import execution -from colab_cli.state import SessionState +from colab_cli.state import SSH_CMD, SSH_INTERACTIVE, SSH_PROXY, SessionState import typer from typing_extensions import Annotated import websocket @@ -238,6 +238,34 @@ def _stop_session(name: str) -> None: typer.echo(f"[colab] --rm: failed to stop '{name}': {e}", err=True) +@contextlib.contextmanager +def _holding(name: str, label: str, event: str) -> Iterator[None]: + """Logs ``event`` and shows the session as busy while the block runs. + + Best-effort: a failure is reported on stderr and never stops the session. + """ + from colab_cli.common import state + + try: + state.history.log_event(name, event, {}) + except Exception as e: + typer.echo(f"[colab] could not log '{event}' for '{name}': {e}", err=True) + holders = state.store.ssh_holders + holder = None + try: + holder = holders.register(name, label) + except Exception as e: + typer.echo(f"[colab] could not mark '{name}' busy: {e}", err=True) + try: + yield + finally: + if holder is not None: + try: + holders.unregister(name, holder) + except Exception as e: + typer.echo(f"[colab] could not unmark '{name}' busy: {e}", err=True) + + def _build_ws_url(session: SessionState, mode: str = _DEFAULT_SSH_MODE) -> str: """Builds the WebSocket URL for the session's SSH endpoint.""" if mode not in _SSH_MODES: @@ -731,7 +759,9 @@ def _do_rm() -> None: pubkey = _resolve_pubkey(identity) ws = _connect_websocket(_build_ws_url(s, mode), pubkey) try: - return _bridge_proxy_mode(ws) + label = SSH_CMD if mode == _CMD_SSH_MODE else SSH_PROXY + with _holding(s.name, label, "ssh_proxy_started"): + return _bridge_proxy_mode(ws) finally: _do_rm() @@ -757,7 +787,8 @@ def _run_interactive_shell( err=True, ) try: - return _run_interactive_ssh(s, identity) + with _holding(s.name, SSH_INTERACTIVE, "ssh_started"): + return _run_interactive_ssh(s, identity) finally: if created and rm: _stop_session(s.name) diff --git a/src/colab_cli/state.py b/src/colab_cli/state.py index 6d08b7b3..538cd91e 100644 --- a/src/colab_cli/state.py +++ b/src/colab_cli/state.py @@ -12,9 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. +import collections.abc import contextlib +import hashlib import json import os +import re +import secrets from datetime import datetime from typing import Dict, Optional, Tuple, Iterator, IO @@ -37,6 +41,151 @@ class SessionState(BaseModel): running: Optional[str] = None +SSH_INTERACTIVE = "ssh" +SSH_CMD = "ssh(cmd)" +SSH_PROXY = "ssh(proxy)" +SSH_LABELS = (SSH_INTERACTIVE, SSH_CMD, SSH_PROXY) +_HOLDER_LOCK_TIMEOUT_SECONDS = 3 +_HOLDER_NAME = re.compile( + rf"[0-9]+-[0-9a-f]{{8}}\.({'|'.join(map(re.escape, SSH_LABELS))})" +) + + +def ssh_busy_label(labels: collections.abc.Set[str]) -> str | None: + """Returns the highest-priority held label in ``SSH_LABELS``, or None.""" + return next((label for label in SSH_LABELS if label in labels), None) + + +_RELEASE_DELETES = int(filelock.__version__.split(".")[0]) < 4 + + +def _delete_and_release(lock: filelock.BaseFileLock) -> None: + """Deletes the lock file under the lock on filelock 4+ before releasing. + + filelock 3 and Windows release() already delete the file. + """ + if lock.is_locked and not _RELEASE_DELETES: + with contextlib.suppress(OSError): + os.unlink(lock.lock_file) + lock.release() + + +class SshHolders: + """The live ``colab ssh`` processes of each session, kept as lock files. + + A process holding a session keeps an exclusive OS lock on its own empty + file, ``-.