-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker_utils.py
More file actions
77 lines (68 loc) · 2.46 KB
/
docker_utils.py
File metadata and controls
77 lines (68 loc) · 2.46 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
"""
Docker and SSH utility functions.
"""
import os
import asyncio
import logging
import paramiko
from typing import Optional
try:
import docker
from docker.client import DockerClient
except ImportError:
docker = None
DockerClient = None
logger = logging.getLogger(__name__)
DOCKER_SERVER_IP = os.environ.get("DOCKER_SERVER_IP")
DOCKER_SERVER_USER = os.environ.get("DOCKER_SERVER_USER")
SSH_PORT = os.environ.get("SSH_PORT", "22")
DOCKER_SERVER_PASSWORD = os.environ.get("DOCKER_SERVER_PASSWORD")
async def get_ssh_client() -> Optional[paramiko.SSHClient]:
"""
Establishes an SSH connection to the Docker server.
Returns:
An SSH client object if the connection is successful, otherwise None.
"""
if not all([DOCKER_SERVER_IP, DOCKER_SERVER_USER, DOCKER_SERVER_PASSWORD]):
logger.error(
"Docker: SSH connection details (IP, User, Password) are not fully set in environment variables.")
return None
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
logger.info(
f"Docker: Attempting to establish SSH connection to {DOCKER_SERVER_IP} as {DOCKER_SERVER_USER}...")
try:
await asyncio.to_thread(
ssh.connect,
DOCKER_SERVER_IP,
port=int(SSH_PORT),
username=DOCKER_SERVER_USER,
password=DOCKER_SERVER_PASSWORD
)
logger.info(
f"Docker: Successfully established SSH connection to {DOCKER_SERVER_IP}.")
return ssh
except paramiko.AuthenticationException:
logger.error(
f"Docker: SSH Authentication failed for {DOCKER_SERVER_USER}@{DOCKER_SERVER_IP}. Check credentials.")
except paramiko.SSHException as e:
logger.error(f"Docker: SSH negotiation failed or other SSH error: {e}")
except Exception as e:
logger.error(
f"Docker: An unexpected error occurred during SSH connection: {e}", exc_info=True)
return None
def get_docker_client() -> Optional[DockerClient]:
"""
Gets the Docker client.
Returns:
The Docker client if available, otherwise None.
"""
if not docker:
logger.error("The 'docker' library is not installed. Docker commands will not work.")
return None
try:
return docker.from_env()
except Exception as e:
logger.error(
f"Could not connect to Docker daemon: {e}. Is Docker running and socket mounted correctly?")
return None