manage.py 17 KB

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