manage.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. var_path = "/data/apps/" + app_name + "/variables.json"
  81. real_name = docker.read_var(var_path, 'name')
  82. info, code = if_app_exits(app_id)
  83. if code:
  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)
  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. if app_name == None or customer_app_name == None or app_version == None:
  195. message = "Please fill in the APP information completely!"
  196. elif not docker.check_app_directory(app_name):
  197. message = "Installing the app is not supported!"
  198. elif re.match('^[a-z0-9]+$', customer_app_name) == None:
  199. message = "App names must be lowercase letters and numbers!"
  200. elif docker.check_directory("/data/apps/" + customer_app_name):
  201. message = "The APP name is already in use, please specify a different name to reinstall."
  202. elif not docker.check_vm_resource(app_name):
  203. 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!"
  204. else:
  205. code = const.RETURN_SUCCESS
  206. return code, message
  207. def prepare_app(app_name, customer_app_name):
  208. library_path = "/data/library/apps/" + app_name
  209. install_path = "/data/apps/" + customer_app_name
  210. message = " "
  211. code = const.RETURN_SUCCESS
  212. output = shell_execute.execute_command_output_all("cp -r " + library_path + " " + install_path)
  213. if int(output["code"]) != 0:
  214. message = "creating" + customer_app_name + "directory failed!"
  215. code = const.RETURN_FAIL
  216. return code, message
  217. def install_app_delay(app_name, customer_app_name, app_version):
  218. try:
  219. code, message = check_app(app_name, customer_app_name, app_version)
  220. if code == const.RETURN_SUCCESS:
  221. code, message = prepare_app(app_name, customer_app_name)
  222. if code == const.RETURN_SUCCESS:
  223. myLogger.info_logger("start job=" + customer_app_name)
  224. # modify env
  225. env_path = "/data/apps/" + customer_app_name + "/.env"
  226. docker.modify_env(env_path, 'APP_NAME', customer_app_name)
  227. docker.modify_env(env_path, "APP_VERSION", app_version)
  228. # check port
  229. docker.check_app_compose(env_path)
  230. cmd = "cd /data/apps/" + customer_app_name + " && sudo docker compose pull && sudo docker compose up -d"
  231. output = shell_execute.execute_command_output_all(cmd)
  232. if int(output["code"]) != 0:
  233. raise Exception("install" + customer_app_name + " failed!")
  234. else:
  235. raise Exception("prepare_app failed")
  236. else:
  237. raise Exception("resource check failed")
  238. except Exception as e:
  239. myLogger.info_logger(customer_app_name+"install failed!")
  240. myLogger.error_logger(e)
  241. job_id = app_name + "_" + customer_app_name
  242. fail_job = q.fetch_job(job_id)
  243. fail_job.set_status('failed')
  244. def if_app_exits(app_id):
  245. app_name = app_id.split('_')[1]
  246. real_name = app_id.split('_')[0]
  247. flag = False
  248. info = ""
  249. cmd = "docker compose ls -a | grep \'/" + app_name + "/\'"
  250. output = shell_execute.execute_command_output_all(cmd)
  251. if int(output["code"]) == 0:
  252. info = output["result"]
  253. app_path = info.split()[-1].rsplit('/', 1)[0]
  254. is_official = check_if_official_app(app_path + '/variables.json')
  255. if is_official:
  256. name = docker.read_var(app_path + '/variables.json', 'name')
  257. if name == real_name:
  258. flag = True
  259. elif real_name == app_name:
  260. flag = True
  261. myLogger.info_logger("APP info: " + info)
  262. return info, flag
  263. def split_app_id(app_id):
  264. return app_id.split("_")[1]
  265. def get_apps_from_compose(output_list):
  266. ip_result = shell_execute.execute_command_output_all("curl ifconfig.me")
  267. ip = ip_result["result"]
  268. app_list = []
  269. has_add = []
  270. for app_info in output_list:
  271. volume = app_info["ConfigFiles"] # volume
  272. app_path = volume.rsplit('/', 1)[0]
  273. app_name = volume.split('/')[-2]
  274. app_id = app_name + "_" + app_name # app_id
  275. real_name = ""
  276. trade_mark = ""
  277. port = 0
  278. url = ""
  279. admin_url = ""
  280. image_url = ""
  281. user_name = ""
  282. password = ""
  283. official_app = False
  284. if app_name in ['appmanage', 'nginxproxymanager', 'redis']:
  285. continue
  286. # get code
  287. case = app_info["Status"].split("(")[0] # case
  288. if case == "running":
  289. case_code = const.APP_RUNNING # case_code
  290. elif case == "exited":
  291. case = "stop"
  292. case_code = const.APP_STOP
  293. elif case == "created":
  294. case_code = const.APP_READY
  295. case = "installing"
  296. else:
  297. case_code = const.APP_ERROR
  298. var_path = app_path + "/variables.json"
  299. official_app = check_if_official_app(var_path)
  300. if official_app:
  301. real_name = docker.read_var(var_path, 'name')
  302. app_id = real_name + "_" + app_name # app_id
  303. # get trade_mark
  304. trade_mark = docker.read_var(var_path, 'trademark')
  305. image_url = get_Image_url(real_name)
  306. # get env info
  307. path = app_path + "/.env"
  308. # get port and url
  309. try:
  310. http_port = list(docker.read_env(
  311. path, "APP_HTTP_PORT").values())[0]
  312. port = int(http_port)
  313. easy_url = "http://" + ip + ":" + str(port)
  314. url = get_url(real_name, easy_url)
  315. admin_url = get_admin_url(real_name, url)
  316. except IndexError:
  317. try:
  318. db_port = list(docker.read_env(
  319. path, "APP_DB.*_PORT").values())[0]
  320. port = int(db_port)
  321. except IndexError:
  322. pass
  323. # get user_name
  324. try:
  325. user_name = list(docker.read_env(path, "APP_USER").values())[0]
  326. except IndexError:
  327. pass
  328. # get password
  329. try:
  330. password = list(docker.read_env(
  331. path, "POWER_PASSWORD").values())[0]
  332. except IndexError:
  333. pass
  334. has_add.append(app_name)
  335. app = App(app_id=app_id, name=real_name, customer_name=app_name, status_code=case_code, status=case, port=port,
  336. volume=volume, url=url,
  337. image_url=image_url, admin_url=admin_url, trade_mark=trade_mark, user_name=user_name,
  338. password=password, official_app=official_app)
  339. app_list.append(app.dict())
  340. return app_list, has_add
  341. def check_if_official_app(var_path):
  342. if docker.check_directory(var_path):
  343. if docker.read_var(var_path, 'name') != "" and docker.read_var(var_path, 'trademark') != "" and docker.read_var(
  344. var_path, 'requirements') != "":
  345. requirements = docker.read_var(var_path, 'requirements')
  346. try:
  347. cpu = requirements['cpu']
  348. mem = requirements['memory']
  349. return True
  350. except:
  351. return False
  352. else:
  353. return False
  354. def get_apps_from_queue():
  355. myLogger.info_logger("get queque apps...")
  356. # 获取 StartedJobRegistry 实例
  357. registry = StartedJobRegistry(queue=q)
  358. finish = FinishedJobRegistry(queue=q)
  359. deferred = DeferredJobRegistry(queue=q)
  360. failed = FailedJobRegistry(queue=q)
  361. scheduled = ScheduledJobRegistry(queue=q)
  362. # 获取正在执行的作业 ID 列表
  363. run_job_ids = registry.get_job_ids()
  364. finish_job_ids = finish.get_job_ids()
  365. wait_job_ids = deferred.get_job_ids()
  366. failed_jobs = failed.get_job_ids()
  367. scheduled_jobs = scheduled.get_job_ids()
  368. myLogger.info_logger(q.jobs)
  369. myLogger.info_logger(wait_job_ids)
  370. myLogger.info_logger(run_job_ids)
  371. myLogger.info_logger(finish_job_ids)
  372. myLogger.info_logger(failed_jobs )
  373. myLogger.info_logger(scheduled_jobs)
  374. installing_list = []
  375. for id in run_job_ids:
  376. app = get_installing_app(id, const.APP_READY, 'installing')
  377. installing_list.append(app)
  378. for id in wait_job_ids:
  379. app = get_installing_app(id, const.APP_WAIT, 'waiting')
  380. installing_list.append(app)
  381. return installing_list
  382. def get_installing_app(id, status_code, status):
  383. real_name = id.split('_')[0]
  384. app_name = id.split('_')[1]
  385. var_path = "/data/apps/" + app_name + "/variables.json"
  386. trade_mark = docker.read_var(var_path, 'trademark')
  387. real_name = docker.read_var(var_path, 'name')
  388. image_url = get_Image_url(real_name)
  389. app = App(app_id=real_name + "_" + app_name, name=real_name, customer_name=app_name,
  390. status_code=status_code, status=status, port=0, volume="",
  391. url="", image_url=image_url, admin_url="", trade_mark=trade_mark, user_name="",
  392. password="", official_app=True)
  393. return app
  394. def get_Image_url(app_name):
  395. image_url = "static/images/" + app_name + "-websoft9.png"
  396. return image_url
  397. def get_url(app_name, easy_url):
  398. url = easy_url
  399. if app_name == "joomla":
  400. url = easy_url + "/administrator"
  401. elif app_name == "other":
  402. url = easy_url + "/administrator"
  403. else:
  404. url = easy_url
  405. return url
  406. def get_admin_url(app_name, url):
  407. admin_url = ""
  408. if app_name == "wordpress":
  409. admin_url = url + "/wp-admin"
  410. elif app_name == "other":
  411. admin_url = url + "/admin"
  412. else:
  413. admin_url = ""
  414. return admin_url