blob: f9f02b63f4e30609972cb12a258c9a9190e5f2f9 [file] [log] [blame]
Matthias Andreas Benkardd1f5b682023-11-18 13:18:30 +01001import os
2import sys
3import uvicorn
4import json
5import uuid
6import async_timeout
7import asyncio
8import aioredis
9import aiodocker
10import docker
11import logging
12from logging.config import dictConfig
13from fastapi import FastAPI, Response, Request
14from modules.DockerApi import DockerApi
15
16dockerapi = None
17app = FastAPI()
18
19# Define Routes
20@app.get("/host/stats")
21async def get_host_update_stats():
22 global dockerapi
23
24 if dockerapi.host_stats_isUpdating == False:
25 asyncio.create_task(dockerapi.get_host_stats())
26 dockerapi.host_stats_isUpdating = True
27
28 while True:
29 if await dockerapi.redis_client.exists('host_stats'):
30 break
31 await asyncio.sleep(1.5)
32
33 stats = json.loads(await dockerapi.redis_client.get('host_stats'))
34 return Response(content=json.dumps(stats, indent=4), media_type="application/json")
35
36@app.get("/containers/{container_id}/json")
37async def get_container(container_id : str):
38 global dockerapi
39
40 if container_id and container_id.isalnum():
41 try:
42 for container in (await dockerapi.async_docker_client.containers.list()):
43 if container._id == container_id:
44 container_info = await container.show()
45 return Response(content=json.dumps(container_info, indent=4), media_type="application/json")
46
47 res = {
48 "type": "danger",
49 "msg": "no container found"
50 }
51 return Response(content=json.dumps(res, indent=4), media_type="application/json")
52 except Exception as e:
53 res = {
54 "type": "danger",
55 "msg": str(e)
56 }
57 return Response(content=json.dumps(res, indent=4), media_type="application/json")
58 else:
59 res = {
60 "type": "danger",
61 "msg": "no or invalid id defined"
62 }
63 return Response(content=json.dumps(res, indent=4), media_type="application/json")
64
65@app.get("/containers/json")
66async def get_containers():
67 global dockerapi
68
69 containers = {}
70 try:
71 for container in (await dockerapi.async_docker_client.containers.list()):
72 container_info = await container.show()
73 containers.update({container_info['Id']: container_info})
74 return Response(content=json.dumps(containers, indent=4), media_type="application/json")
75 except Exception as e:
76 res = {
77 "type": "danger",
78 "msg": str(e)
79 }
80 return Response(content=json.dumps(res, indent=4), media_type="application/json")
81
82@app.post("/containers/{container_id}/{post_action}")
83async def post_containers(container_id : str, post_action : str, request: Request):
84 global dockerapi
85
86 try :
87 request_json = await request.json()
88 except Exception as err:
89 request_json = {}
90
91 if container_id and container_id.isalnum() and post_action:
92 try:
93 """Dispatch container_post api call"""
94 if post_action == 'exec':
95 if not request_json or not 'cmd' in request_json:
96 res = {
97 "type": "danger",
98 "msg": "cmd is missing"
99 }
100 return Response(content=json.dumps(res, indent=4), media_type="application/json")
101 if not request_json or not 'task' in request_json:
102 res = {
103 "type": "danger",
104 "msg": "task is missing"
105 }
106 return Response(content=json.dumps(res, indent=4), media_type="application/json")
107
108 api_call_method_name = '__'.join(['container_post', str(post_action), str(request_json['cmd']), str(request_json['task']) ])
109 else:
110 api_call_method_name = '__'.join(['container_post', str(post_action) ])
111
112 api_call_method = getattr(dockerapi, api_call_method_name, lambda container_id: Response(content=json.dumps({'type': 'danger', 'msg':'container_post - unknown api call' }, indent=4), media_type="application/json"))
113
114 dockerapi.logger.info("api call: %s, container_id: %s" % (api_call_method_name, container_id))
115 return api_call_method(request_json, container_id=container_id)
116 except Exception as e:
117 dockerapi.logger.error("error - container_post: %s" % str(e))
118 res = {
119 "type": "danger",
120 "msg": str(e)
121 }
122 return Response(content=json.dumps(res, indent=4), media_type="application/json")
123
124 else:
125 res = {
126 "type": "danger",
127 "msg": "invalid container id or missing action"
128 }
129 return Response(content=json.dumps(res, indent=4), media_type="application/json")
130
131@app.post("/container/{container_id}/stats/update")
132async def post_container_update_stats(container_id : str):
133 global dockerapi
134
135 # start update task for container if no task is running
136 if container_id not in dockerapi.containerIds_to_update:
137 asyncio.create_task(dockerapi.get_container_stats(container_id))
138 dockerapi.containerIds_to_update.append(container_id)
139
140 while True:
141 if await dockerapi.redis_client.exists(container_id + '_stats'):
142 break
143 await asyncio.sleep(1.5)
144
145 stats = json.loads(await dockerapi.redis_client.get(container_id + '_stats'))
146 return Response(content=json.dumps(stats, indent=4), media_type="application/json")
147
148# Events
149@app.on_event("startup")
150async def startup_event():
151 global dockerapi
152
153 # Initialize a custom logger
154 logger = logging.getLogger("dockerapi")
155 logger.setLevel(logging.INFO)
156 # Configure the logger to output logs to the terminal
157 handler = logging.StreamHandler()
158 handler.setLevel(logging.INFO)
159 formatter = logging.Formatter("%(levelname)s: %(message)s")
160 handler.setFormatter(formatter)
161 logger.addHandler(handler)
162
163 logger.info("Init APP")
164
165 # Init redis client
166 if os.environ['REDIS_SLAVEOF_IP'] != "":
167 redis_client = redis = await aioredis.from_url(f"redis://{os.environ['REDIS_SLAVEOF_IP']}:{os.environ['REDIS_SLAVEOF_PORT']}/0")
168 else:
169 redis_client = redis = await aioredis.from_url("redis://redis-mailcow:6379/0")
170
171 # Init docker clients
172 sync_docker_client = docker.DockerClient(base_url='unix://var/run/docker.sock', version='auto')
173 async_docker_client = aiodocker.Docker(url='unix:///var/run/docker.sock')
174
175 dockerapi = DockerApi(redis_client, sync_docker_client, async_docker_client, logger)
176
177 logger.info("Subscribe to redis channel")
178 # Subscribe to redis channel
179 dockerapi.pubsub = redis.pubsub()
180 await dockerapi.pubsub.subscribe("MC_CHANNEL")
181 asyncio.create_task(handle_pubsub_messages(dockerapi.pubsub))
182
183@app.on_event("shutdown")
184async def shutdown_event():
185 global dockerapi
186
187 # Close docker connections
188 dockerapi.sync_docker_client.close()
189 await dockerapi.async_docker_client.close()
190
191 # Close redis
192 await dockerapi.pubsub.unsubscribe("MC_CHANNEL")
193 await dockerapi.redis_client.close()
194
195# PubSub Handler
196async def handle_pubsub_messages(channel: aioredis.client.PubSub):
197 global dockerapi
198
199 while True:
200 try:
201 async with async_timeout.timeout(60):
202 message = await channel.get_message(ignore_subscribe_messages=True, timeout=30)
203 if message is not None:
204 # Parse message
205 data_json = json.loads(message['data'].decode('utf-8'))
206 dockerapi.logger.info(f"PubSub Received - {json.dumps(data_json)}")
207
208 # Handle api_call
209 if 'api_call' in data_json:
210 # api_call: container_post
211 if data_json['api_call'] == "container_post":
212 if 'post_action' in data_json and 'container_name' in data_json:
213 try:
214 """Dispatch container_post api call"""
215 request_json = {}
216 if data_json['post_action'] == 'exec':
217 if 'request' in data_json:
218 request_json = data_json['request']
219 if 'cmd' in request_json:
220 if 'task' in request_json:
221 api_call_method_name = '__'.join(['container_post', str(data_json['post_action']), str(request_json['cmd']), str(request_json['task']) ])
222 else:
223 dockerapi.logger.error("api call: task missing")
224 else:
225 dockerapi.logger.error("api call: cmd missing")
226 else:
227 dockerapi.logger.error("api call: request missing")
228 else:
229 api_call_method_name = '__'.join(['container_post', str(data_json['post_action'])])
230
231 if api_call_method_name:
232 api_call_method = getattr(dockerapi, api_call_method_name)
233 if api_call_method:
234 dockerapi.logger.info("api call: %s, container_name: %s" % (api_call_method_name, data_json['container_name']))
235 api_call_method(request_json, container_name=data_json['container_name'])
236 else:
237 dockerapi.logger.error("api call not found: %s, container_name: %s" % (api_call_method_name, data_json['container_name']))
238 except Exception as e:
239 dockerapi.logger.error("container_post: %s" % str(e))
240 else:
241 dockerapi.logger.error("api call: missing container_name, post_action or request")
242 else:
243 dockerapi.logger.error("Unknwon PubSub recieved - %s" % json.dumps(data_json))
244 else:
245 dockerapi.logger.error("Unknwon PubSub recieved - %s" % json.dumps(data_json))
246
247 await asyncio.sleep(0.0)
248 except asyncio.TimeoutError:
249 pass
250
251if __name__ == '__main__':
252 uvicorn.run(
253 app,
254 host="0.0.0.0",
255 port=443,
256 ssl_certfile="/app/dockerapi_cert.pem",
257 ssl_keyfile="/app/dockerapi_key.pem",
258 log_level="info",
259 loop="none"
260 )