manage.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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 = installing_list + installed_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 = "localhost"
  234. try:
  235. ip_result = shell_execute.execute_command_output_all("cat /data/apps/stackhub/docker/w9appmanage/public_ip")
  236. ip = ip_result["result"].rstrip('\n')
  237. except Exception:
  238. ip = "127.0.0.1"
  239. app_list = []
  240. for app_info in output_list:
  241. volume = app_info["ConfigFiles"] # volume
  242. app_path = volume.rsplit('/', 1)[0]
  243. customer_name = volume.split('/')[-2]
  244. app_id = "" # app_id
  245. app_name = ""
  246. trade_mark = ""
  247. port = 0
  248. url = ""
  249. admin_url = ""
  250. image_url = ""
  251. user_name = ""
  252. password = ""
  253. official_app = False
  254. if customer_name in ['w9appmanage', 'w9nginxproxymanager','w9redis','w9portainer'] and app_path == '/data/apps/stackhub/docker/' + customer_name:
  255. continue
  256. # get code
  257. status = app_info["Status"].split("(")[0]
  258. if status == "running" or status == "exited" or status == "restarting":
  259. myLogger.info_logger("ok")
  260. elif status == "created":
  261. status = "failed"
  262. else:
  263. continue
  264. var_path = app_path + "/variables.json"
  265. official_app = check_if_official_app(var_path)
  266. if official_app:
  267. app_name = docker.read_var(var_path, 'name')
  268. app_id = app_name + "_" + customer_name # app_id
  269. # get trade_mark
  270. trade_mark = docker.read_var(var_path, 'trademark')
  271. image_url = get_Image_url(app_name)
  272. # get env info
  273. path = app_path + "/.env"
  274. # get port and url
  275. try:
  276. http_port = list(docker.read_env(
  277. path, "APP_HTTP_PORT").values())[0]
  278. port = int(http_port)
  279. easy_url = "http://" + ip + ":" + str(port)
  280. url = get_url(app_name, easy_url)
  281. admin_url = get_admin_url(app_name, url)
  282. except IndexError:
  283. try:
  284. db_port = list(docker.read_env(path, "APP_DB.*_PORT").values())[0]
  285. port = int(db_port)
  286. except IndexError:
  287. pass
  288. # get user_name
  289. try:
  290. user_name = list(docker.read_env(path, "APP_USER").values())[0]
  291. except IndexError:
  292. pass
  293. # get password
  294. try:
  295. password = list(docker.read_env(path, "POWER_PASSWORD").values())[0]
  296. except IndexError:
  297. pass
  298. if status in ['running', 'exited']:
  299. config = Config(port=port, compose_file=volume, url=url, admin_url=admin_url,
  300. user_name=user_name, password=password, default_domain="", set_domain="")
  301. else:
  302. config = None
  303. if status == "failed":
  304. status_reason = StatusReason(Code=const.ERROR_SERVER_SYSTEM, Message="system original error", Detail="unknown error")
  305. else:
  306. status_reason = None
  307. app = App(app_id=app_id, app_name=app_name, customer_name=customer_name, trade_mark=trade_mark, status=status,
  308. status_reason=status_reason, official_app=official_app, image_url=image_url,
  309. config=config)
  310. app_list.append(app.dict())
  311. return app_list
  312. def check_if_official_app(var_path):
  313. if docker.check_directory(var_path):
  314. if docker.read_var(var_path, 'name') != "" and docker.read_var(var_path, 'trademark') != "" and docker.read_var(
  315. var_path, 'requirements') != "":
  316. requirements = docker.read_var(var_path, 'requirements')
  317. try:
  318. cpu = requirements['cpu']
  319. mem = requirements['memory']
  320. disk = requirements['disk']
  321. return True
  322. except KeyError:
  323. return False
  324. else:
  325. return False
  326. def check_app_docker(app_id):
  327. customer_name = app_id.split('_')[1]
  328. app_name = app_id.split('_')[0]
  329. flag = False
  330. cmd = "docker compose ls -a | grep \'/" + customer_name + "/\'"
  331. try:
  332. shell_execute.execute_command_output_all(cmd)
  333. flag = True
  334. myLogger.info_logger("APP in docker")
  335. except CommandException as ce:
  336. myLogger.info_logger("APP not in docker")
  337. return flag
  338. def check_app_rq(app_id):
  339. myLogger.info_logger("check_app_rq")
  340. started = StartedJobRegistry(queue=q)
  341. failed = FailedJobRegistry(queue=q)
  342. run_job_ids = started.get_job_ids()
  343. failed_job_ids = failed.get_job_ids()
  344. queue_job_ids = q.job_ids
  345. myLogger.info_logger(queue_job_ids)
  346. myLogger.info_logger(run_job_ids)
  347. myLogger.info_logger(failed_job_ids)
  348. if queue_job_ids and app_id in queue_job_ids:
  349. myLogger.info_logger("App in RQ")
  350. return True
  351. if failed_job_ids and app_id in failed_job_ids:
  352. myLogger.info_logger("App in RQ")
  353. return True
  354. if run_job_ids and app_id in run_job_ids:
  355. myLogger.info_logger("App in RQ")
  356. return True
  357. myLogger.info_logger("App not in RQ")
  358. return False
  359. def get_apps_from_queue():
  360. myLogger.info_logger("get queque apps...")
  361. # 获取 StartedJobRegistry 实例
  362. started = StartedJobRegistry(queue=q)
  363. finish = FinishedJobRegistry(queue=q)
  364. deferred = DeferredJobRegistry(queue=q)
  365. failed = FailedJobRegistry(queue=q)
  366. scheduled = ScheduledJobRegistry(queue=q)
  367. cancel = CanceledJobRegistry(queue=q)
  368. # 获取正在执行的作业 ID 列表
  369. run_job_ids = started.get_job_ids()
  370. finish_job_ids = finish.get_job_ids()
  371. wait_job_ids = deferred.get_job_ids()
  372. failed_jobs = failed.get_job_ids()
  373. scheduled_jobs = scheduled.get_job_ids()
  374. cancel_jobs = cancel.get_job_ids()
  375. myLogger.info_logger(q.jobs)
  376. myLogger.info_logger(run_job_ids)
  377. myLogger.info_logger(failed_jobs)
  378. myLogger.info_logger(cancel_jobs)
  379. myLogger.info_logger(wait_job_ids)
  380. myLogger.info_logger(finish_job_ids)
  381. myLogger.info_logger(scheduled_jobs)
  382. installing_list = []
  383. for job_id in run_job_ids:
  384. app = get_rq_app(job_id, 'installing', "", "", "")
  385. installing_list.append(app)
  386. for job in q.jobs:
  387. app = get_rq_app(job.id, 'installing', "", "", "")
  388. installing_list.append(app)
  389. for job_id in failed_jobs:
  390. job = q.fetch_job(job_id)
  391. exc_info = job.exc_info
  392. code = exc_info.split('##websoft9##')[1]
  393. message = exc_info.split('##websoft9##')[2]
  394. detail = exc_info.split('##websoft9##')[3]
  395. app = get_rq_app(job_id, 'failed', code, message, detail)
  396. installing_list.append(app)
  397. return installing_list
  398. def get_rq_app(id, status, code, message, detail):
  399. app_name = id.split('_')[0]
  400. customer_name = id.split('_')[1]
  401. # 当app还在RQ时,可能文件夹还没创建,无法获取trade_mark
  402. trade_mark = ""
  403. image_url = get_Image_url(app_name)
  404. config = None
  405. if status == "installing" :
  406. status_reason = None
  407. else:
  408. status_reason = StatusReason(Code=code, Message=message, Detail=detail)
  409. app = App(app_id=id, app_name=app_name, customer_name=customer_name, trade_mark=trade_mark,
  410. status=status, status_reason=status_reason, official_app=True, image_url=image_url,
  411. config=config)
  412. return app.dict()
  413. def get_Image_url(app_name):
  414. image_url = "static/images/" + app_name + "-websoft9.png"
  415. return image_url
  416. def get_url(app_name, easy_url):
  417. url = easy_url
  418. if app_name == "joomla":
  419. url = easy_url + "/administrator"
  420. elif app_name == "other":
  421. url = easy_url + "/administrator"
  422. else:
  423. url = easy_url
  424. return url
  425. def get_admin_url(app_name, url):
  426. admin_url = ""
  427. if app_name == "wordpress":
  428. admin_url = url + "/wp-admin"
  429. elif app_name == "other":
  430. admin_url = url + "/admin"
  431. else:
  432. admin_url = ""
  433. return admin_url
  434. def get_error_info(code, message, detail):
  435. error = {}
  436. error['Code'] = code
  437. error['Message'] = message
  438. error['Detail'] = detail
  439. return error