manage.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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.utils.common_log import myLogger
  17. from redis import Redis
  18. from rq import Queue, Worker, Connection
  19. from rq.registry import StartedJobRegistry, FinishedJobRegistry, DeferredJobRegistry, FailedJobRegistry, ScheduledJobRegistry
  20. # 指定 Redis 容器的主机名和端口
  21. redis_conn = Redis(host='websoft9-redis', port=6379)
  22. # 使用指定的 Redis 连接创建 RQ 队列
  23. q = Queue(connection=redis_conn)
  24. # 获取所有app的信息
  25. def get_my_app():
  26. ret = Response(code=const.RETURN_FAIL, message="App query failed!")
  27. # get all info
  28. cmd = "docker compose ls -a --format json"
  29. output = shell_execute.execute_command_output_all(cmd)
  30. if int(output["code"]) == 0:
  31. output_list = json.loads(output["result"])
  32. installed_list, has_add = get_apps_from_compose(output_list)
  33. installing_list = get_apps_from_queue()
  34. app_list = installed_list + installing_list
  35. ret = Response(code=const.RETURN_SUCCESS, message="The app query is successful.", data=app_list)
  36. ret = ret.dict()
  37. return ret
  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. # 查询某个正在安装的app的 具体状态:waiting(等待安装)pulling(拉取镜像)initializing(初始化)running(正常运行)
  73. def install_app_process(app_id):
  74. ret = {}
  75. ret['code'] = const.RETURN_FAIL
  76. ret['message'] = ""
  77. ret['status'] = ""
  78. app_name = split_app_id(app_id)
  79. if docker.check_app_id(app_id):
  80. info, code = if_app_exits(app_id)
  81. if code:
  82. var_path = "/data/apps/" + app_name + "/variables.json"
  83. real_name = docker.read_var(var_path, 'name')
  84. app_status = docker.get_process_perc(app_name, real_name)
  85. ret["code"] = const.RETURN_SUCCESS
  86. ret['message'] = "This app is installing."
  87. ret['status'] = app_status
  88. else:
  89. ret['message'] = "This app is not currently installed."
  90. else:
  91. ret['message'] = "AppID is not legal!"
  92. ret = ret.dict()
  93. return ret
  94. def install_app(app_name, customer_app_name, app_version):
  95. myLogger.info_logger("Install app ...")
  96. ret = Response(code=const.RETURN_FAIL, message=" ")
  97. app_id = app_name + "_" + customer_app_name
  98. ret.code, ret.message = check_app(app_name, customer_app_name, app_version)
  99. if ret.code == const.RETURN_SUCCESS:
  100. myLogger.info_logger("create job=" + app_id)
  101. # 根据请求创建新作业
  102. new_job = q.enqueue(install_app_delay, app_name, customer_app_name, app_version, job_id=app_id,timeout=3600)
  103. ret.message = "The app is prepare to install, please check again in a few minutes."
  104. ret = ret.dict()
  105. return ret
  106. def start_app(app_id):
  107. ret = Response(code=const.RETURN_FAIL, message="")
  108. if docker.check_app_id(app_id):
  109. app_name = split_app_id(app_id)
  110. info, code = if_app_exits(app_id)
  111. if code:
  112. app_path = info.split()[-1].rsplit('/', 1)[0]
  113. docker.check_app_compose(app_path + '/.env')
  114. cmd = "docker compose -f " + app_path + "/docker-compose.yml start"
  115. output = shell_execute.execute_command_output_all(cmd)
  116. if int(output["code"]) == 0:
  117. ret.code = const.RETURN_SUCCESS
  118. ret.message = "The app starts successfully."
  119. else:
  120. ret.message = "The app failed to start!"
  121. else:
  122. ret.message = "This app is not currently installed."
  123. else:
  124. ret.message = "AppID is not legal!"
  125. ret = ret.dict()
  126. return ret
  127. def stop_app(app_id):
  128. ret = Response(code=const.RETURN_FAIL, message="")
  129. if docker.check_app_id(app_id):
  130. app_name = split_app_id(app_id)
  131. info, code = if_app_exits(app_id)
  132. if code:
  133. app_path = info.split()[-1].rsplit('/', 1)[0]
  134. cmd = "docker compose -f " + app_path + "/docker-compose.yml stop"
  135. output = shell_execute.execute_command_output_all(cmd)
  136. if int(output["code"]) == 0:
  137. ret.code = const.RETURN_SUCCESS
  138. ret.message = "The app stopped successfully."
  139. else:
  140. ret.message = "App stop failed!"
  141. else:
  142. ret.message = "This app is not currently installed."
  143. else:
  144. ret.message = 'AppID is not legal!'
  145. ret = ret.dict()
  146. return ret
  147. def restart_app(app_id):
  148. ret = Response(code=const.RETURN_FAIL, message="")
  149. if docker.check_app_id(app_id):
  150. app_name = split_app_id(app_id)
  151. info, code = if_app_exits(app_id)
  152. if code:
  153. app_path = info.split()[-1].rsplit('/', 1)[0]
  154. cmd = "docker compose -f " + app_path + "/docker-compose.yml restart"
  155. output = shell_execute.execute_command_output_all(cmd)
  156. if int(output["code"]) == 0:
  157. ret.code = const.RETURN_SUCCESS
  158. ret.message = "The app restarts successfully."
  159. else:
  160. ret.message = "App restart failed!"
  161. else:
  162. ret.message = "This app is not currently installed."
  163. else:
  164. ret.message = 'AppID is not legal!'
  165. ret = ret.dict()
  166. return ret
  167. def uninstall_app(app_id):
  168. ret = Response(code=const.RETURN_FAIL, message="")
  169. if docker.check_app_id(app_id):
  170. app_name = split_app_id(app_id)
  171. if_stopped = stop_app(app_id) # stop_app
  172. if if_stopped["code"] == 0:
  173. info, code = if_app_exits(app_id)
  174. app_path = info.split()[-1].rsplit('/', 1)[0]
  175. cmd = "docker compose -f " + app_path + "/docker-compose.yml down -v"
  176. lib_path = '/data/library/apps/' + app_name
  177. if app_path != lib_path:
  178. cmd = cmd + " && sudo rm -rf " + app_path
  179. output = shell_execute.execute_command_output_all(cmd)
  180. if int(output["code"]) == 0:
  181. ret.code = 0
  182. ret.message = "The app is deleted successfully"
  183. else:
  184. ret.message = "App deletion failed!"
  185. else:
  186. ret.message = if_stopped["message"]
  187. else:
  188. ret.message = 'AppID is not legal!'
  189. ret = ret.dict()
  190. return ret
  191. def check_app(app_name, customer_app_name, app_version):
  192. message = " "
  193. code = const.RETURN_FAIL
  194. app_id = app_name + "-" + customer_app_name
  195. if app_name == None or customer_app_name == None or app_version == None:
  196. message = "Please fill in the APP information completely!"
  197. elif not docker.check_app_websoft9(app_name):
  198. message = "Installing the app is not supported!"
  199. elif re.match('^[a-z0-9]+$', customer_app_name) == None:
  200. message = "App names must be lowercase letters and numbers!"
  201. elif docker.check_directory("/data/apps/" + customer_app_name):
  202. message = "The APP name is already in use, please specify a different name to reinstall."
  203. elif not docker.check_vm_resource(app_name):
  204. message = "System resources (memory, CPU, disk) are insufficient, and continuing to install may cause the app to not run or the server to be abnormal!"
  205. elif check_app_wait(app_id):
  206. message = "The APP name is waiting for install, please rename app to install."
  207. else:
  208. code = const.RETURN_SUCCESS
  209. return code, message
  210. def prepare_app(app_name, customer_app_name):
  211. library_path = "/data/library/apps/" + app_name
  212. install_path = "/data/apps/" + customer_app_name
  213. message = " "
  214. code = const.RETURN_SUCCESS
  215. output = shell_execute.execute_command_output_all("cp -r " + library_path + " " + install_path)
  216. if int(output["code"]) != 0:
  217. message = "creating" + customer_app_name + "directory failed!"
  218. code = const.RETURN_FAIL
  219. return code, message
  220. def install_app_delay(app_name, customer_app_name, app_version):
  221. try:
  222. code, message = check_app(app_name, customer_app_name, app_version)
  223. if code == const.RETURN_SUCCESS:
  224. code, message = prepare_app(app_name, customer_app_name)
  225. if code == const.RETURN_SUCCESS:
  226. myLogger.info_logger("start job=" + customer_app_name)
  227. # modify env
  228. env_path = "/data/apps/" + customer_app_name + "/.env"
  229. docker.modify_env(env_path, 'APP_NAME', customer_app_name)
  230. docker.modify_env(env_path, "APP_VERSION", app_version)
  231. # check port
  232. docker.check_app_compose(env_path)
  233. cmd = "cd /data/apps/" + customer_app_name + " && sudo docker compose pull && sudo docker compose up -d"
  234. output = shell_execute.execute_command_output_all(cmd)
  235. myLogger.info_logger("install output")
  236. myLogger.info_logger(output["code"])
  237. myLogger.info_logger(output["result"])
  238. if int(output["code"]) != 0 or "error" in output["result"] or "fail" in output["result"]:
  239. raise Exception("installfailed!")
  240. else:
  241. return "success"
  242. else:
  243. raise Exception("prepare_app failed")
  244. else:
  245. raise Exception("resource check failed")
  246. except Exception as e:
  247. myLogger.info_logger(customer_app_name + "install failed!")
  248. myLogger.error_logger(e)
  249. job_id = app_name + "_" + customer_app_name
  250. try:
  251. uninstall_app(job_id)
  252. except Exception as e:
  253. myLogger.error_logger(e)
  254. raise Exception(e)
  255. def if_app_exits(app_id):
  256. app_name = app_id.split('_')[1]
  257. real_name = app_id.split('_')[0]
  258. flag = False
  259. info = ""
  260. cmd = "docker compose ls -a | grep \'/" + app_name + "/\'"
  261. output = shell_execute.execute_command_output_all(cmd)
  262. if int(output["code"]) == 0:
  263. info = output["result"]
  264. app_path = info.split()[-1].rsplit('/', 1)[0]
  265. is_official = check_if_official_app(app_path + '/variables.json')
  266. if is_official:
  267. name = docker.read_var(app_path + '/variables.json', 'name')
  268. if name == real_name:
  269. flag = True
  270. elif real_name == app_name:
  271. flag = True
  272. myLogger.info_logger("APP info: " + info)
  273. return info, flag
  274. def split_app_id(app_id):
  275. return app_id.split("_")[1]
  276. def get_apps_from_compose(output_list):
  277. ip_result = shell_execute.execute_command_output_all("curl ifconfig.me")
  278. ip = ip_result["result"]
  279. app_list = []
  280. has_add = []
  281. for app_info in output_list:
  282. volume = app_info["ConfigFiles"] # volume
  283. app_path = volume.rsplit('/', 1)[0]
  284. app_name = volume.split('/')[-2]
  285. app_id = app_name + "_" + app_name # app_id
  286. real_name = ""
  287. trade_mark = ""
  288. port = 0
  289. url = ""
  290. admin_url = ""
  291. image_url = ""
  292. user_name = ""
  293. password = ""
  294. official_app = False
  295. if app_name in ['appmanage', 'nginxproxymanager',
  296. 'redis'] and app_path == '/data/apps/stackhub/docker/' + app_name:
  297. continue
  298. # get code
  299. case = app_info["Status"].split("(")[0] # case
  300. if case == "running":
  301. case_code = const.APP_RUNNING # case_code
  302. elif case == "exited":
  303. case = "stop"
  304. case_code = const.APP_STOP
  305. elif case == "created":
  306. case_code = const.APP_READY
  307. case = "installing"
  308. else:
  309. case_code = const.APP_ERROR
  310. var_path = app_path + "/variables.json"
  311. official_app = check_if_official_app(var_path)
  312. if official_app:
  313. real_name = docker.read_var(var_path, 'name')
  314. app_id = real_name + "_" + app_name # app_id
  315. # get trade_mark
  316. trade_mark = docker.read_var(var_path, 'trademark')
  317. image_url = get_Image_url(real_name)
  318. # get env info
  319. path = app_path + "/.env"
  320. # get port and url
  321. try:
  322. http_port = list(docker.read_env(
  323. path, "APP_HTTP_PORT").values())[0]
  324. port = int(http_port)
  325. easy_url = "http://" + ip + ":" + str(port)
  326. url = get_url(real_name, easy_url)
  327. admin_url = get_admin_url(real_name, url)
  328. except IndexError:
  329. try:
  330. db_port = list(docker.read_env(
  331. path, "APP_DB.*_PORT").values())[0]
  332. port = int(db_port)
  333. except IndexError:
  334. pass
  335. # get user_name
  336. try:
  337. user_name = list(docker.read_env(path, "APP_USER").values())[0]
  338. except IndexError:
  339. pass
  340. # get password
  341. try:
  342. password = list(docker.read_env(
  343. path, "POWER_PASSWORD").values())[0]
  344. except IndexError:
  345. pass
  346. has_add.append(app_name)
  347. app = App(app_id=app_id, name=real_name, customer_name=app_name, status_code=case_code, status=case, port=port,
  348. volume=volume, url=url,
  349. image_url=image_url, admin_url=admin_url, trade_mark=trade_mark, user_name=user_name,
  350. password=password, official_app=official_app)
  351. app_list.append(app.dict())
  352. return app_list, has_add
  353. def check_if_official_app(var_path):
  354. if docker.check_directory(var_path):
  355. if docker.read_var(var_path, 'name') != "" and docker.read_var(var_path, 'trademark') != "" and docker.read_var(
  356. var_path, 'requirements') != "":
  357. requirements = docker.read_var(var_path, 'requirements')
  358. try:
  359. cpu = requirements['cpu']
  360. mem = requirements['memory']
  361. return True
  362. except:
  363. return False
  364. else:
  365. return False
  366. def check_app_wait(app_id):
  367. myLogger.info_logger("check_app_wait")
  368. deferred = DeferredJobRegistry(queue=q)
  369. wait_job_ids = deferred.get_job_ids()
  370. if app_id in wait_job_ids:
  371. return True
  372. else:
  373. return False
  374. def get_apps_from_queue():
  375. myLogger.info_logger("get queque apps...")
  376. # 获取 StartedJobRegistry 实例
  377. registry = StartedJobRegistry(queue=q)
  378. finish = FinishedJobRegistry(queue=q)
  379. deferred = DeferredJobRegistry(queue=q)
  380. failed = FailedJobRegistry(queue=q)
  381. scheduled = ScheduledJobRegistry(queue=q)
  382. # 获取正在执行的作业 ID 列表
  383. run_job_ids = registry.get_job_ids()
  384. finish_job_ids = finish.get_job_ids()
  385. wait_job_ids = deferred.get_job_ids()
  386. failed_jobs = failed.get_job_ids()
  387. scheduled_jobs = scheduled.get_job_ids()
  388. myLogger.info_logger(q.jobs)
  389. myLogger.info_logger(wait_job_ids)
  390. myLogger.info_logger(run_job_ids)
  391. myLogger.info_logger(finish_job_ids)
  392. myLogger.info_logger(failed_jobs)
  393. myLogger.info_logger(scheduled_jobs)
  394. myLogger.info_logger("----------------------------------------")
  395. installing_list = []
  396. for job in run_job_ids:
  397. app = get_installing_app(job, const.APP_READY, 'installing')
  398. installing_list.append(app)
  399. for job in q.jobs:
  400. app = get_installing_app(job.id, const.APP_WAIT, 'waiting')
  401. installing_list.append(app)
  402. for job_id in finish_job_ids:
  403. job = q.fetch_job(job_id)
  404. if job.result == "fail":
  405. app = get_installing_app(job_id, const.APP_ERROR, 'error')
  406. installing_list.append(app)
  407. return installing_list
  408. def get_installing_app(id, status_code, status):
  409. real_name = id.split('_')[0]
  410. app_name = id.split('_')[1]
  411. var_path = "/data/apps/" + app_name + "/variables.json"
  412. trade_mark = docker.read_var(var_path, 'trademark')
  413. real_name = docker.read_var(var_path, 'name')
  414. image_url = get_Image_url(real_name)
  415. app = App(app_id=real_name + "_" + app_name, name=real_name, customer_name=app_name,
  416. status_code=status_code, status=status, port=0, volume="",
  417. url="", image_url=image_url, admin_url="", trade_mark=trade_mark, user_name="",
  418. password="", official_app=True)
  419. return app
  420. def get_Image_url(app_name):
  421. image_url = "static/images/" + app_name + "-websoft9.png"
  422. return image_url
  423. def get_url(app_name, easy_url):
  424. url = easy_url
  425. if app_name == "joomla":
  426. url = easy_url + "/administrator"
  427. elif app_name == "other":
  428. url = easy_url + "/administrator"
  429. else:
  430. url = easy_url
  431. return url
  432. def get_admin_url(app_name, url):
  433. admin_url = ""
  434. if app_name == "wordpress":
  435. admin_url = url + "/wp-admin"
  436. elif app_name == "other":
  437. admin_url = url + "/admin"
  438. else:
  439. admin_url = ""
  440. return admin_url