manage.py 16 KB

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