-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdocker_client.py
More file actions
80 lines (63 loc) · 2.4 KB
/
docker_client.py
File metadata and controls
80 lines (63 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# -*- coding: utf-8 -*-
import logging
import docker
import requests_unixsocket
from config import DOCKER_SOCKET_URL
# Patch requests for http+docker:// support (or unix:// handling)
requests_unixsocket.monkeypatch()
client = None
api_client = None
init_error = None
init_attempted = False
def initialize_docker_clients(force=False):
"""Initialize Docker clients lazily so the app can start in degraded mode."""
global client, api_client, init_error, init_attempted
if init_attempted and not force and client and api_client:
return True
init_attempted = True
try:
logging.info("Attempting to connect to Docker daemon via %s", DOCKER_SOCKET_URL)
client = docker.DockerClient(base_url=DOCKER_SOCKET_URL, timeout=10)
api_client = docker.APIClient(base_url=DOCKER_SOCKET_URL, timeout=10)
client.ping()
init_error = None
logging.info("Docker client successfully connected via %s", DOCKER_SOCKET_URL)
return True
except docker.errors.DockerException as exc:
client = None
api_client = None
init_error = (
f"Failed to connect to Docker daemon at {DOCKER_SOCKET_URL}: {exc}. "
"Make sure the daemon is running and the socket is accessible."
)
logging.error(init_error)
return False
except Exception as exc:
client = None
api_client = None
init_error = f"Unexpected Docker initialization error at {DOCKER_SOCKET_URL}: {exc}"
logging.error(init_error)
return False
def get_docker_status():
"""Return the current Docker connectivity status for diagnostics."""
if not init_attempted:
initialize_docker_clients()
return {
"connected": bool(client and api_client),
"base_url": DOCKER_SOCKET_URL,
"error": init_error,
}
def get_docker_client():
"""Return the Docker client instance, retrying initialization if needed."""
if not client:
initialize_docker_clients(force=True)
if not client:
raise RuntimeError(init_error or "Docker client is not initialized.")
return client
def get_api_client():
"""Return the low-level Docker API client instance, retrying if needed."""
if not api_client:
initialize_docker_clients(force=True)
if not api_client:
raise RuntimeError(init_error or "Docker API client is not initialized.")
return api_client