manage.py 17 KB

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