manage.py 17 KB

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