manage.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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
  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. code, message = check_app(app_name, customer_app_name, app_version)
  219. if code == const.RETURN_SUCCESS:
  220. code, message = prepare_app(app_name, customer_app_name)
  221. if code == const.RETURN_SUCCESS:
  222. myLogger.info_logger("start job=" + customer_app_name)
  223. # modify env
  224. env_path = "/data/apps/" + customer_app_name + "/.env"
  225. docker.modify_env(env_path, 'APP_NAME', customer_app_name)
  226. docker.modify_env(env_path, "APP_VERSION", app_version)
  227. # check port
  228. docker.check_app_compose(env_path)
  229. cmd = "cd /data/apps/" + customer_app_name + " && sudo docker compose pull && sudo docker compose up -d"
  230. shell_execute.execute_command_output_all(cmd)
  231. def if_app_exits(app_id):
  232. app_name = app_id.split('_')[1]
  233. real_name = app_id.split('_')[0]
  234. flag = False
  235. info = ""
  236. cmd = "docker compose ls -a | grep \'/" + app_name + "/\'"
  237. output = shell_execute.execute_command_output_all(cmd)
  238. if int(output["code"]) == 0:
  239. info = output["result"]
  240. app_path = info.split()[-1].rsplit('/', 1)[0]
  241. is_official = check_if_official_app(app_path + '/variables.json')
  242. if is_official:
  243. name = docker.read_var(app_path + '/variables.json', 'name')
  244. if name == real_name:
  245. flag = True
  246. elif real_name == app_name:
  247. flag = True
  248. myLogger.info_logger("APP info: " + info)
  249. return info, flag
  250. def split_app_id(app_id):
  251. return app_id.split("_")[1]
  252. def get_apps_from_compose(output_list):
  253. ip_result = shell_execute.execute_command_output_all("curl ifconfig.me")
  254. ip = ip_result["result"]
  255. app_list = []
  256. has_add = []
  257. for app_info in output_list:
  258. volume = app_info["ConfigFiles"] # volume
  259. app_path = volume.rsplit('/', 1)[0]
  260. app_name = volume.split('/')[-2]
  261. app_id = app_name + "_" + app_name # app_id
  262. real_name = ""
  263. trade_mark = ""
  264. port = 0
  265. url = ""
  266. admin_url = ""
  267. image_url = ""
  268. user_name = ""
  269. password = ""
  270. official_app = False
  271. if app_name in ['appmanage', 'nginxproxymanager', 'redis']:
  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. real_name = docker.read_var(var_path, 'name')
  289. app_id = real_name + "_" + app_name # app_id
  290. # get trade_mark
  291. trade_mark = docker.read_var(var_path, 'trademark')
  292. image_url = get_Image_url(real_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(real_name, easy_url)
  302. admin_url = get_admin_url(real_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(app_name)
  322. app = App(app_id=app_id, name=real_name, customer_name=app_name, status_code=case_code, status=case, port=port,
  323. volume=volume, url=url,
  324. image_url=image_url, admin_url=admin_url, trade_mark=trade_mark, user_name=user_name,
  325. password=password, official_app=official_app)
  326. app_list.append(app.dict())
  327. return app_list, has_add
  328. def check_if_official_app(var_path):
  329. if docker.check_directory(var_path):
  330. if docker.read_var(var_path, 'name') != "" and docker.read_var(var_path, 'trademark') != "" and docker.read_var(
  331. var_path, 'requirements') != "":
  332. requirements = docker.read_var(var_path, 'requirements')
  333. try:
  334. cpu = requirements['cpu']
  335. mem = requirements['memory']
  336. return True
  337. except:
  338. return False
  339. else:
  340. return False
  341. def get_apps_from_queue():
  342. myLogger.info_logger("get queque apps...")
  343. # 获取 StartedJobRegistry 实例
  344. registry = StartedJobRegistry(queue=q)
  345. finish = FinishedJobRegistry(queue=q)
  346. deferred = DeferredJobRegistry(queue=q)
  347. # 获取正在执行的作业 ID 列表
  348. run_job_ids = registry.get_job_ids()
  349. finish_job_ids = finish.get_job_ids()
  350. wait_job_ids = deferred.get_job_ids()
  351. myLogger.info_logger(wait_job_ids)
  352. myLogger.info_logger(run_job_ids)
  353. myLogger.info_logger(finish_job_ids)
  354. installing_list = []
  355. for id in run_job_ids:
  356. app = get_installing_app(id, const.APP_READY, 'installing')
  357. installing_list.append(app)
  358. for id in wait_job_ids:
  359. app = get_installing_app(id, const.APP_WAIT, 'waiting')
  360. installing_list.append(app)
  361. return installing_list
  362. def get_installing_app(id, status_code, status):
  363. real_name = id.split('_')[0]
  364. app_name = id.split('_')[1]
  365. var_path = "/data/apps/" + app_name + "/variables.json"
  366. trade_mark = docker.read_var(var_path, 'trademark')
  367. real_name = docker.read_var(var_path, 'name')
  368. image_url = get_Image_url(real_name)
  369. app = App(app_id=real_name + "_" + app_name, name=real_name, customer_name=app_name,
  370. status_code=status_code, status=status, port=0, volume="",
  371. url="", image_url=image_url, admin_url="", trade_mark=trade_mark, user_name="",
  372. password="", official_app=True)
  373. return app
  374. def get_Image_url(app_name):
  375. image_url = "static/images/" + app_name + "-websoft9.png"
  376. return image_url
  377. def get_url(app_name, easy_url):
  378. url = easy_url
  379. if app_name == "joomla":
  380. url = easy_url + "/administrator"
  381. elif app_name == "other":
  382. url = easy_url + "/administrator"
  383. else:
  384. url = easy_url
  385. return url
  386. def get_admin_url(app_name, url):
  387. admin_url = ""
  388. if app_name == "wordpress":
  389. admin_url = url + "/wp-admin"
  390. elif app_name == "other":
  391. admin_url = url + "/admin"
  392. else:
  393. admin_url = ""
  394. return admin_url