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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
|
"""
Router for Docker routes
"""
import logging
from typing import Dict, List
from docker import DockerClient
from docker.errors import APIError, ImageNotFound, NotFound
from docker.models.containers import Container, Image
from docker.types.daemon import CancellableStream
from fastapi import APIRouter, HTTPException, status
from fastapi.params import Depends
from fastapi.responses import StreamingResponse
from serverctl_deployd.dependencies import get_docker_client
from serverctl_deployd.models.docker import (ContainerDetails, DeleteRequest,
ImageTagRequest, LogsResponse,
PruneRequest, PruneResponse)
from serverctl_deployd.models.exceptions import GenericError
router = APIRouter(
prefix="/docker",
tags=["docker"]
)
@router.get(
"/containers/{container_id}",
response_model=ContainerDetails,
responses={
status.HTTP_404_NOT_FOUND: {"model": GenericError},
status.HTTP_500_INTERNAL_SERVER_ERROR: {"model": GenericError}
}
)
async def get_container_details(
container_id: str,
docker_client: DockerClient = Depends(get_docker_client)
) -> ContainerDetails:
"""
Get container details
"""
try:
container: Container = docker_client.containers.get(container_id)
container_response: ContainerDetails = ContainerDetails(
id=container.id,
status=container.status,
image=container.image.tags,
name=container.name,
ports=container.ports,
created=container.attrs['Created'])
except NotFound as not_found_exception:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Container not found"
) from not_found_exception
except APIError as api_error_exception:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Internal server error"
) from api_error_exception
return container_response
@router.post(
"/containers/delete",
responses={
status.HTTP_404_NOT_FOUND: {"model": GenericError},
status.HTTP_403_FORBIDDEN: {"model": GenericError},
status.HTTP_500_INTERNAL_SERVER_ERROR: {"model": GenericError}
}
)
async def delete_container(
delete_request: DeleteRequest,
docker_client: DockerClient = Depends(get_docker_client)
) -> Dict[str, str]:
"""
Delete container
"""
container = Container()
try:
container = docker_client.containers.get(delete_request.container_id)
container.remove(force=delete_request.force, v=delete_request.v)
except NotFound as not_found_exception:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Container not found") from not_found_exception
except APIError as api_error_exception:
if container.status == "running":
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Cannot remove running containers, try forcing") from api_error_exception
logging.exception(
"Error deleting the container %s",
delete_request.container_id)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Internal server error"
) from api_error_exception
return {"message": f"Container {delete_request.container_id} deleted"}
@router.post(
"/containers/{container_id}/start",
responses={
status.HTTP_500_INTERNAL_SERVER_ERROR: {"model": GenericError}
}
)
async def start_container(
container_id: str,
docker_client: DockerClient = Depends(get_docker_client)
) -> Dict[str, str]:
"""
Start container
"""
try:
container: Container = docker_client.containers.get(container_id)
container.start()
except NotFound as not_found_exception:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Container not found") from not_found_exception
except APIError as api_error_exception:
logging.exception("Error starting the container %s", container_id)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Internal server error"
) from api_error_exception
return {"message": f"Container {container_id} started"}
@router.post(
"/containers/{container_id}/stop",
responses={
status.HTTP_404_NOT_FOUND: {"model": GenericError},
status.HTTP_500_INTERNAL_SERVER_ERROR: {"model": GenericError}
})
async def stop_container(
container_id: str,
docker_client: DockerClient = Depends(get_docker_client)
) -> Dict[str, str]:
"""
Stop container
"""
try:
container: Container = docker_client.containers.get(container_id)
container.stop()
except NotFound as not_found_exception:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Container not found") from not_found_exception
except APIError as api_error_exception:
logging.exception("Error stopping the container %s", container_id)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Internal server error"
) from api_error_exception
return {"message": f"Container {container_id} stopped"}
@router.post(
"/containers/{container_id}/restart",
responses={
status.HTTP_404_NOT_FOUND: {"model": GenericError},
status.HTTP_500_INTERNAL_SERVER_ERROR: {"model": GenericError}
})
async def restart_container(
container_id: str,
docker_client: DockerClient = Depends(get_docker_client)
) -> Dict[str, str]:
"""
Restart container
"""
try:
container: Container = docker_client.containers.get(container_id)
container.restart()
except NotFound as not_found_exception:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Container not found") from not_found_exception
except APIError as api_error_exception:
logging.exception("Error restarting the container %s", container_id)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Internal server error"
) from api_error_exception
return {"message": f"Container {container_id} restarted"}
@router.post(
"/containers/{container_id}/kill",
responses={
status.HTTP_404_NOT_FOUND: {"model": GenericError},
status.HTTP_403_FORBIDDEN: {"model": GenericError},
status.HTTP_500_INTERNAL_SERVER_ERROR: {"model": GenericError}
})
async def kill_container(
container_id: str,
docker_client: DockerClient = Depends(get_docker_client)
) -> Dict[str, str]:
"""
Kill container
"""
container = Container()
try:
container = docker_client.containers.get(container_id)
container.kill()
except NotFound as not_found_exception:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Container not found") from not_found_exception
except APIError as api_error_exception:
if container.status != "running":
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Cannot kill containers that are not running") from api_error_exception
logging.exception("Error killing the container %s", container_id)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Internal server error"
) from api_error_exception
return {"message": f"Container {container_id} killed"}
@router.get(
"/containers/{container_id}/logs",
response_model=LogsResponse,
responses={
status.HTTP_404_NOT_FOUND: {"model": GenericError},
status.HTTP_500_INTERNAL_SERVER_ERROR: {"model": GenericError}
})
async def get_logs(
container_id: str,
docker_client: DockerClient = Depends(get_docker_client)
) -> LogsResponse:
"""
Get logs
"""
try:
container: Container = docker_client.containers.get(container_id)
logs: str = container.logs()
except NotFound as not_found_exception:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Container not found") from not_found_exception
except APIError as api_error_exception:
logging.exception(
"Error getting the logs of the container %s",
container_id)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Internal server error"
) from api_error_exception
return LogsResponse(container_id=container_id, logs=logs)
@router.get("/containers",
response_model=List[ContainerDetails],
responses={
status.HTTP_500_INTERNAL_SERVER_ERROR: {"model": GenericError}
}
)
async def get_containers(
docker_client: DockerClient = Depends(get_docker_client)
) -> List[ContainerDetails]:
"""
Get all containers
"""
try:
containers: List[Container] = [ContainerDetails(
id=container.id,
status=container.status,
image=container.image.tags,
name=container.name,
ports=container.ports,
created=container.attrs['Created']
)
for container in docker_client.containers.list(all=True)]
except APIError as api_error_exception:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Internal server error"
) from api_error_exception
return containers
@router.post(
"/images/tag",
responses={
status.HTTP_404_NOT_FOUND: {"model": GenericError},
status.HTTP_500_INTERNAL_SERVER_ERROR: {"model": GenericError}
})
async def tag_image(
tag_image_request: ImageTagRequest,
docker_client: DockerClient = Depends(get_docker_client)
) -> Dict[str, str]:
"""
Tag image
"""
try:
image: Image = docker_client.images.get(tag_image_request.image_id)
image.tag(tag_image_request.tag, "latest")
except ImageNotFound as image_not_found_exception:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Image not found"
) from image_not_found_exception
except APIError as api_error_exception:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Internal server error"
) from api_error_exception
return {"message": f"Image {tag_image_request.image_id} tagged"}
@router.post(
"/prune",
response_model=PruneResponse,
responses={
status.HTTP_500_INTERNAL_SERVER_ERROR: {"model": GenericError}
}
)
async def prune(
prune_request: PruneRequest,
docker_client: DockerClient = Depends(get_docker_client)
) -> PruneResponse:
"""
Prune Docker images and containers
"""
try:
prune_response = PruneResponse()
if prune_request.containers or prune_request.all:
prune_response.containers = docker_client.containers.prune()
if prune_request.images or prune_request.all:
prune_response.images = docker_client.images.prune()
if prune_request.volumes or prune_request.all:
prune_response.volumes = docker_client.volumes.prune()
if prune_request.networks or prune_request.all:
prune_response.networks = docker_client.networks.prune()
if prune_request.build_cache or prune_request.all:
prune_response.build_cache = docker_client.api.prune_builds()
except APIError as api_error_exception:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Internal server error"
) from api_error_exception
return prune_response
@router.get(
"/containers/{container_id}/attach",
responses={
status.HTTP_404_NOT_FOUND: {"model": GenericError},
status.HTTP_500_INTERNAL_SERVER_ERROR: {"model": GenericError}
}
)
async def container_attach(
container_id: str,
docker_client: DockerClient = Depends(get_docker_client)
) -> StreamingResponse:
"""
Returns a HTTP Stream for the container's stdout and stderr
"""
try:
container: Container = docker_client.containers.get(container_id)
log_stream: CancellableStream = container.attach(stream=True)
except NotFound as not_found_exception:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Container not found"
) from not_found_exception
except APIError as api_error_exception:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Internal server error"
) from api_error_exception
return StreamingResponse(
log_stream,
media_type="text/plain"
)
|