main.py 9.3 KB

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