blob: 3ca4560c6dd57a5a97a3914a4edc01042e70193d [file] [log] [blame]
Matthias Andreas Benkardd1f5b682023-11-18 13:18:30 +01001import psutil
2import sys
3import os
4import re
5import time
6import json
7import asyncio
8import platform
9from datetime import datetime
10from fastapi import FastAPI, Response, Request
11
12class DockerApi:
13 def __init__(self, redis_client, sync_docker_client, async_docker_client, logger):
14 self.redis_client = redis_client
15 self.sync_docker_client = sync_docker_client
16 self.async_docker_client = async_docker_client
17 self.logger = logger
18
19 self.host_stats_isUpdating = False
20 self.containerIds_to_update = []
21
22 # api call: container_post - post_action: stop
23 def container_post__stop(self, request_json, **kwargs):
24 if 'container_id' in kwargs:
25 filters = {"id": kwargs['container_id']}
26 elif 'container_name' in kwargs:
27 filters = {"name": kwargs['container_name']}
28
29 for container in self.sync_docker_client.containers.list(all=True, filters=filters):
30 container.stop()
31
32 res = { 'type': 'success', 'msg': 'command completed successfully'}
33 return Response(content=json.dumps(res, indent=4), media_type="application/json")
34 # api call: container_post - post_action: start
35 def container_post__start(self, request_json, **kwargs):
36 if 'container_id' in kwargs:
37 filters = {"id": kwargs['container_id']}
38 elif 'container_name' in kwargs:
39 filters = {"name": kwargs['container_name']}
40
41 for container in self.sync_docker_client.containers.list(all=True, filters=filters):
42 container.start()
43
44 res = { 'type': 'success', 'msg': 'command completed successfully'}
45 return Response(content=json.dumps(res, indent=4), media_type="application/json")
46 # api call: container_post - post_action: restart
47 def container_post__restart(self, request_json, **kwargs):
48 if 'container_id' in kwargs:
49 filters = {"id": kwargs['container_id']}
50 elif 'container_name' in kwargs:
51 filters = {"name": kwargs['container_name']}
52
53 for container in self.sync_docker_client.containers.list(all=True, filters=filters):
54 container.restart()
55
56 res = { 'type': 'success', 'msg': 'command completed successfully'}
57 return Response(content=json.dumps(res, indent=4), media_type="application/json")
58 # api call: container_post - post_action: top
59 def container_post__top(self, request_json, **kwargs):
60 if 'container_id' in kwargs:
61 filters = {"id": kwargs['container_id']}
62 elif 'container_name' in kwargs:
63 filters = {"name": kwargs['container_name']}
64
65 for container in self.sync_docker_client.containers.list(all=True, filters=filters):
66 res = { 'type': 'success', 'msg': container.top()}
67 return Response(content=json.dumps(res, indent=4), media_type="application/json")
68 # api call: container_post - post_action: stats
69 def container_post__stats(self, request_json, **kwargs):
70 if 'container_id' in kwargs:
71 filters = {"id": kwargs['container_id']}
72 elif 'container_name' in kwargs:
73 filters = {"name": kwargs['container_name']}
74
75 for container in self.sync_docker_client.containers.list(all=True, filters=filters):
76 for stat in container.stats(decode=True, stream=True):
77 res = { 'type': 'success', 'msg': stat}
78 return Response(content=json.dumps(res, indent=4), media_type="application/json")
79 # api call: container_post - post_action: exec - cmd: mailq - task: delete
80 def container_post__exec__mailq__delete(self, request_json, **kwargs):
81 if 'container_id' in kwargs:
82 filters = {"id": kwargs['container_id']}
83 elif 'container_name' in kwargs:
84 filters = {"name": kwargs['container_name']}
85
86 if 'items' in request_json:
87 r = re.compile("^[0-9a-fA-F]+$")
88 filtered_qids = filter(r.match, request_json['items'])
89 if filtered_qids:
90 flagged_qids = ['-d %s' % i for i in filtered_qids]
91 sanitized_string = str(' '.join(flagged_qids))
92 for container in self.sync_docker_client.containers.list(filters=filters):
93 postsuper_r = container.exec_run(["/bin/bash", "-c", "/usr/sbin/postsuper " + sanitized_string])
94 return self.exec_run_handler('generic', postsuper_r)
95 # api call: container_post - post_action: exec - cmd: mailq - task: hold
96 def container_post__exec__mailq__hold(self, request_json, **kwargs):
97 if 'container_id' in kwargs:
98 filters = {"id": kwargs['container_id']}
99 elif 'container_name' in kwargs:
100 filters = {"name": kwargs['container_name']}
101
102 if 'items' in request_json:
103 r = re.compile("^[0-9a-fA-F]+$")
104 filtered_qids = filter(r.match, request_json['items'])
105 if filtered_qids:
106 flagged_qids = ['-h %s' % i for i in filtered_qids]
107 sanitized_string = str(' '.join(flagged_qids))
108 for container in self.sync_docker_client.containers.list(filters=filters):
109 postsuper_r = container.exec_run(["/bin/bash", "-c", "/usr/sbin/postsuper " + sanitized_string])
110 return self.exec_run_handler('generic', postsuper_r)
111 # api call: container_post - post_action: exec - cmd: mailq - task: cat
112 def container_post__exec__mailq__cat(self, request_json, **kwargs):
113 if 'container_id' in kwargs:
114 filters = {"id": kwargs['container_id']}
115 elif 'container_name' in kwargs:
116 filters = {"name": kwargs['container_name']}
117
118 if 'items' in request_json:
119 r = re.compile("^[0-9a-fA-F]+$")
120 filtered_qids = filter(r.match, request_json['items'])
121 if filtered_qids:
122 sanitized_string = str(' '.join(filtered_qids))
123
124 for container in self.sync_docker_client.containers.list(filters=filters):
125 postcat_return = container.exec_run(["/bin/bash", "-c", "/usr/sbin/postcat -q " + sanitized_string], user='postfix')
126 if not postcat_return:
127 postcat_return = 'err: invalid'
128 return self.exec_run_handler('utf8_text_only', postcat_return)
129 # api call: container_post - post_action: exec - cmd: mailq - task: unhold
130 def container_post__exec__mailq__unhold(self, request_json, **kwargs):
131 if 'container_id' in kwargs:
132 filters = {"id": kwargs['container_id']}
133 elif 'container_name' in kwargs:
134 filters = {"name": kwargs['container_name']}
135
136 if 'items' in request_json:
137 r = re.compile("^[0-9a-fA-F]+$")
138 filtered_qids = filter(r.match, request_json['items'])
139 if filtered_qids:
140 flagged_qids = ['-H %s' % i for i in filtered_qids]
141 sanitized_string = str(' '.join(flagged_qids))
142 for container in self.sync_docker_client.containers.list(filters=filters):
143 postsuper_r = container.exec_run(["/bin/bash", "-c", "/usr/sbin/postsuper " + sanitized_string])
144 return self.exec_run_handler('generic', postsuper_r)
145 # api call: container_post - post_action: exec - cmd: mailq - task: deliver
146 def container_post__exec__mailq__deliver(self, request_json, **kwargs):
147 if 'container_id' in kwargs:
148 filters = {"id": kwargs['container_id']}
149 elif 'container_name' in kwargs:
150 filters = {"name": kwargs['container_name']}
151
152 if 'items' in request_json:
153 r = re.compile("^[0-9a-fA-F]+$")
154 filtered_qids = filter(r.match, request_json['items'])
155 if filtered_qids:
156 flagged_qids = ['-i %s' % i for i in filtered_qids]
157 for container in self.sync_docker_client.containers.list(filters=filters):
158 for i in flagged_qids:
159 postqueue_r = container.exec_run(["/bin/bash", "-c", "/usr/sbin/postqueue " + i], user='postfix')
160 # todo: check each exit code
161 res = { 'type': 'success', 'msg': 'Scheduled immediate delivery'}
Matthias Andreas Benkarda515bc62023-11-18 16:44:25 +0100162 return Response(content=json.dumps(res, indent=4), media_type="application/json")
Matthias Andreas Benkardd1f5b682023-11-18 13:18:30 +0100163 # api call: container_post - post_action: exec - cmd: mailq - task: list
164 def container_post__exec__mailq__list(self, request_json, **kwargs):
165 if 'container_id' in kwargs:
166 filters = {"id": kwargs['container_id']}
167 elif 'container_name' in kwargs:
168 filters = {"name": kwargs['container_name']}
169
170 for container in self.sync_docker_client.containers.list(filters=filters):
171 mailq_return = container.exec_run(["/usr/sbin/postqueue", "-j"], user='postfix')
172 return self.exec_run_handler('utf8_text_only', mailq_return)
173 # api call: container_post - post_action: exec - cmd: mailq - task: flush
174 def container_post__exec__mailq__flush(self, request_json, **kwargs):
175 if 'container_id' in kwargs:
176 filters = {"id": kwargs['container_id']}
177 elif 'container_name' in kwargs:
178 filters = {"name": kwargs['container_name']}
179
180 for container in self.sync_docker_client.containers.list(filters=filters):
181 postqueue_r = container.exec_run(["/usr/sbin/postqueue", "-f"], user='postfix')
182 return self.exec_run_handler('generic', postqueue_r)
183 # api call: container_post - post_action: exec - cmd: mailq - task: super_delete
184 def container_post__exec__mailq__super_delete(self, request_json, **kwargs):
185 if 'container_id' in kwargs:
186 filters = {"id": kwargs['container_id']}
187 elif 'container_name' in kwargs:
188 filters = {"name": kwargs['container_name']}
189
190 for container in self.sync_docker_client.containers.list(filters=filters):
191 postsuper_r = container.exec_run(["/usr/sbin/postsuper", "-d", "ALL"])
192 return self.exec_run_handler('generic', postsuper_r)
193 # api call: container_post - post_action: exec - cmd: system - task: fts_rescan
194 def container_post__exec__system__fts_rescan(self, request_json, **kwargs):
195 if 'container_id' in kwargs:
196 filters = {"id": kwargs['container_id']}
197 elif 'container_name' in kwargs:
198 filters = {"name": kwargs['container_name']}
199
200 if 'username' in request_json:
201 for container in self.sync_docker_client.containers.list(filters=filters):
202 rescan_return = container.exec_run(["/bin/bash", "-c", "/usr/bin/doveadm fts rescan -u '" + request_json['username'].replace("'", "'\\''") + "'"], user='vmail')
203 if rescan_return.exit_code == 0:
204 res = { 'type': 'success', 'msg': 'fts_rescan: rescan triggered'}
205 return Response(content=json.dumps(res, indent=4), media_type="application/json")
206 else:
207 res = { 'type': 'warning', 'msg': 'fts_rescan error'}
208 return Response(content=json.dumps(res, indent=4), media_type="application/json")
209 if 'all' in request_json:
210 for container in self.sync_docker_client.containers.list(filters=filters):
211 rescan_return = container.exec_run(["/bin/bash", "-c", "/usr/bin/doveadm fts rescan -A"], user='vmail')
212 if rescan_return.exit_code == 0:
213 res = { 'type': 'success', 'msg': 'fts_rescan: rescan triggered'}
214 return Response(content=json.dumps(res, indent=4), media_type="application/json")
215 else:
216 res = { 'type': 'warning', 'msg': 'fts_rescan error'}
217 return Response(content=json.dumps(res, indent=4), media_type="application/json")
218 # api call: container_post - post_action: exec - cmd: system - task: df
219 def container_post__exec__system__df(self, request_json, **kwargs):
220 if 'container_id' in kwargs:
221 filters = {"id": kwargs['container_id']}
222 elif 'container_name' in kwargs:
223 filters = {"name": kwargs['container_name']}
224
225 if 'dir' in request_json:
226 for container in self.sync_docker_client.containers.list(filters=filters):
227 df_return = container.exec_run(["/bin/bash", "-c", "/bin/df -H '" + request_json['dir'].replace("'", "'\\''") + "' | /usr/bin/tail -n1 | /usr/bin/tr -s [:blank:] | /usr/bin/tr ' ' ','"], user='nobody')
228 if df_return.exit_code == 0:
229 return df_return.output.decode('utf-8').rstrip()
230 else:
231 return "0,0,0,0,0,0"
232 # api call: container_post - post_action: exec - cmd: system - task: mysql_upgrade
233 def container_post__exec__system__mysql_upgrade(self, request_json, **kwargs):
Matthias Andreas Benkarda515bc62023-11-18 16:44:25 +0100234 return Response(content=json.dumps(dict(type='success', msg='mysql_upgrade: not touching fake MySQL', text=''), indent=4), media_type="application/json")
Matthias Andreas Benkardd1f5b682023-11-18 13:18:30 +0100235 # api call: container_post - post_action: exec - cmd: system - task: mysql_tzinfo_to_sql
236 def container_post__exec__system__mysql_tzinfo_to_sql(self, request_json, **kwargs):
Matthias Andreas Benkarda515bc62023-11-18 16:44:25 +0100237 return Response(content=json.dumps(dict(type='success', msg='mysql_tzinfo_to_sql: not touching fake MySQL', text=''), indent=4), media_type="application/json")
Matthias Andreas Benkardd1f5b682023-11-18 13:18:30 +0100238 # api call: container_post - post_action: exec - cmd: reload - task: dovecot
239 def container_post__exec__reload__dovecot(self, request_json, **kwargs):
240 if 'container_id' in kwargs:
241 filters = {"id": kwargs['container_id']}
242 elif 'container_name' in kwargs:
243 filters = {"name": kwargs['container_name']}
244
245 for container in self.sync_docker_client.containers.list(filters=filters):
246 reload_return = container.exec_run(["/bin/bash", "-c", "/usr/sbin/dovecot reload"])
247 return self.exec_run_handler('generic', reload_return)
248 # api call: container_post - post_action: exec - cmd: reload - task: postfix
249 def container_post__exec__reload__postfix(self, request_json, **kwargs):
250 if 'container_id' in kwargs:
251 filters = {"id": kwargs['container_id']}
252 elif 'container_name' in kwargs:
253 filters = {"name": kwargs['container_name']}
254
255 for container in self.sync_docker_client.containers.list(filters=filters):
256 reload_return = container.exec_run(["/bin/bash", "-c", "/usr/sbin/postfix reload"])
257 return self.exec_run_handler('generic', reload_return)
258 # api call: container_post - post_action: exec - cmd: reload - task: nginx
259 def container_post__exec__reload__nginx(self, request_json, **kwargs):
260 if 'container_id' in kwargs:
261 filters = {"id": kwargs['container_id']}
262 elif 'container_name' in kwargs:
263 filters = {"name": kwargs['container_name']}
264
265 for container in self.sync_docker_client.containers.list(filters=filters):
266 reload_return = container.exec_run(["/bin/sh", "-c", "/usr/sbin/nginx -s reload"])
267 return self.exec_run_handler('generic', reload_return)
268 # api call: container_post - post_action: exec - cmd: sieve - task: list
269 def container_post__exec__sieve__list(self, request_json, **kwargs):
270 if 'container_id' in kwargs:
271 filters = {"id": kwargs['container_id']}
272 elif 'container_name' in kwargs:
273 filters = {"name": kwargs['container_name']}
274
275 if 'username' in request_json:
276 for container in self.sync_docker_client.containers.list(filters=filters):
277 sieve_return = container.exec_run(["/bin/bash", "-c", "/usr/bin/doveadm sieve list -u '" + request_json['username'].replace("'", "'\\''") + "'"])
278 return self.exec_run_handler('utf8_text_only', sieve_return)
279 # api call: container_post - post_action: exec - cmd: sieve - task: print
280 def container_post__exec__sieve__print(self, request_json, **kwargs):
281 if 'container_id' in kwargs:
282 filters = {"id": kwargs['container_id']}
283 elif 'container_name' in kwargs:
284 filters = {"name": kwargs['container_name']}
285
286 if 'username' in request_json and 'script_name' in request_json:
287 for container in self.sync_docker_client.containers.list(filters=filters):
Matthias Andreas Benkarda515bc62023-11-18 16:44:25 +0100288 cmd = ["/bin/bash", "-c", "/usr/bin/doveadm sieve get -u '" + request_json['username'].replace("'", "'\\''") + "' '" + request_json['script_name'].replace("'", "'\\''") + "'"]
Matthias Andreas Benkardd1f5b682023-11-18 13:18:30 +0100289 sieve_return = container.exec_run(cmd)
290 return self.exec_run_handler('utf8_text_only', sieve_return)
291 # api call: container_post - post_action: exec - cmd: maildir - task: cleanup
292 def container_post__exec__maildir__cleanup(self, request_json, **kwargs):
293 if 'container_id' in kwargs:
294 filters = {"id": kwargs['container_id']}
295 elif 'container_name' in kwargs:
296 filters = {"name": kwargs['container_name']}
297
298 if 'maildir' in request_json:
299 for container in self.sync_docker_client.containers.list(filters=filters):
300 sane_name = re.sub(r'\W+', '', request_json['maildir'])
301 vmail_name = request_json['maildir'].replace("'", "'\\''")
302 cmd_vmail = "if [[ -d '/var/vmail/" + vmail_name + "' ]]; then /bin/mv '/var/vmail/" + vmail_name + "' '/var/vmail/_garbage/" + str(int(time.time())) + "_" + sane_name + "'; fi"
303 index_name = request_json['maildir'].split("/")
304 if len(index_name) > 1:
305 index_name = index_name[1].replace("'", "'\\''") + "@" + index_name[0].replace("'", "'\\''")
306 cmd_vmail_index = "if [[ -d '/var/vmail_index/" + index_name + "' ]]; then /bin/mv '/var/vmail_index/" + index_name + "' '/var/vmail/_garbage/" + str(int(time.time())) + "_" + sane_name + "_index'; fi"
307 cmd = ["/bin/bash", "-c", cmd_vmail + " && " + cmd_vmail_index]
308 else:
309 cmd = ["/bin/bash", "-c", cmd_vmail]
310 maildir_cleanup = container.exec_run(cmd, user='vmail')
311 return self.exec_run_handler('generic', maildir_cleanup)
312 # api call: container_post - post_action: exec - cmd: rspamd - task: worker_password
313 def container_post__exec__rspamd__worker_password(self, request_json, **kwargs):
314 if 'container_id' in kwargs:
315 filters = {"id": kwargs['container_id']}
316 elif 'container_name' in kwargs:
317 filters = {"name": kwargs['container_name']}
318
319 if 'raw' in request_json:
320 for container in self.sync_docker_client.containers.list(filters=filters):
321 cmd = "/usr/bin/rspamadm pw -e -p '" + request_json['raw'].replace("'", "'\\''") + "' 2> /dev/null"
322 cmd_response = self.exec_cmd_container(container, cmd, user="_rspamd")
323
324 matched = False
325 for line in cmd_response.split("\n"):
326 if '$2$' in line:
327 hash = line.strip()
328 hash_out = re.search('\$2\$.+$', hash).group(0)
329 rspamd_passphrase_hash = re.sub('[^0-9a-zA-Z\$]+', '', hash_out.rstrip())
330 rspamd_password_filename = "/etc/rspamd/override.d/worker-controller-password.inc"
331 cmd = '''/bin/echo 'enable_password = "%s";' > %s && cat %s''' % (rspamd_passphrase_hash, rspamd_password_filename, rspamd_password_filename)
332 cmd_response = self.exec_cmd_container(container, cmd, user="_rspamd")
333 if rspamd_passphrase_hash.startswith("$2$") and rspamd_passphrase_hash in cmd_response:
334 container.restart()
335 matched = True
336 if matched:
337 res = { 'type': 'success', 'msg': 'command completed successfully' }
338 self.logger.info('success changing Rspamd password')
339 return Response(content=json.dumps(res, indent=4), media_type="application/json")
340 else:
341 self.logger.error('failed changing Rspamd password')
342 res = { 'type': 'danger', 'msg': 'command did not complete' }
343 return Response(content=json.dumps(res, indent=4), media_type="application/json")
344
345 # Collect host stats
346 async def get_host_stats(self, wait=5):
347 try:
348 system_time = datetime.now()
349 host_stats = {
350 "cpu": {
351 "cores": psutil.cpu_count(),
352 "usage": psutil.cpu_percent()
353 },
354 "memory": {
355 "total": psutil.virtual_memory().total,
356 "usage": psutil.virtual_memory().percent,
357 "swap": psutil.swap_memory()
358 },
359 "uptime": time.time() - psutil.boot_time(),
360 "system_time": system_time.strftime("%d.%m.%Y %H:%M:%S"),
361 "architecture": platform.machine()
362 }
363
364 await self.redis_client.set('host_stats', json.dumps(host_stats), ex=10)
365 except Exception as e:
366 res = {
367 "type": "danger",
368 "msg": str(e)
369 }
370
371 await asyncio.sleep(wait)
372 self.host_stats_isUpdating = False
373 # Collect container stats
374 async def get_container_stats(self, container_id, wait=5, stop=False):
375 if container_id and container_id.isalnum():
376 try:
377 for container in (await self.async_docker_client.containers.list()):
378 if container._id == container_id:
379 res = await container.stats(stream=False)
380
381 if await self.redis_client.exists(container_id + '_stats'):
382 stats = json.loads(await self.redis_client.get(container_id + '_stats'))
383 else:
384 stats = []
385 stats.append(res[0])
386 if len(stats) > 3:
387 del stats[0]
388 await self.redis_client.set(container_id + '_stats', json.dumps(stats), ex=60)
389 except Exception as e:
390 res = {
391 "type": "danger",
392 "msg": str(e)
393 }
394 else:
395 res = {
396 "type": "danger",
397 "msg": "no or invalid id defined"
398 }
399
400 await asyncio.sleep(wait)
401 if stop == True:
402 # update task was called second time, stop
403 self.containerIds_to_update.remove(container_id)
404 else:
405 # call update task a second time
406 await self.get_container_stats(container_id, wait=0, stop=True)
407
408 def exec_cmd_container(self, container, cmd, user, timeout=2, shell_cmd="/bin/bash"):
409 def recv_socket_data(c_socket, timeout):
410 c_socket.setblocking(0)
411 total_data=[]
412 data=''
413 begin=time.time()
414 while True:
415 if total_data and time.time()-begin > timeout:
416 break
417 elif time.time()-begin > timeout*2:
418 break
419 try:
420 data = c_socket.recv(8192)
421 if data:
422 total_data.append(data.decode('utf-8'))
423 #change the beginning time for measurement
424 begin=time.time()
425 else:
426 #sleep for sometime to indicate a gap
427 time.sleep(0.1)
428 break
429 except:
430 pass
431 return ''.join(total_data)
Matthias Andreas Benkarda515bc62023-11-18 16:44:25 +0100432
Matthias Andreas Benkardd1f5b682023-11-18 13:18:30 +0100433 try :
434 socket = container.exec_run([shell_cmd], stdin=True, socket=True, user=user).output._sock
435 if not cmd.endswith("\n"):
436 cmd = cmd + "\n"
437 socket.send(cmd.encode('utf-8'))
438 data = recv_socket_data(socket, timeout)
439 socket.close()
440 return data
441 except Exception as e:
442 self.logger.error("error - exec_cmd_container: %s" % str(e))
443 traceback.print_exc(file=sys.stdout)
444
445 def exec_run_handler(self, type, output):
446 if type == 'generic':
447 if output.exit_code == 0:
448 res = { 'type': 'success', 'msg': 'command completed successfully' }
449 return Response(content=json.dumps(res, indent=4), media_type="application/json")
450 else:
451 res = { 'type': 'danger', 'msg': 'command failed: ' + output.output.decode('utf-8') }
452 return Response(content=json.dumps(res, indent=4), media_type="application/json")
453 if type == 'utf8_text_only':
454 return Response(content=output.output.decode('utf-8'), media_type="text/plain")