manage.py 18 KB

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