Skip to content

Commit 47a91f4

Browse files
committed
fix: Enhance environment connection error handling
Signed-off-by: Kanishk Pachauri <[email protected]>
1 parent 67aedd4 commit 47a91f4

File tree

2 files changed

+87
-20
lines changed

2 files changed

+87
-20
lines changed

podman/client.py

Lines changed: 32 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
from podman.domain.secrets import SecretsManager
2020
from podman.domain.system import SystemManager
2121
from podman.domain.volumes import VolumesManager
22+
from podman.errors.exceptions import PodmanConnectionError
2223

2324
logger = logging.getLogger("podman")
2425

@@ -114,27 +115,38 @@ def from_env(
114115
Client used to communicate with a Podman service.
115116
116117
Raises:
117-
ValueError when required environment variable is not set
118+
PodmanConnectionError: When connection to service fails or environment is invalid
118119
"""
119-
environment = environment or os.environ
120-
credstore_env = credstore_env or {}
121-
122-
if version == "auto":
123-
version = None
124-
125-
kwargs = {
126-
'version': version,
127-
'timeout': timeout,
128-
'tls': False,
129-
'credstore_env': credstore_env,
130-
'max_pool_size': max_pool_size,
131-
}
132-
133-
host = environment.get("CONTAINER_HOST") or environment.get("DOCKER_HOST") or None
134-
if host is not None:
135-
kwargs['base_url'] = host
136-
137-
return PodmanClient(**kwargs)
120+
try:
121+
environment = environment or os.environ
122+
credstore_env = credstore_env or {}
123+
124+
if version == "auto":
125+
version = None
126+
127+
kwargs = {
128+
'version': version,
129+
'timeout': timeout,
130+
'tls': False,
131+
'credstore_env': credstore_env,
132+
'max_pool_size': max_pool_size,
133+
}
134+
135+
host = environment.get("CONTAINER_HOST") or environment.get("DOCKER_HOST") or None
136+
if host is not None:
137+
kwargs['base_url'] = host
138+
139+
return PodmanClient(**kwargs)
140+
except Exception as exc:
141+
error_msg = "Failed to initialize Podman client from environment"
142+
if isinstance(exc, ValueError):
143+
error_msg = "Invalid environment configuration for Podman client"
144+
elif isinstance(exc, (ConnectionError, TimeoutError)):
145+
error_msg = "Failed to connect to Podman service"
146+
147+
raise PodmanConnectionError(
148+
message=error_msg, environment=environment, host=host, original_error=exc
149+
) from exc
138150

139151
@cached_property
140152
def containers(self) -> ContainersManager:

podman/errors/exceptions.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,3 +142,58 @@ def __init__(
142142

143143
class InvalidArgument(PodmanError):
144144
"""Parameter to method/function was not valid."""
145+
146+
147+
class PodmanConnectionError(PodmanError):
148+
"""Exception raised when connection to Podman service fails using environment configuration."""
149+
150+
def __init__(
151+
self,
152+
message: str,
153+
environment: Optional[Dict[str, str]] = None,
154+
host: Optional[str] = None,
155+
original_error: Optional[Exception] = None,
156+
):
157+
"""Initialize PodmanConnectionError.
158+
159+
Args:
160+
message: Description of the error
161+
environment: Environment variables used in connection attempt
162+
host: URL to Podman service that failed
163+
original_error: Original exception that caused this error
164+
"""
165+
super().__init__(message)
166+
self.environment = environment
167+
self.host = host
168+
self.original_error = original_error
169+
170+
def __str__(self) -> str:
171+
"""Format error message with details about connection attempt."""
172+
msg = [super().__str__()]
173+
174+
if self.host:
175+
msg.append(f"Host: {self.host}")
176+
177+
if self.environment:
178+
relevant_vars = {
179+
k: v
180+
for k, v in self.environment.items()
181+
if k
182+
in (
183+
'DOCKER_HOST',
184+
'CONTAINER_HOST',
185+
'DOCKER_TLS_VERIFY',
186+
'CONTAINER_TLS_VERIFY',
187+
'DOCKER_CERT_PATH',
188+
'CONTAINER_CERT_PATH',
189+
)
190+
}
191+
if relevant_vars:
192+
msg.append("Environment:")
193+
for key, value in relevant_vars.items():
194+
msg.append(f" {key}={value}")
195+
196+
if self.original_error:
197+
msg.append(f"Caused by: {str(self.original_error)}")
198+
199+
return " | ".join(msg)

0 commit comments

Comments
 (0)