forked from andyjsmith/CTFd-Docker-Plugin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontainer_manager.py
executable file
·310 lines (265 loc) · 10.2 KB
/
container_manager.py
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
"""
This module defines the ContainerManager class for managing Docker containers in CTFd.
It also includes a custom ContainerException class for handling container-related errors.
"""
import atexit
import time
import json
import docker
import paramiko.ssh_exception
import requests
from flask import Flask
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.schedulers import SchedulerNotRunningError
from CTFd.models import db
from .models import ContainerInfoModel
class ContainerException(Exception):
"""
Custom exception class for container-related errors.
"""
def __init__(self, *args: object) -> None:
super().__init__(*args)
if args:
self.message = args[0]
else:
self.message = None
def __str__(self) -> str:
if self.message:
return self.message
else:
return "Unknown Container Exception"
class ContainerManager:
"""
Manages Docker containers for CTFd challenges.
"""
def __init__(self, settings, app):
"""
Initialize the ContainerManager.
Args:
settings (dict): Configuration settings for the container manager.
app (Flask): The Flask application instance.
"""
self.settings = settings
self.client = None
self.app = app
if settings.get("docker_base_url") is None or settings.get("docker_base_url") == "":
return
# Connect to the docker daemon
try:
self.initialize_connection(settings, app)
except ContainerException:
print("Docker could not initialize or connect.")
return
def initialize_connection(self, settings, app) -> None:
"""
Initialize the connection to the Docker daemon.
Args:
settings (dict): Configuration settings for the container manager.
app (Flask): The Flask application instance.
Raises:
ContainerException: If unable to connect to Docker.
"""
self.settings = settings
self.app = app
# Remove any leftover expiration schedulers
try:
self.expiration_scheduler.shutdown()
except (SchedulerNotRunningError, AttributeError):
# Scheduler was never running
pass
if settings.get("docker_base_url") is None:
self.client = None
return
try:
self.client = docker.DockerClient(
base_url=settings.get("docker_base_url"))
except (docker.errors.DockerException) as e:
self.client = None
raise ContainerException("CTFd could not connect to Docker")
except TimeoutError as e:
self.client = None
raise ContainerException(
"CTFd timed out when connecting to Docker")
except paramiko.ssh_exception.NoValidConnectionsError as e:
self.client = None
raise ContainerException(
"CTFd timed out when connecting to Docker: " + str(e))
except paramiko.ssh_exception.AuthenticationException as e:
self.client = None
raise ContainerException(
"CTFd had an authentication error when connecting to Docker: " + str(e))
# Set up expiration scheduler
try:
self.expiration_seconds = int(
settings.get("container_expiration", 0)) * 60
except (ValueError, AttributeError):
self.expiration_seconds = 0
EXPIRATION_CHECK_INTERVAL = 5
if self.expiration_seconds > 0:
self.expiration_scheduler = BackgroundScheduler()
self.expiration_scheduler.add_job(
func=self.kill_expired_containers, args=(app,), trigger="interval", seconds=EXPIRATION_CHECK_INTERVAL)
self.expiration_scheduler.start()
# Shut down the scheduler when exiting the app
atexit.register(lambda: self.expiration_scheduler.shutdown())
def run_command(func):
"""
Decorator to ensure Docker connection is active before running a command.
"""
def wrapper_run_command(self, *args, **kwargs):
if self.client is None:
try:
self.__init__(self.settings, self.app)
except:
raise ContainerException("Docker is not connected")
try:
if self.client is None:
raise ContainerException("Docker is not connected")
if self.client.ping():
return func(self, *args, **kwargs)
except (paramiko.ssh_exception.SSHException, ConnectionError, requests.exceptions.ConnectionError) as e:
# Try to reconnect before failing
try:
self.__init__(self.settings, self.app)
except:
pass
raise ContainerException(
"Docker connection was lost. Please try your request again later.")
return wrapper_run_command
@run_command
def kill_expired_containers(self, app: Flask):
"""
Kill containers that have expired.
Args:
app (Flask): The Flask application instance.
"""
with app.app_context():
containers: "list[ContainerInfoModel]" = ContainerInfoModel.query.all()
for container in containers:
delta_seconds = container.expires - int(time.time())
if delta_seconds < 0:
try:
self.kill_container(container.container_id)
except ContainerException:
print(
"[Container Expiry Job] Docker is not initialized. Please check your settings.")
db.session.delete(container)
db.session.commit()
@run_command
def is_container_running(self, container_id: str) -> bool:
"""
Check if a container is running.
Args:
container_id (str): The ID of the container to check.
Returns:
bool: True if the container is running, False otherwise.
"""
container = self.client.containers.list(filters={"id": container_id})
if len(container) == 0:
return False
return container[0].status == "running"
@run_command
def create_container(self, image: str, port: int, command: str, volumes: str):
"""
Create a new Docker container.
Args:
image (str): The Docker image to use.
port (int): The port to expose.
command (str): The command to run in the container.
volumes (str): JSON string representing volume configurations.
Returns:
docker.models.containers.Container: The created container.
Raises:
ContainerException: If the container creation fails.
"""
kwargs = {}
# Set the memory and CPU limits for the container
if self.settings.get("container_maxmemory"):
try:
mem_limit = int(self.settings.get("container_maxmemory"))
if mem_limit > 0:
kwargs["mem_limit"] = f"{mem_limit}m"
except ValueError:
ContainerException(
"Configured container memory limit must be an integer")
if self.settings.get("container_maxcpu"):
try:
cpu_period = float(self.settings.get("container_maxcpu"))
if cpu_period > 0:
kwargs["cpu_quota"] = int(cpu_period * 100000)
kwargs["cpu_period"] = 100000
except ValueError:
ContainerException(
"Configured container CPU limit must be a number")
if volumes is not None and volumes != "":
print("Volumes:", volumes)
try:
volumes_dict = json.loads(volumes)
kwargs["volumes"] = volumes_dict
except json.decoder.JSONDecodeError:
raise ContainerException("Volumes JSON string is invalid")
try:
return self.client.containers.run(
image,
ports={str(port): None},
command=command,
detach=True,
auto_remove=True,
**kwargs
)
except docker.errors.ImageNotFound:
raise ContainerException("Docker image not found")
@run_command
def get_container_port(self, container_id: str) -> "str|None":
"""
Get the host port that a container's port is mapped to.
Args:
container_id (str): The ID of the container.
Returns:
str|None: The host port, or None if not found.
"""
try:
for port in list(self.client.containers.get(container_id).ports.values()):
if port is not None:
return port[0]["HostPort"]
except (KeyError, IndexError):
return None
@run_command
def get_images(self) -> "list[str]|None":
"""
Get a list of available Docker images.
Returns:
list[str]|None: A sorted list of image tags, or None if no images are found.
"""
try:
images = self.client.images.list()
except (KeyError, IndexError):
return []
images_list = []
for image in images:
if len(image.tags) > 0:
images_list.append(image.tags[0])
images_list.sort()
return images_list
@run_command
def kill_container(self, container_id: str):
"""
Kill a running container.
Args:
container_id (str): The ID of the container to kill.
"""
try:
self.client.containers.get(container_id).kill()
except docker.errors.NotFound:
pass
def is_connected(self) -> bool:
"""
Check if the Docker client is connected.
Returns:
bool: True if connected, False otherwise.
"""
try:
self.client.ping()
except:
return False
return True