diff --git a/podman/client.py b/podman/client.py index f9a023e7..821e271d 100644 --- a/podman/client.py +++ b/podman/client.py @@ -69,8 +69,15 @@ def __init__(self, **kwargs) -> None: # Override configured identity, if provided in arguments api_kwargs["identity"] = kwargs.get("identity", str(connection.identity)) elif "base_url" not in api_kwargs: - path = str(Path(get_runtime_dir()) / "podman" / "podman.sock") - api_kwargs["base_url"] = "http+unix://" + path + # Check if there's an active service configured and is a podman machine + active_service = config.active_service + if active_service and active_service.is_machine: + api_kwargs["base_url"] = active_service.url.geturl() + api_kwargs["identity"] = kwargs.get("identity", str(active_service.identity)) + else: + # Fall back to local Unix socket + path = str(Path(get_runtime_dir()) / "podman" / "podman.sock") + api_kwargs["base_url"] = "http+unix://" + path self.api = APIClient(**api_kwargs) def __enter__(self) -> "PodmanClient": diff --git a/podman/domain/config.py b/podman/domain/config.py index 1d4e8bf7..bd60ca51 100644 --- a/podman/domain/config.py +++ b/podman/domain/config.py @@ -59,6 +59,11 @@ def identity(self): return Path(self.attrs.get("identity")) return Path(self.attrs.get("Identity")) + @cached_property + def is_machine(self) -> bool: + """bool: Returns True if connection is to a Podman machine.""" + return self.attrs.get("IsMachine", False) + class PodmanConfig: """PodmanConfig provides a representation of the containers.conf file.""" diff --git a/podman/tests/unit/test_podmanclient.py b/podman/tests/unit/test_podmanclient.py index fdf8d344..78a7a84b 100644 --- a/podman/tests/unit/test_podmanclient.py +++ b/podman/tests/unit/test_podmanclient.py @@ -6,6 +6,7 @@ import requests_mock +from podman.domain.config import PodmanConfig, ServiceConnection from podman import PodmanClient, tests from podman.api.path_utils import get_runtime_dir, get_xdg_config_home @@ -108,6 +109,23 @@ def test_connect_default(self): expected = Path(get_xdg_config_home()) / "containers" / "containers.conf" PodmanClientTestCase.opener.assert_called_with(expected, encoding="utf-8") + def test_connect_with_connection_file(self): + mock_config = MagicMock(spec=PodmanConfig) + mock_service = MagicMock(spec=ServiceConnection) + mock_service.url.geturl.return_value = ( + "http+ssh://core@127.0.0.1:58468/run/user/501/podman/podman.sock" + ) + mock_service.identity = "/Users/test/.local/share/containers/podman/machine/machine" + mock_service.is_machine = True + mock_config.active_service = mock_service + + with mock.patch('podman.client.PodmanConfig', return_value=mock_config): + # Mock pathlib.Path.exists to return True for the identity file + with mock.patch('pathlib.Path.exists', return_value=True): + with PodmanClient() as client: + expected = "http+ssh://core@127.0.0.1:58468/run/user/501/podman/podman.sock" + self.assertEqual(client.api.base_url.geturl(), expected) + if __name__ == '__main__': unittest.main()