Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 2 additions & 1 deletion docs/01_session_management.md
Original file line number Diff line number Diff line change
@@ -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 <target>` now falls back to `list_assignments()` and matches by server endpoint when `<target>` 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 <name>` 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).
Expand Down Expand Up @@ -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`)
Expand Down
27 changes: 25 additions & 2 deletions docs/06_ssh_access.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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 |
Expand All @@ -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.

Expand Down
10 changes: 8 additions & 2 deletions src/colab_cli/commands/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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,
Expand Down
39 changes: 35 additions & 4 deletions src/colab_cli/commands/ssh.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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()

Expand All @@ -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)
Expand Down
160 changes: 157 additions & 3 deletions src/colab_cli/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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, ``<pid>-<random>.<label>``, in the session's directory. The OS drops
the lock however the process ends, so a file whose lock can be taken
belongs to a process that is gone, and whoever takes that lock deletes it.

Attributes:
directory: The root holding one directory per session.
"""

def __init__(self, directory: str):
"""Initializes the instance."""
self.directory = directory

def session_dir(self, session: str) -> str:
"""Returns the session's holder directory, named by a hash of the name."""
digest = hashlib.sha256(session.encode("utf-8")).hexdigest()[:16]
return os.path.join(self.directory, digest)

def _ensure_session_dir(self, session_dir: str) -> None:
for directory in (self.directory, session_dir):
os.makedirs(directory, mode=_PRIVATE_DIR_MODE, exist_ok=True)
make_private(directory, _PRIVATE_DIR_MODE)

def register(self, session: str, label: str) -> filelock.BaseFileLock | None:
"""Marks this process as holding ``session`` until ``unregister``.

Args:
session: The session name.
label: One of ``SSH_LABELS``.

Returns:
The held lock to pass to ``unregister``, or None where only soft
locks exist, so busy state is not tracked.

Raises:
ValueError: If ``label`` is not one of ``SSH_LABELS``.
filelock.Timeout: If the lock is not acquired within
``_HOLDER_LOCK_TIMEOUT_SECONDS`` seconds.
OSError: If the holder file cannot be created.
"""
if label not in SSH_LABELS:
raise ValueError(f"unknown ssh holder label: {label!r}")
self.labels(session)
session_dir = self.session_dir(session)
self._ensure_session_dir(session_dir)
name = f"{os.getpid()}-{secrets.token_hex(4)}.{label}"
path = os.path.join(session_dir, name)
holder = filelock.FileLock(
path,
timeout=_HOLDER_LOCK_TIMEOUT_SECONDS,
thread_local=False,
mode=_OWNER_ONLY_MODE,
)
try:
holder.acquire()
except FileNotFoundError:
self._ensure_session_dir(session_dir)
holder.acquire()
if isinstance(holder, filelock.SoftFileLock):
holder.release()
return None
return holder

def unregister(self, session: str, holder: filelock.BaseFileLock) -> None:
"""Releases a holder from ``register``, deleting its file; repeatable."""
_delete_and_release(holder)
self.cleanup_session(session)

def cleanup_session(self, session: str) -> None:
"""Deletes unlocked holder files for ``session`` and removes its empty dir.

Args:
session: The session name.
"""
self.labels(session)
with contextlib.suppress(OSError):
os.rmdir(self.session_dir(session))

def labels(self, session: str) -> set[str]:
"""Returns the labels of the live holders of ``session``.

A holder whose lock is free belongs to a process that is gone; probing
it deletes its file. Other entries are left alone. Where only soft locks
exist, no holder counts as live.

Args:
session: The session name.
"""
session_dir = self.session_dir(session)
try:
names = os.listdir(session_dir)
except OSError:
return set()
live = set()
for name in names:
match = _HOLDER_NAME.fullmatch(name)
if not match:
continue
probe = filelock.FileLock(
os.path.join(session_dir, name), timeout=0, mode=_OWNER_ONLY_MODE
)
try:
probe.acquire()
except filelock.Timeout:
if not isinstance(probe, filelock.SoftFileLock):
live.add(match.group(1))
except (OSError, NotImplementedError):
continue
else:
_delete_and_release(probe)
return live


class Settings(BaseModel):
update_url: str = "https://pypi.org/pypi/google-colab-cli/json"
last_check: Optional[datetime] = None
Expand All @@ -49,6 +198,7 @@ class Settings(BaseModel):


_OWNER_ONLY_MODE = 0o600
_PRIVATE_DIR_MODE = 0o700


def private_opener(path: str, flags: int) -> int:
Expand All @@ -59,10 +209,10 @@ def private_opener(path: str, flags: int) -> int:
return os.open(path, flags, _OWNER_ONLY_MODE)


def make_private(path: str) -> None:
"""Restricts an existing file to owner-only access, ignoring errors."""
def make_private(path: str, mode: int = _OWNER_ONLY_MODE) -> None:
"""Restricts an existing path to owner-only access, ignoring errors."""
with contextlib.suppress(OSError):
os.chmod(path, _OWNER_ONLY_MODE)
os.chmod(path, mode)


class _LockedFileStore:
Expand Down Expand Up @@ -135,6 +285,9 @@ def __init__(self, path: Optional[str] = None):
if not path:
path = os.path.expanduser("~/.config/colab-cli/sessions.json")
super().__init__(path)
self.ssh_holders = SshHolders(
os.path.join(os.path.dirname(self.path), "ssh-holders")
)

def _load_raw(self, f) -> Dict[str, SessionState]:
try:
Expand Down Expand Up @@ -172,6 +325,7 @@ def remove(self, name: str):
if name in sessions:
del sessions[name]
self._save_raw(f, sessions)
self.ssh_holders.cleanup_session(name)

def list(self) -> Dict[str, SessionState]:
with self._lock_shared() as f:
Expand Down
Loading