From 48e4e25c9a69be4a2003ae87e3921b10668d1e2d Mon Sep 17 00:00:00 2001 From: Neal Richardson Date: Fri, 23 Oct 2026 09:38:53 -0400 Subject: [PATCH 1/3] fix: Report Docker errors and installed-command errors as a short message The installed with-connect command calls cli(), which prints RuntimeErrors as a one-line Error: message, as python main.py already did. Failures to reach Docker, create the container, or start it are reported the same way, and a container that fails to start is removed. Fixes #59. Fixes #61. Co-Authored-By: Claude Opus 5.5 --- main.py | 43 +++++++++++++++++---- pyproject.toml | 2 +- test_main.py | 102 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 139 insertions(+), 8 deletions(-) diff --git a/main.py b/main.py index 0f5cbb7..e92d34b 100644 --- a/main.py +++ b/main.py @@ -172,6 +172,16 @@ def has_local_image(client, image_name: str) -> bool: return False +def docker_client(): + """ + Connect to the Docker daemon, with a short error if it isn't reachable. + """ + try: + return docker.from_env() + except docker.errors.DockerException as e: + raise RuntimeError(f"Could not connect to Docker. Is it running? {e}") + + def _force_amd64(base_image: str) -> bool: """ Whether to force linux/amd64 when pulling and running an image. @@ -377,7 +387,7 @@ def main() -> int: container_id = args.stop or os.environ.get("CONTAINER_ID") if not container_id: raise RuntimeError("No container ID provided and CONTAINER_ID environment variable not set") - client = docker.from_env() + client = docker_client() try: container = client.containers.get(container_id) stop_connect_container(container) @@ -404,7 +414,7 @@ def main() -> int: if args.image and args.version != VERSION: raise RuntimeError("Cannot specify both 'image' and 'version'") - client = docker.from_env() + client = docker_client() if args.image: base_image, tag, used_default = parse_image_spec(args.image) @@ -439,9 +449,8 @@ def main() -> int: container_env = build_container_env(bootstrap_secret, args.env_vars) - run_kwargs = { + create_kwargs = { "image": image_name, - "detach": True, "tty": True, "stdin_open": True, "privileged": True, @@ -450,8 +459,21 @@ def main() -> int: "environment": container_env, } if _force_amd64(base_image): - run_kwargs["platform"] = "linux/amd64" - container = client.containers.run(**run_kwargs) + create_kwargs["platform"] = "linux/amd64" + # Create and start separately so a container that fails to start + # can be removed instead of left behind + try: + container = client.containers.create(**create_kwargs) + except Exception as e: + raise RuntimeError(f"Failed to create container from {image_name}: {e}") + try: + container.start() + except Exception as e: + try: + container.remove(force=True) + except Exception: + pass # Don't hide the start error behind a cleanup error + raise RuntimeError(f"Failed to start container from {image_name}: {e}") server_url = f"http://localhost:{args.port}" stop_container = True @@ -675,9 +697,16 @@ def get_api_key(bootstrap_secret: str, container, server_url: str) -> str: raise RuntimeError(f"Failed to bootstrap Connect and retrieve API key: {e}") -if __name__ == "__main__": +def cli() -> None: + """ + Console entry point: run main() and report errors as a short message. + """ try: sys.exit(main()) except RuntimeError as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1) + + +if __name__ == "__main__": + cli() diff --git a/pyproject.toml b/pyproject.toml index 1d48458..dd63c15 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,7 +9,7 @@ dependencies = [ ] [project.scripts] -with-connect = "main:main" +with-connect = "main:cli" [tool.setuptools] py-modules = ["main"] diff --git a/test_main.py b/test_main.py index 55621e9..e2e442c 100644 --- a/test_main.py +++ b/test_main.py @@ -8,6 +8,7 @@ import subprocess import sys import tempfile +import tomllib from contextlib import redirect_stderr, redirect_stdout from unittest.mock import MagicMock, Mock, patch @@ -621,6 +622,89 @@ def test_post_bootstrap_raises_on_other_errors(): assert urlopen.call_count == 1 + +def run_main_with_client(client): + """Run main() against a mock Docker client, expecting a RuntimeError.""" + with tempfile.NamedTemporaryFile(suffix=".lic") as license_file: + argv = ["with-connect", "--license", license_file.name, "--quiet"] + with ( + patch.object(sys, "argv", argv), + patch.object(main.docker, "from_env", return_value=client), + patch.object(main, "ensure_image"), + ): + try: + main.main() + except RuntimeError as e: + return str(e) + raise AssertionError("Expected RuntimeError") + + +def test_container_create_error_is_reported(): + errors = [ + docker.errors.APIError("400 Client Error: Bad Request (invalid mount config)"), + requests.exceptions.ReadTimeout("Read timed out. (read timeout=60)"), + ] + for error in errors: + client = MagicMock() + client.containers.create.side_effect = error + + message = run_main_with_client(client) + + assert "Failed to create container from" in message + assert str(error) in message + + +def test_container_start_error_removes_container(): + error = docker.errors.APIError("500 Server Error: port is already allocated") + client = MagicMock() + container = client.containers.create.return_value + container.start.side_effect = error + + message = run_main_with_client(client) + + assert "Failed to start container from" in message + assert str(error) in message + container.remove.assert_called_once_with(force=True) + + +def test_container_start_error_survives_failed_cleanup(): + client = MagicMock() + container = client.containers.create.return_value + container.start.side_effect = docker.errors.APIError("port is already allocated") + container.remove.side_effect = docker.errors.APIError("removal failed") + + message = run_main_with_client(client) + + assert "port is already allocated" in message + + +def test_docker_unreachable_is_reported(): + error = docker.errors.DockerException("Error while fetching server API version") + with patch.object(main.docker, "from_env", side_effect=error): + try: + main.docker_client() + assert False, "Expected RuntimeError" + except RuntimeError as e: + assert "Could not connect to Docker" in str(e) + assert str(error) in str(e) + + +def test_cli_prints_short_error(): + output = io.StringIO() + with patch.object(main, "main", side_effect=RuntimeError("boom")), redirect_stderr(output): + try: + main.cli() + assert False, "Expected SystemExit" + except SystemExit as e: + assert e.code == 1 + assert output.getvalue() == "Error: boom\n" + + +def test_installed_command_uses_cli(): + with open(os.path.join(os.path.dirname(__file__), "pyproject.toml"), "rb") as f: + scripts = tomllib.load(f)["project"]["scripts"] + assert scripts["with-connect"] == "main:cli" + if __name__ == "__main__": test_license_file_not_exists() print("✓ test_license_file_not_exists passed") @@ -778,4 +862,22 @@ def test_post_bootstrap_raises_on_other_errors(): test_post_bootstrap_raises_on_other_errors() print("✓ test_post_bootstrap_raises_on_other_errors passed") + test_container_create_error_is_reported() + print("✓ test_container_create_error_is_reported passed") + + test_container_start_error_removes_container() + print("✓ test_container_start_error_removes_container passed") + + test_container_start_error_survives_failed_cleanup() + print("✓ test_container_start_error_survives_failed_cleanup passed") + + test_docker_unreachable_is_reported() + print("✓ test_docker_unreachable_is_reported passed") + + test_cli_prints_short_error() + print("✓ test_cli_prints_short_error passed") + + test_installed_command_uses_cli() + print("✓ test_installed_command_uses_cli passed") + print("\nAll tests passed!") From 7f4ea3892582100ac9dada6a232b5002493ec724 Mon Sep 17 00:00:00 2001 From: Neal Richardson Date: Fri, 23 Oct 2026 09:41:32 -0400 Subject: [PATCH 2/3] fix: Report container stop failures without a traceback --stop reports a short error, and a failed stop during cleanup prints a warning instead of hiding the original error or exit code. Addresses roborev job 680. Co-Authored-By: Claude Opus 5.5 --- main.py | 12 +++++++++++- test_main.py | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/main.py b/main.py index e92d34b..56361a7 100644 --- a/main.py +++ b/main.py @@ -395,6 +395,8 @@ def main() -> int: return 0 except docker.errors.NotFound: raise RuntimeError(f"Container not found: {container_id}") + except Exception as e: + raise RuntimeError(f"Failed to stop container {container_id}: {e}") # Fail before starting Connect if the command can't be run if args.command: @@ -528,7 +530,15 @@ def main() -> int: return exit_code finally: if stop_container: - stop_connect_container(container) + # Warn instead of raising so a stop failure doesn't replace the + # command's exit code or an error that is already being raised + try: + stop_connect_container(container) + except Exception as e: + print( + f"Warning: failed to stop container {container.id}: {e}", + file=sys.stderr, + ) def is_port_open( diff --git a/test_main.py b/test_main.py index e2e442c..9ffd36a 100644 --- a/test_main.py +++ b/test_main.py @@ -678,6 +678,35 @@ def test_container_start_error_survives_failed_cleanup(): assert "port is already allocated" in message +def test_stop_error_is_reported(): + client = MagicMock() + client.containers.get.return_value.stop.side_effect = docker.errors.APIError("permission denied") + with ( + patch.object(sys, "argv", ["with-connect", "--stop", "abc123"]), + patch.object(main.docker, "from_env", return_value=client), + ): + try: + main.main() + assert False, "Expected RuntimeError" + except RuntimeError as e: + assert "Failed to stop container abc123" in str(e) + assert "permission denied" in str(e) + + +def test_cleanup_stop_error_does_not_hide_original_error(): + client = MagicMock() + container = client.containers.create.return_value + container.id = "abc123" + container.logs.return_value = b"" + container.stop.side_effect = docker.errors.APIError("daemon went away") + + stderr = io.StringIO() + with patch.object(main, "is_port_open", return_value=False), redirect_stderr(stderr): + message = run_main_with_client(client) + + assert "did not start within 60 seconds" in message + assert "Warning: failed to stop container abc123: daemon went away" in stderr.getvalue() + def test_docker_unreachable_is_reported(): error = docker.errors.DockerException("Error while fetching server API version") with patch.object(main.docker, "from_env", side_effect=error): @@ -871,6 +900,12 @@ def test_installed_command_uses_cli(): test_container_start_error_survives_failed_cleanup() print("✓ test_container_start_error_survives_failed_cleanup passed") + test_stop_error_is_reported() + print("✓ test_stop_error_is_reported passed") + + test_cleanup_stop_error_does_not_hide_original_error() + print("✓ test_cleanup_stop_error_does_not_hide_original_error passed") + test_docker_unreachable_is_reported() print("✓ test_docker_unreachable_is_reported passed") From 2f9b0259f9e86823c570852b85d496d23c9089b4 Mon Sep 17 00:00:00 2001 From: Neal Richardson Date: Fri, 23 Oct 2026 14:38:40 -0400 Subject: [PATCH 3/3] refactor: Make main() the entry point and rename the workflow to run() Co-Authored-By: Claude Opus 5.5 --- main.py | 14 ++++++++------ pyproject.toml | 2 +- test_main.py | 44 ++++++++++++++++++++++---------------------- 3 files changed, 31 insertions(+), 29 deletions(-) diff --git a/main.py b/main.py index 56361a7..b0f5c17 100644 --- a/main.py +++ b/main.py @@ -367,9 +367,9 @@ def stop_connect_container(container) -> None: container.stop(timeout=2) -def main() -> int: +def run() -> int: """ - Main entry point for the with-connect CLI tool. + Run the with-connect workflow and return the exit code. Orchestrates the full workflow: 1. Parse arguments and validate file paths @@ -707,16 +707,18 @@ def get_api_key(bootstrap_secret: str, container, server_url: str) -> str: raise RuntimeError(f"Failed to bootstrap Connect and retrieve API key: {e}") -def cli() -> None: +def main() -> None: """ - Console entry point: run main() and report errors as a short message. + Main entry point for the with-connect CLI tool. + + Runs the workflow and reports errors as a short message. """ try: - sys.exit(main()) + sys.exit(run()) except RuntimeError as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1) if __name__ == "__main__": - cli() + main() diff --git a/pyproject.toml b/pyproject.toml index dd63c15..1d48458 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,7 +9,7 @@ dependencies = [ ] [project.scripts] -with-connect = "main:cli" +with-connect = "main:main" [tool.setuptools] py-modules = ["main"] diff --git a/test_main.py b/test_main.py index 9ffd36a..65d4484 100644 --- a/test_main.py +++ b/test_main.py @@ -77,7 +77,7 @@ def test_invalid_license_detection(): except RuntimeError as e: assert "Unable to obtain a valid license" in str(e) assert "expired or invalid" in str(e) - # main() stops the container when this raises + # run() stops the container when this raises mock_container.stop.assert_not_called() @@ -410,7 +410,7 @@ def test_missing_command_fails_before_starting_connect(): output = io.StringIO() argv = ["with-connect", "--license", license_file.name, "--", "no-such-command-xyz"] with patch.object(sys, "argv", argv), redirect_stderr(output): - result_code = main.main() + result_code = main.run() assert result_code == 127 assert "command not found: no-such-command-xyz" in output.getvalue() @@ -500,7 +500,7 @@ def test_stop_mode_signals_connect(): patch.object(main.docker, "from_env", return_value=client), redirect_stderr(io.StringIO()), ): - assert main.main() == 0 + assert main.run() == 0 container.exec_run.assert_called_once_with( ["pkill", "-TERM", "-f", main.CONNECT_PROCESS_PATTERN] @@ -509,7 +509,7 @@ def test_stop_mode_signals_connect(): def test_command_mode_signals_connect_after_command(): client = MagicMock() - container = client.containers.run.return_value + container = client.containers.create.return_value container.exec_run.return_value = (0, b"") with tempfile.NamedTemporaryFile(suffix=".lic") as license_file: argv = ["with-connect", "--license", license_file.name, "--", "true"] @@ -523,7 +523,7 @@ def test_command_mode_signals_connect_after_command(): patch.object(main.subprocess, "run", return_value=Mock(returncode=0)), redirect_stderr(io.StringIO()), ): - assert main.main() == 0 + assert main.run() == 0 container.exec_run.assert_called_once_with( ["pkill", "-TERM", "-f", main.CONNECT_PROCESS_PATTERN] @@ -623,8 +623,8 @@ def test_post_bootstrap_raises_on_other_errors(): -def run_main_with_client(client): - """Run main() against a mock Docker client, expecting a RuntimeError.""" +def run_with_client(client): + """Run run() against a mock Docker client, expecting a RuntimeError.""" with tempfile.NamedTemporaryFile(suffix=".lic") as license_file: argv = ["with-connect", "--license", license_file.name, "--quiet"] with ( @@ -633,7 +633,7 @@ def run_main_with_client(client): patch.object(main, "ensure_image"), ): try: - main.main() + main.run() except RuntimeError as e: return str(e) raise AssertionError("Expected RuntimeError") @@ -648,7 +648,7 @@ def test_container_create_error_is_reported(): client = MagicMock() client.containers.create.side_effect = error - message = run_main_with_client(client) + message = run_with_client(client) assert "Failed to create container from" in message assert str(error) in message @@ -660,7 +660,7 @@ def test_container_start_error_removes_container(): container = client.containers.create.return_value container.start.side_effect = error - message = run_main_with_client(client) + message = run_with_client(client) assert "Failed to start container from" in message assert str(error) in message @@ -673,7 +673,7 @@ def test_container_start_error_survives_failed_cleanup(): container.start.side_effect = docker.errors.APIError("port is already allocated") container.remove.side_effect = docker.errors.APIError("removal failed") - message = run_main_with_client(client) + message = run_with_client(client) assert "port is already allocated" in message @@ -686,7 +686,7 @@ def test_stop_error_is_reported(): patch.object(main.docker, "from_env", return_value=client), ): try: - main.main() + main.run() assert False, "Expected RuntimeError" except RuntimeError as e: assert "Failed to stop container abc123" in str(e) @@ -702,7 +702,7 @@ def test_cleanup_stop_error_does_not_hide_original_error(): stderr = io.StringIO() with patch.object(main, "is_port_open", return_value=False), redirect_stderr(stderr): - message = run_main_with_client(client) + message = run_with_client(client) assert "did not start within 60 seconds" in message assert "Warning: failed to stop container abc123: daemon went away" in stderr.getvalue() @@ -718,21 +718,21 @@ def test_docker_unreachable_is_reported(): assert str(error) in str(e) -def test_cli_prints_short_error(): +def test_main_prints_short_error(): output = io.StringIO() - with patch.object(main, "main", side_effect=RuntimeError("boom")), redirect_stderr(output): + with patch.object(main, "run", side_effect=RuntimeError("boom")), redirect_stderr(output): try: - main.cli() + main.main() assert False, "Expected SystemExit" except SystemExit as e: assert e.code == 1 assert output.getvalue() == "Error: boom\n" -def test_installed_command_uses_cli(): +def test_installed_command_uses_main(): with open(os.path.join(os.path.dirname(__file__), "pyproject.toml"), "rb") as f: scripts = tomllib.load(f)["project"]["scripts"] - assert scripts["with-connect"] == "main:cli" + assert scripts["with-connect"] == "main:main" if __name__ == "__main__": test_license_file_not_exists() @@ -909,10 +909,10 @@ def test_installed_command_uses_cli(): test_docker_unreachable_is_reported() print("✓ test_docker_unreachable_is_reported passed") - test_cli_prints_short_error() - print("✓ test_cli_prints_short_error passed") + test_main_prints_short_error() + print("✓ test_main_prints_short_error passed") - test_installed_command_uses_cli() - print("✓ test_installed_command_uses_cli passed") + test_installed_command_uses_main() + print("✓ test_installed_command_uses_main passed") print("\nAll tests passed!")