manage.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. import os
  2. import io
  3. import sys
  4. import platform
  5. import shutil
  6. import time
  7. import subprocess
  8. import json
  9. import datetime
  10. import socket
  11. import re
  12. from threading import Thread
  13. from api.utils import shell_execute, docker, const
  14. from api.model.app import App
  15. from api.model.response import Response
  16. from api.model.running_info import RunningInfo
  17. from api.model.status_reason import StatusReason
  18. from api.utils.common_log import myLogger
  19. from redis import Redis
  20. from rq import Queue, Worker, Connection
  21. from rq.registry import StartedJobRegistry, FinishedJobRegistry, DeferredJobRegistry, FailedJobRegistry, \
  22. ScheduledJobRegistry, CanceledJobRegistry
  23. from api.exception.command_exception import CommandException
  24. # 指定 Redis 容器的主机名和端口
  25. redis_conn = Redis(host='websoft9-redis', port=6379)
  26. # 使用指定的 Redis 连接创建 RQ 队列
  27. q = Queue(connection=redis_conn)
  28. # 获取所有app的信息
  29. def get_my_app():
  30. # get all info
  31. cmd = "docker compose ls -a --format json"
  32. output = shell_execute.execute_command_output_all(cmd)
  33. output_list = json.loads(output["result"])
  34. installed_list, has_add = get_apps_from_compose(output_list)
  35. installing_list = get_apps_from_queue()
  36. app_list = installed_list + installing_list
  37. return app_list
  38. # 获取具体某个app的信息
  39. def get_app_status(app_id):
  40. code, message = docker.check_app_id(app_id)
  41. if code == None:
  42. app_list = get_my_app()
  43. # 将app_list 过滤出app_id的app,并缩减信息,使其符合文档的要求
  44. else:
  45. raise CommandException(code, message, "")
  46. def install_app(app_name, customer_name, app_version):
  47. myLogger.info_logger("Install app ...")
  48. ret = {}
  49. ret['ResponseData'] = {}
  50. app_id = app_name + "_" + customer_name
  51. ret['ResponseData']['app_id'] = app_id
  52. code, message = check_app(app_name, customer_name, app_version)
  53. if code == None:
  54. q.enqueue(install_app_delay, app_name, customer_name, app_version, job_id=app_id, timeout=3600)
  55. else:
  56. ret['Error'] = get_error_info(code, message, "")
  57. return ret
  58. def start_app(app_id):
  59. ret = Response(code=const.RETURN_FAIL, message="")
  60. if docker.check_app_id(app_id):
  61. app_name = split_app_id(app_id)
  62. info, code = if_app_exits(app_id)
  63. if code:
  64. app_path = info.split()[-1].rsplit('/', 1)[0]
  65. docker.check_app_compose(app_path + '/.env')
  66. cmd = "docker compose -f " + app_path + "/docker-compose.yml start"
  67. output = shell_execute.execute_command_output_all(cmd)
  68. if int(output["code"]) == 0:
  69. ret.code = const.RETURN_SUCCESS
  70. ret.message = "The app starts successfully."
  71. else:
  72. ret.message = "The app failed to start!"
  73. else:
  74. ret.message = "This app is not currently installed."
  75. else:
  76. ret.message = "AppID is not legal!"
  77. ret = ret.dict()
  78. return ret
  79. def stop_app(app_id):
  80. ret = Response(code=const.RETURN_FAIL, message="")
  81. if docker.check_app_id(app_id):
  82. app_name = split_app_id(app_id)
  83. info, code = if_app_exits(app_id)
  84. if code:
  85. app_path = info.split()[-1].rsplit('/', 1)[0]
  86. cmd = "docker compose -f " + app_path + "/docker-compose.yml stop"
  87. output = shell_execute.execute_command_output_all(cmd)
  88. if int(output["code"]) == 0:
  89. ret.code = const.RETURN_SUCCESS
  90. ret.message = "The app stopped successfully."
  91. else:
  92. ret.message = "App stop failed!"
  93. else:
  94. ret.message = "This app is not currently installed."
  95. else:
  96. ret.message = 'AppID is not legal!'
  97. ret = ret.dict()
  98. return ret
  99. def restart_app(app_id):
  100. ret = Response(code=const.RETURN_FAIL, message="")
  101. if docker.check_app_id(app_id):
  102. app_name = split_app_id(app_id)
  103. info, code = if_app_exits(app_id)
  104. if code:
  105. app_path = info.split()[-1].rsplit('/', 1)[0]
  106. cmd = "docker compose -f " + app_path + "/docker-compose.yml restart"
  107. output = shell_execute.execute_command_output_all(cmd)
  108. if int(output["code"]) == 0:
  109. ret.code = const.RETURN_SUCCESS
  110. ret.message = "The app restarts successfully."
  111. else:
  112. ret.message = "App restart failed!"
  113. else:
  114. ret.message = "This app is not currently installed."
  115. else:
  116. ret.message = 'AppID is not legal!'
  117. ret = ret.dict()
  118. return ret
  119. def delete_app_failedjob(app_id):
  120. myLogger.info_logger("delete_app_failedjob")
  121. def uninstall_app(app_id):
  122. ret = {}
  123. ret['ResponseData'] = {}
  124. ret['ResponseData']['app_id'] = app_id
  125. code, message = docker.check_app_id(app_id)
  126. if code == None:
  127. app_name = split_app_id(app_id)
  128. info, code_exist = if_app_exits(app_id)
  129. if code_exist:
  130. app_path = info.split()[-1].rsplit('/', 1)[0]
  131. cmd = "docker compose -f " + app_path + "/docker-compose.yml down -v"
  132. lib_path = '/data/library/apps/' + app_name
  133. if app_path != lib_path:
  134. cmd = cmd + " && sudo rm -rf " + app_path
  135. shell_execute.execute_command_output_all(cmd)
  136. else:
  137. delete_app_failedjob(app_id)
  138. else:
  139. ret['Error'] = get_error_info(code, message, "")
  140. return ret
  141. def check_app(app_name, customer_name, app_version):
  142. message = ""
  143. code = None
  144. app_id = app_name + "-" + customer_name
  145. if app_name == None:
  146. code = const.ERROR_CLIENT_PARAM_BLANK
  147. message = "app_name is null"
  148. elif customer_name == None:
  149. code = const.ERROR_CLIENT_PARAM_BLANK
  150. message = "customer_name is null"
  151. elif app_version == None:
  152. code = const.ERROR_CLIENT_PARAM_BLANK
  153. message = "app_version is null"
  154. elif not docker.check_app_websoft9(app_name):
  155. code = const.ERROR_CLIENT_PARAM_NOTEXIST
  156. message = "It is not support to install " + app_name
  157. elif re.match('^[a-z0-9]+$', customer_name) == None:
  158. code = const.ERROR_CLIENT_PARAM_Format
  159. message = "APP name can only be composed of numbers and lowercase letters"
  160. elif docker.check_directory("/data/apps/" + customer_name):
  161. code = const.ERROR_CLIENT_PARAM_REPEAT
  162. message = "Repeat installation: " + customer_name
  163. elif not docker.check_vm_resource(app_name):
  164. code = const.ERROR_SERVER_RESOURCE
  165. message = "Insufficient system resources (cpu, memory, disk space)"
  166. elif check_app_rq(app_id):
  167. code = const.ERROR_CLIENT_PARAM_REPEAT
  168. message = "Repeat installation: " + customer_name
  169. return code, message
  170. def prepare_app(app_name, customer_name):
  171. library_path = "/data/library/apps/" + app_name
  172. install_path = "/data/apps/" + customer_name
  173. shell_execute.execute_command_output_all("cp -r " + library_path + " " + install_path)
  174. def install_app_delay(app_name, customer_name, app_version):
  175. job_id = app_name + "_" + customer_name
  176. try:
  177. code, message = check_app(app_name, customer_name, app_version)
  178. if code == None:
  179. prepare_app(app_name, customer_name)
  180. myLogger.info_logger("start JobID=" + job_id)
  181. # modify env
  182. env_path = "/data/apps/" + customer_name + "/.env"
  183. docker.modify_env(env_path, 'APP_NAME', customer_name)
  184. docker.modify_env(env_path, "APP_VERSION", app_version)
  185. # check port
  186. docker.check_app_compose(env_path)
  187. cmd = "cd /data/apps/" + customer_name + " && sudo docker compose pull && sudo docker compose up -d"
  188. output = shell_execute.execute_command_output_all(cmd)
  189. myLogger.info_logger("-------Install result--------")
  190. myLogger.info_logger(output["code"])
  191. myLogger.info_logger(output["result"])
  192. else:
  193. raise CommandException(code, message, "")
  194. except CommandException as ce:
  195. uninstall_app(job_id)
  196. raise CommandException(ce.code, ce.message, ce.detail)
  197. except Exception as e:
  198. myLogger.info_logger(customer_name + "install failed!")
  199. myLogger.error_logger(e)
  200. uninstall_app(job_id)
  201. raise CommandException(const.ERROR_SERVER_SYSTEM, "system original error", str(e))
  202. def app_exits_in_docker(app_id):
  203. customer_name = app_id.split('_')[1]
  204. app_name = app_id.split('_')[0]
  205. flag = False
  206. info = ""
  207. cmd = "docker compose ls -a | grep \'/" + app_name + "/\'"
  208. output = shell_execute.execute_command_output_all(cmd)
  209. if int(output["code"]) == 0:
  210. info = output["result"]
  211. app_path = info.split()[-1].rsplit('/', 1)[0]
  212. is_official = check_if_official_app(app_path + '/variables.json')
  213. if is_official:
  214. name = docker.read_var(app_path + '/variables.json', 'name')
  215. if name == app_name:
  216. flag = True
  217. elif app_name == customer_name:
  218. flag = True
  219. myLogger.info_logger("APP info: " + info)
  220. return info, flag
  221. def split_app_id(app_id):
  222. return app_id.split("_")[1]
  223. def get_apps_from_compose(output_list):
  224. ip_result = shell_execute.execute_command_output_all("curl ifconfig.me")
  225. ip = ip_result["result"]
  226. app_list = []
  227. has_add = []
  228. for app_info in output_list:
  229. volume = app_info["ConfigFiles"] # volume
  230. app_path = volume.rsplit('/', 1)[0]
  231. customer_name = volume.split('/')[-2]
  232. app_id = "" # app_id
  233. app_name = ""
  234. trade_mark = ""
  235. port = 0
  236. url = ""
  237. admin_url = ""
  238. image_url = ""
  239. user_name = ""
  240. password = ""
  241. official_app = False
  242. if customer_name in ['appmanage', 'nginxproxymanager',
  243. 'redis'] and app_path == '/data/apps/stackhub/docker/' + customer_name:
  244. continue
  245. # get code
  246. status = app_info["Status"].split("(")[0]
  247. if status == "running" or status == "exited" or status == "restarting":
  248. myLogger.info_logger("ok")
  249. elif status == "created":
  250. status = "failed"
  251. else:
  252. continue
  253. var_path = app_path + "/variables.json"
  254. official_app = check_if_official_app(var_path)
  255. if official_app:
  256. app_name = docker.read_var(var_path, 'name')
  257. app_id = app_name + "_" + customer_name # app_id
  258. # get trade_mark
  259. trade_mark = docker.read_var(var_path, 'trademark')
  260. image_url = get_Image_url(app_name)
  261. # get env info
  262. path = app_path + "/.env"
  263. # get port and url
  264. try:
  265. http_port = list(docker.read_env(
  266. path, "APP_HTTP_PORT").values())[0]
  267. port = int(http_port)
  268. easy_url = "http://" + ip + ":" + str(port)
  269. url = get_url(app_name, easy_url)
  270. admin_url = get_admin_url(app_name, url)
  271. except IndexError:
  272. try:
  273. db_port = list(docker.read_env(path, "APP_DB.*_PORT").values())[0]
  274. port = int(db_port)
  275. except IndexError:
  276. pass
  277. # get user_name
  278. try:
  279. user_name = list(docker.read_env(path, "APP_USER").values())[0]
  280. except IndexError:
  281. pass
  282. # get password
  283. try:
  284. password = list(docker.read_env(path, "POWER_PASSWORD").values())[0]
  285. except IndexError:
  286. pass
  287. has_add.append(customer_name)
  288. running_info = RunningInfo(port=port, compose_file=volume, url=url, image_url=image_url, admin_url=admin_url,
  289. user_name=user_name, password=password, default_domain="", set_domain="")
  290. status_reason = StatusReason(Code="", Message="", Detail="")
  291. app = App(app_id=app_id, name=app_name, customer_name=customer_name, trade_mark=trade_mark, status=status,
  292. official_app=official_app, running_info=running_info, status_reason=status_reason)
  293. app_list.append(app.dict())
  294. return app_list, has_add
  295. def check_if_official_app(var_path):
  296. if docker.check_directory(var_path):
  297. if docker.read_var(var_path, 'name') != "" and docker.read_var(var_path, 'trademark') != "" and docker.read_var(
  298. var_path, 'requirements') != "":
  299. requirements = docker.read_var(var_path, 'requirements')
  300. try:
  301. cpu = requirements['cpu']
  302. mem = requirements['memory']
  303. return True
  304. except:
  305. return False
  306. else:
  307. return False
  308. def check_app_rq(app_id):
  309. myLogger.info_logger("check_app_rq")
  310. for job in q.jobs:
  311. if app_id == job.id:
  312. return True
  313. started = StartedJobRegistry(queue=q)
  314. failed = FailedJobRegistry(queue=q)
  315. run_job_ids = started.get_job_ids()
  316. failed_jobs = failed.get_job_ids()
  317. if app_id in run_job_ids:
  318. return True
  319. if app_id in failed_jobs:
  320. return True
  321. return False
  322. def get_apps_from_queue():
  323. myLogger.info_logger("get queque apps...")
  324. # 获取 StartedJobRegistry 实例
  325. started = StartedJobRegistry(queue=q)
  326. finish = FinishedJobRegistry(queue=q)
  327. deferred = DeferredJobRegistry(queue=q)
  328. failed = FailedJobRegistry(queue=q)
  329. scheduled = ScheduledJobRegistry(queue=q)
  330. cancel = CanceledJobRegistry(queue=q)
  331. # 获取正在执行的作业 ID 列表
  332. run_job_ids = started.get_job_ids()
  333. finish_job_ids = finish.get_job_ids()
  334. wait_job_ids = deferred.get_job_ids()
  335. failed_jobs = failed.get_job_ids()
  336. scheduled_jobs = scheduled.get_job_ids()
  337. cancel_jobs = cancel.get_job_ids()
  338. myLogger.info_logger(q.jobs)
  339. myLogger.info_logger(run_job_ids)
  340. myLogger.info_logger(failed_jobs)
  341. myLogger.info_logger(cancel_jobs)
  342. myLogger.info_logger(wait_job_ids)
  343. myLogger.info_logger(finish_job_ids)
  344. myLogger.info_logger(scheduled_jobs)
  345. installing_list = []
  346. for job_id in run_job_ids:
  347. app = get_installing_app(job_id, 'installing', '""', "", "")
  348. installing_list.append(app)
  349. for job in q.jobs:
  350. app = get_installing_app(job.id, 'installing', "", "", "")
  351. installing_list.append(app)
  352. for job_id in failed_jobs:
  353. job = q.fetch_job(job_id)
  354. app = get_installing_app(job_id, 'failed', "", "", "")
  355. installing_list.append(app)
  356. return installing_list
  357. def get_installing_app(id, status, code, message, detail):
  358. app_name = id.split('_')[0]
  359. customer_name = id.split('_')[1]
  360. var_path = "/data/apps/" + customer_name + "/variables.json"
  361. trade_mark = docker.read_var(var_path, 'trademark')
  362. app_name = docker.read_var(var_path, 'name')
  363. image_url = get_Image_url(app_name)
  364. running_info = RunningInfo(port=0, compose_file="", url="", image_url=image_url, admin_url="",
  365. user_name="", password="", default_domain="", set_domain="")
  366. status_reason = StatusReason(Code=code, Message=message, Detail=detail)
  367. app = App(app_id=app_name + "_" + customer_name, name=app_name, customer_name=customer_name,
  368. trade_mark=trade_mark, status=status, official_app=True, running_info=running_info,
  369. status_reason=status_reason)
  370. return app
  371. def get_Image_url(app_name):
  372. image_url = "static/images/" + app_name + "-websoft9.png"
  373. return image_url
  374. def get_url(app_name, easy_url):
  375. url = easy_url
  376. if app_name == "joomla":
  377. url = easy_url + "/administrator"
  378. elif app_name == "other":
  379. url = easy_url + "/administrator"
  380. else:
  381. url = easy_url
  382. return url
  383. def get_admin_url(app_name, url):
  384. admin_url = ""
  385. if app_name == "wordpress":
  386. admin_url = url + "/wp-admin"
  387. elif app_name == "other":
  388. admin_url = url + "/admin"
  389. else:
  390. admin_url = ""
  391. return admin_url
  392. def get_error_info(code, message, detail):
  393. error = {}
  394. error['Code'] = code
  395. error['Message'] = message
  396. error['Detail'] = detail
  397. return error