manage.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. app_name = split_app_id(app_id)
  81. info, flag = app_exits_in_docker(app_id)
  82. if flag:
  83. app_path = info.split()[-1].rsplit('/', 1)[0]
  84. cmd = "docker compose -f " + app_path + "/docker-compose.yml start"
  85. shell_execute.execute_command_output_all(cmd)
  86. else:
  87. raise CommandException(const.ERROR_CLIENT_PARAM_NOTEXIST, "APP is not exist", "")
  88. else:
  89. raise CommandException(code, message, '')
  90. def stop_app(app_id):
  91. code, message = docker.check_app_id(app_id)
  92. myLogger.info_logger(message)
  93. if code == None:
  94. app_name = split_app_id(app_id)
  95. info, flag = app_exits_in_docker(app_id)
  96. if flag:
  97. app_path = info.split()[-1].rsplit('/', 1)[0]
  98. cmd = "docker compose -f " + app_path + "/docker-compose.yml stop"
  99. shell_execute.execute_command_output_all(cmd)
  100. else:
  101. raise CommandException(const.ERROR_CLIENT_PARAM_NOTEXIST, "APP is not exist", "")
  102. else:
  103. myLogger.info_logger("check app failed")
  104. raise CommandException(code, message, "")
  105. def restart_app(app_id):
  106. code, message = docker.check_app_id(app_id)
  107. if code == None:
  108. app_name = split_app_id(app_id)
  109. info, flag = app_exits_in_docker(app_id)
  110. if flag:
  111. app_path = info.split()[-1].rsplit('/', 1)[0]
  112. cmd = "docker compose -f " + app_path + "/docker-compose.yml restart"
  113. shell_execute.execute_command_output_all(cmd)
  114. else:
  115. raise CommandException(const.ERROR_CLIENT_PARAM_NOTEXIST, "APP is not exist", "")
  116. else:
  117. raise CommandException(code, message, "")
  118. def delete_app_failedjob(job_id):
  119. myLogger.info_logger("delete_app_failedjob")
  120. failed = FailedJobRegistry(queue=q)
  121. failed.remove(job_id, delete_job=True)
  122. def uninstall_app(app_id):
  123. code, message = docker.check_app_id(app_id)
  124. if code == None:
  125. app_name = app_id.split('_')[0]
  126. info, code_exist = app_exits_in_docker(app_id)
  127. if code_exist:
  128. app_path = info.split()[-1].rsplit('/', 1)[0]
  129. cmd = "docker compose -f " + app_path + "/docker-compose.yml down -v"
  130. lib_path = '/data/library/apps/' + app_name
  131. if app_path != lib_path:
  132. cmd = cmd + " && sudo rm -rf " + app_path
  133. shell_execute.execute_command_output_all(cmd)
  134. else:
  135. if check_app_rq(app_id):
  136. delete_app_failedjob(app_id)
  137. else:
  138. raise CommandException(const.ERROR_CLIENT_PARAM_NOTEXIST, "AppID is not exist", "")
  139. else:
  140. raise CommandException(code, message, "")
  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. myLogger.info_logger("job check ok, continue to install app")
  180. prepare_app(app_name, customer_name)
  181. myLogger.info_logger("start JobID=" + job_id)
  182. # modify env
  183. env_path = "/data/apps/" + customer_name + "/.env"
  184. docker.modify_env(env_path, 'APP_NAME', customer_name)
  185. docker.modify_env(env_path, "APP_VERSION", app_version)
  186. # check port
  187. docker.check_app_compose(env_path)
  188. cmd = "cd /data/apps/" + customer_name + " && sudo docker compose pull && sudo docker compose up -d"
  189. output = shell_execute.execute_command_output_all(cmd)
  190. myLogger.info_logger("-------Install result--------")
  191. myLogger.info_logger(output["code"])
  192. myLogger.info_logger(output["result"])
  193. else:
  194. myLogger.info_logger("job check failed, stop to install app")
  195. raise CommandException(code, message, "")
  196. except CommandException as ce:
  197. uninstall_app(job_id)
  198. raise CommandException(ce.code, ce.message, ce.detail)
  199. except Exception as e:
  200. myLogger.info_logger(customer_name + "install failed!")
  201. myLogger.error_logger(e)
  202. uninstall_app(job_id)
  203. raise CommandException(const.ERROR_SERVER_SYSTEM, "system original error", str(e))
  204. def app_exits_in_docker(app_id):
  205. customer_name = app_id.split('_')[1]
  206. app_name = app_id.split('_')[0]
  207. flag = False
  208. info = ""
  209. cmd = "docker compose ls -a | grep \'/" + app_name + "/\'"
  210. try:
  211. output = shell_execute.execute_command_output_all(cmd)
  212. if int(output["code"]) == 0:
  213. info = output["result"]
  214. app_path = info.split()[-1].rsplit('/', 1)[0]
  215. is_official = check_if_official_app(app_path + '/variables.json')
  216. if is_official:
  217. name = docker.read_var(app_path + '/variables.json', 'name')
  218. if name == app_name:
  219. flag = True
  220. elif app_name == customer_name:
  221. flag = True
  222. myLogger.info_logger("APP in docker")
  223. except CommandException as ce:
  224. myLogger.info_logger("APP not in docker")
  225. return info, flag
  226. def split_app_id(app_id):
  227. return app_id.split("_")[1]
  228. def get_apps_from_compose():
  229. myLogger.info_logger("Search all of apps ...")
  230. cmd = "docker compose ls -a --format json"
  231. output = shell_execute.execute_command_output_all(cmd)
  232. output_list = json.loads(output["result"])
  233. myLogger.info_logger(len(output_list))
  234. ip_result = shell_execute.execute_command_output_all("curl ifconfig.me")
  235. ip = ip_result["result"]
  236. app_list = []
  237. for app_info in output_list:
  238. volume = app_info["ConfigFiles"] # volume
  239. app_path = volume.rsplit('/', 1)[0]
  240. customer_name = volume.split('/')[-2]
  241. app_id = "" # app_id
  242. app_name = ""
  243. trade_mark = ""
  244. port = 0
  245. url = ""
  246. admin_url = ""
  247. image_url = ""
  248. user_name = ""
  249. password = ""
  250. official_app = False
  251. if customer_name in ['appmanage', 'nginxproxymanager','redis'] and app_path == '/data/apps/stackhub/docker/' + customer_name:
  252. continue
  253. # get code
  254. status = app_info["Status"].split("(")[0]
  255. if status == "running" or status == "exited" or status == "restarting":
  256. myLogger.info_logger("ok")
  257. elif status == "created":
  258. status = "failed"
  259. else:
  260. continue
  261. var_path = app_path + "/variables.json"
  262. official_app = check_if_official_app(var_path)
  263. if official_app:
  264. app_name = docker.read_var(var_path, 'name')
  265. app_id = app_name + "_" + customer_name # app_id
  266. # get trade_mark
  267. trade_mark = docker.read_var(var_path, 'trademark')
  268. image_url = get_Image_url(app_name)
  269. # get env info
  270. path = app_path + "/.env"
  271. # get port and url
  272. try:
  273. http_port = list(docker.read_env(
  274. path, "APP_HTTP_PORT").values())[0]
  275. port = int(http_port)
  276. easy_url = "http://" + ip + ":" + str(port)
  277. url = get_url(app_name, easy_url)
  278. admin_url = get_admin_url(app_name, url)
  279. except IndexError:
  280. try:
  281. db_port = list(docker.read_env(path, "APP_DB.*_PORT").values())[0]
  282. port = int(db_port)
  283. except IndexError:
  284. pass
  285. # get user_name
  286. try:
  287. user_name = list(docker.read_env(path, "APP_USER").values())[0]
  288. except IndexError:
  289. pass
  290. # get password
  291. try:
  292. password = list(docker.read_env(path, "POWER_PASSWORD").values())[0]
  293. except IndexError:
  294. pass
  295. running_info = RunningInfo(port=port, compose_file=volume, url=url, admin_url=admin_url,
  296. user_name=user_name, password=password, default_domain="", set_domain="")
  297. status_reason = StatusReason(Code="", Message="", Detail="")
  298. app = App(app_id=app_id, app_name=app_name, customer_name=customer_name, trade_mark=trade_mark, status=status,
  299. status_reason=status_reason, official_app=official_app, image_url=image_url,
  300. running_info=running_info)
  301. app_list.append(app.dict())
  302. return app_list
  303. def check_if_official_app(var_path):
  304. if docker.check_directory(var_path):
  305. if docker.read_var(var_path, 'name') != "" and docker.read_var(var_path, 'trademark') != "" and docker.read_var(
  306. var_path, 'requirements') != "":
  307. requirements = docker.read_var(var_path, 'requirements')
  308. try:
  309. cpu = requirements['cpu']
  310. mem = requirements['memory']
  311. return True
  312. except:
  313. return False
  314. else:
  315. return False
  316. def check_app_rq(app_id):
  317. myLogger.info_logger("check_app_rq")
  318. started = StartedJobRegistry(queue=q)
  319. failed = FailedJobRegistry(queue=q)
  320. run_job_ids = started.get_job_ids()
  321. failed_job_ids = failed.get_job_ids()
  322. queue_job_ids = q.job_ids
  323. myLogger.info_logger(queue_job_ids)
  324. myLogger.info_logger(run_job_ids)
  325. myLogger.info_logger(failed_job_ids)
  326. if queue_job_ids and app_id in queue_job_ids:
  327. myLogger.info_logger("App in RQ")
  328. return True
  329. if failed_job_ids and app_id in failed_job_ids:
  330. myLogger.info_logger("App in RQ")
  331. return True
  332. if run_job_ids and app_id in run_job_ids:
  333. myLogger.info_logger("App in RQ")
  334. return True
  335. myLogger.info_logger("App not in RQ")
  336. return False
  337. def get_apps_from_queue():
  338. myLogger.info_logger("get queque apps...")
  339. # 获取 StartedJobRegistry 实例
  340. started = StartedJobRegistry(queue=q)
  341. finish = FinishedJobRegistry(queue=q)
  342. deferred = DeferredJobRegistry(queue=q)
  343. failed = FailedJobRegistry(queue=q)
  344. scheduled = ScheduledJobRegistry(queue=q)
  345. cancel = CanceledJobRegistry(queue=q)
  346. # 获取正在执行的作业 ID 列表
  347. run_job_ids = started.get_job_ids()
  348. finish_job_ids = finish.get_job_ids()
  349. wait_job_ids = deferred.get_job_ids()
  350. failed_jobs = failed.get_job_ids()
  351. scheduled_jobs = scheduled.get_job_ids()
  352. cancel_jobs = cancel.get_job_ids()
  353. myLogger.info_logger(q.jobs)
  354. myLogger.info_logger(run_job_ids)
  355. myLogger.info_logger(failed_jobs)
  356. myLogger.info_logger(cancel_jobs)
  357. myLogger.info_logger(wait_job_ids)
  358. myLogger.info_logger(finish_job_ids)
  359. myLogger.info_logger(scheduled_jobs)
  360. installing_list = []
  361. for job_id in run_job_ids:
  362. app = get_rq_app(job_id, 'installing', "", "", "")
  363. installing_list.append(app)
  364. for job in q.jobs:
  365. app = get_rq_app(job.id, 'installing', "", "", "")
  366. installing_list.append(app)
  367. for job_id in failed_jobs:
  368. job = q.fetch_job(job_id)
  369. app = get_rq_app(job_id, 'failed', "", "", "")
  370. installing_list.append(app)
  371. return installing_list
  372. def get_rq_app(id, status, code, message, detail):
  373. app_name = id.split('_')[0]
  374. customer_name = id.split('_')[1]
  375. # 当app还在RQ时,可能文件夹还没创建,无法获取trade_mark
  376. trade_mark = ""
  377. image_url = get_Image_url(app_name)
  378. running_info = RunningInfo(port=0, compose_file="", url="", admin_url="",
  379. user_name="", password="", default_domain="", set_domain="")
  380. status_reason = StatusReason(Code=code, Message=message, Detail=detail)
  381. app = App(app_id=id, app_name=app_name, customer_name=customer_name, trade_mark=trade_mark,
  382. status=status, status_reason=status_reason, official_app=True, image_url=image_url,
  383. running_info=running_info)
  384. return app.dict()
  385. def get_Image_url(app_name):
  386. image_url = "static/images/" + app_name + "-websoft9.png"
  387. return image_url
  388. def get_url(app_name, easy_url):
  389. url = easy_url
  390. if app_name == "joomla":
  391. url = easy_url + "/administrator"
  392. elif app_name == "other":
  393. url = easy_url + "/administrator"
  394. else:
  395. url = easy_url
  396. return url
  397. def get_admin_url(app_name, url):
  398. admin_url = ""
  399. if app_name == "wordpress":
  400. admin_url = url + "/wp-admin"
  401. elif app_name == "other":
  402. admin_url = url + "/admin"
  403. else:
  404. admin_url = ""
  405. return admin_url
  406. def get_error_info(code, message, detail):
  407. error = {}
  408. error['Code'] = code
  409. error['Message'] = message
  410. error['Detail'] = detail
  411. return error