Skip to content
Merged
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
63 changes: 52 additions & 11 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -357,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
Expand All @@ -377,14 +387,16 @@ 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)
print(f"Stopped container {container_id}", file=sys.stderr)
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:
Expand All @@ -404,7 +416,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)
Expand Down Expand Up @@ -439,9 +451,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,
Expand All @@ -450,8 +461,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
Expand Down Expand Up @@ -506,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(
Expand Down Expand Up @@ -675,9 +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}")


if __name__ == "__main__":
def main() -> None:
"""
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__":
main()
147 changes: 142 additions & 5 deletions test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -76,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()


Expand Down Expand Up @@ -409,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()
Expand Down Expand Up @@ -499,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]
Expand All @@ -508,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"]
Expand All @@ -522,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]
Expand Down Expand Up @@ -621,6 +622,118 @@ def test_post_bootstrap_raises_on_other_errors():
assert urlopen.call_count == 1



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 (
patch.object(sys, "argv", argv),
patch.object(main.docker, "from_env", return_value=client),
patch.object(main, "ensure_image"),
):
try:
main.run()
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_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_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_with_client(client)

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.run()
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_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):
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_main_prints_short_error():
output = io.StringIO()
with patch.object(main, "run", side_effect=RuntimeError("boom")), redirect_stderr(output):
try:
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_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:main"

if __name__ == "__main__":
test_license_file_not_exists()
print("✓ test_license_file_not_exists passed")
Expand Down Expand Up @@ -778,4 +891,28 @@ 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_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")

test_main_prints_short_error()
print("✓ test_main_prints_short_error passed")

test_installed_command_uses_main()
print("✓ test_installed_command_uses_main passed")

print("\nAll tests passed!")
Loading