manage.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279
  1. from ast import Constant
  2. import os
  3. import io
  4. import sys
  5. import platform
  6. import shutil
  7. import time
  8. import subprocess
  9. import requests
  10. import json
  11. import datetime
  12. import socket
  13. import re
  14. from threading import Thread
  15. from api.utils import shell_execute, docker, const
  16. from api.model.app import App
  17. from api.service import db
  18. from api.model.response import Response
  19. from api.model.config import Config
  20. from api.model.status_reason import StatusReason
  21. from api.utils.common_log import myLogger
  22. from redis import Redis
  23. from rq import Queue, Worker, Connection
  24. from rq.registry import StartedJobRegistry, FinishedJobRegistry, DeferredJobRegistry, FailedJobRegistry, ScheduledJobRegistry, CanceledJobRegistry
  25. from api.exception.command_exception import CommandException
  26. from apscheduler.schedulers.background import BackgroundScheduler
  27. from apscheduler.triggers.date import DateTrigger
  28. from apscheduler.triggers.cron import CronTrigger
  29. from apscheduler.triggers.interval import IntervalTrigger
  30. from apscheduler.events import EVENT_SCHEDULER_PAUSED, EVENT_SCHEDULER_RESUMED,EVENT_SCHEDULER_STARTED,EVENT_SCHEDULER_SHUTDOWN
  31. # 指定 Redis 容器的主机名和端口
  32. redis_conn = Redis(host='websoft9-redis', port=6379)
  33. # 使用指定的 Redis 连接创建 RQ 队列
  34. q = Queue(connection=redis_conn, default_timeout=3600)
  35. def auto_update():
  36. myLogger.info_logger("auto update")
  37. shell_execute.execute_command_output_all("rm -rf /tmp/update_appstore.sh")
  38. shell_execute.execute_command_output_all("cd /tmp && wget https://websoft9.github.io/websoft9/install/update_appstore.sh")
  39. shell_execute.execute_command_output_all("bash /tmp/update_appstore.sh 1>/dev/null 2>&1")
  40. scheduler = BackgroundScheduler()
  41. scheduler.add_job(auto_update, 'cron', hour=1)
  42. scheduler.start()
  43. # 获取github文件内容
  44. def get_github_content(repo, path):
  45. url = 'https://websoft9.github.io/{repo}/{path}'
  46. url = url.format(repo=repo, path=path)
  47. response = requests.get(url)
  48. response.encoding = 'utf-8'
  49. contents = response.text
  50. return contents
  51. def AppAutoUpdate(auto_update):
  52. myLogger.info_logger(scheduler.state)
  53. myLogger.info_logger(scheduler.get_jobs())
  54. if auto_update == "true" or auto_update == "True":
  55. scheduler.resume()
  56. return "true"
  57. elif auto_update == "false" or auto_update == "False":
  58. scheduler.pause()
  59. return "false"
  60. elif auto_update == None or auto_update == "" or auto_update == "undefine":
  61. state = scheduler.state
  62. if state == 1:
  63. return "true"
  64. else:
  65. return "false"
  66. # 更新软件商店
  67. def AppStoreUpdate():
  68. local_path = '/data/library/install/version.json'
  69. local_version = "0"
  70. try:
  71. op = shell_execute.execute_command_output_all("cat " + local_path)['result']
  72. local_version = json.loads(op)['VERSION']
  73. except:
  74. local_version = "0.0.1"
  75. repo = 'docker-library'
  76. version_contents = get_github_content(repo, 'install/version.json')
  77. version = json.loads(version_contents)['VERSION']
  78. if compared_version(local_version, version) == -1:
  79. content = []
  80. change_log_contents = get_github_content(repo, 'CHANGELOG.md')
  81. change_log = change_log_contents.split('## ')[1].split('\n')
  82. for change in change_log[1:]:
  83. if change != '':
  84. content.append(change)
  85. shell_execute.execute_command_output_all("rm -rf /tmp/update_appstore.sh")
  86. shell_execute.execute_command_output_all("cd /tmp && wget https://websoft9.github.io/websoft9/install/update_appstore.sh")
  87. shell_execute.execute_command_output_all("bash /tmp/update_appstore.sh 1>/dev/null 2>&1")
  88. return content
  89. else:
  90. return None
  91. # 获取 update info
  92. def get_update_list():
  93. local_path = '/data/apps/websoft9/install/version.json'
  94. repo = 'websoft9'
  95. local_version = "0"
  96. try:
  97. op = shell_execute.execute_command_output_all("cat " + local_path)['result']
  98. local_version = json.loads(op)['VERSION']
  99. except:
  100. local_version = "0.0.1"
  101. version_contents = get_github_content(repo, 'install/version.json')
  102. version = json.loads(version_contents)['VERSION']
  103. ret = {}
  104. ret['current_version'] = local_version
  105. if compared_version(local_version, version) == -1:
  106. content = []
  107. change_log_contents = get_github_content(repo, 'CHANGELOG.md')
  108. change_log = change_log_contents.split('## ')[1].split('\n')
  109. date = change_log[0].split()[-1]
  110. for change in change_log[1:]:
  111. if change != '':
  112. content.append(change)
  113. ret2= {}
  114. ret2['latest_version'] = version
  115. ret2['date'] = date
  116. ret2['content'] = content
  117. ret['Update_content']=ret2
  118. return ret
  119. else:
  120. ret['Update_content']=None
  121. return ret
  122. def conbine_list(installing_list, installed_list):
  123. app_list = installing_list + installed_list
  124. result_list = []
  125. appid_list = []
  126. for app in app_list:
  127. app_id = app['app_id']
  128. if app_id in appid_list:
  129. continue
  130. else:
  131. appid_list.append(app_id)
  132. result_list.append(app)
  133. return result_list
  134. # 获取所有app的信息
  135. def get_my_app(app_id):
  136. installed_list = get_apps_from_compose()
  137. installing_list = get_apps_from_queue()
  138. app_list = conbine_list(installing_list, installed_list)
  139. find = False
  140. ret = {}
  141. if app_id != None:
  142. for app in app_list:
  143. if app_id == app['app_id']:
  144. ret = app
  145. find = True
  146. break
  147. if not find:
  148. raise CommandException(const.ERROR_CLIENT_PARAM_NOTEXIST, "This App doesn't exist!", "")
  149. else:
  150. ret = app_list
  151. myLogger.info_logger("app list result ok")
  152. return ret
  153. # 获取具体某个app的信息
  154. def get_app_status(app_id):
  155. code, message = docker.check_app_id(app_id)
  156. if code == None:
  157. app = get_my_app(app_id)
  158. # 将app_list 过滤出app_id的app,并缩减信息,使其符合文档的要求
  159. ret = {}
  160. ret['app_id'] = app['app_id']
  161. ret['status'] = app['status']
  162. ret['status_reason'] = app['status_reason']
  163. else:
  164. raise CommandException(code, message, '')
  165. return ret
  166. def install_app(app_name, customer_name, app_version):
  167. myLogger.info_logger("Install app ...")
  168. ret = {}
  169. ret['ResponseData'] = {}
  170. app_id = app_name + "_" + customer_name
  171. ret['ResponseData']['app_id'] = app_id
  172. code, message = check_app(app_name, customer_name, app_version)
  173. if code == None:
  174. q.enqueue(install_app_delay, app_name, customer_name, app_version, job_id=app_id)
  175. else:
  176. ret['Error'] = get_error_info(code, message, "")
  177. return ret
  178. def start_app(app_id):
  179. info, flag = app_exits_in_docker(app_id)
  180. if flag:
  181. app_path = info.split()[-1].rsplit('/', 1)[0]
  182. cmd = "docker compose -f " + app_path + "/docker-compose.yml start"
  183. shell_execute.execute_command_output_all(cmd)
  184. else:
  185. raise CommandException(const.ERROR_CLIENT_PARAM_NOTEXIST, "APP is not exist", "")
  186. def stop_app(app_id):
  187. info, flag = app_exits_in_docker(app_id)
  188. if flag:
  189. app_path = info.split()[-1].rsplit('/', 1)[0]
  190. cmd = "docker compose -f " + app_path + "/docker-compose.yml stop"
  191. shell_execute.execute_command_output_all(cmd)
  192. else:
  193. raise CommandException(const.ERROR_CLIENT_PARAM_NOTEXIST, "APP is not exist", "")
  194. def restart_app(app_id):
  195. code, message = docker.check_app_id(app_id)
  196. if code == None:
  197. info, flag = app_exits_in_docker(app_id)
  198. if flag:
  199. app_path = info.split()[-1].rsplit('/', 1)[0]
  200. cmd = "docker compose -f " + app_path + "/docker-compose.yml restart"
  201. shell_execute.execute_command_output_all(cmd)
  202. else:
  203. raise CommandException(const.ERROR_CLIENT_PARAM_NOTEXIST, "APP is not exist", "")
  204. else:
  205. raise CommandException(code, message, "")
  206. def delete_app_failedjob(job_id):
  207. myLogger.info_logger("delete_app_failedjob")
  208. failed = FailedJobRegistry(queue=q)
  209. failed.remove(job_id, delete_job=True)
  210. def delete_app(app_id):
  211. try:
  212. app_name = app_id.split('_')[0]
  213. customer_name = app_id.split('_')[1]
  214. app_path = ""
  215. info, code_exist = app_exits_in_docker(app_id)
  216. if code_exist:
  217. app_path = info.split()[-1].rsplit('/', 1)[0]
  218. cmd = "docker compose -f " + app_path + "/docker-compose.yml down -v"
  219. lib_path = '/data/library/apps/' + app_name
  220. if app_path != lib_path:
  221. cmd = cmd + " && sudo rm -rf " + app_path
  222. try:
  223. myLogger.info_logger("Intall fail, down app and delete files")
  224. shell_execute.execute_command_output_all(cmd)
  225. except Exception:
  226. myLogger.info_logger("Delete app compose exception")
  227. # 强制删除失败又无法通过docker compose down 删除的容器
  228. try:
  229. myLogger.info_logger("IF delete fail, force to delete containers")
  230. force_cmd = "docker rm -f $(docker ps -f name=^" + customer_name + " -aq)"
  231. shell_execute.execute_command_output_all(force_cmd)
  232. except Exception:
  233. myLogger.info_logger("force delete app compose exception")
  234. else:
  235. if check_app_rq(app_id):
  236. delete_app_failedjob(app_id)
  237. else:
  238. raise CommandException(const.ERROR_CLIENT_PARAM_NOTEXIST, "AppID is not exist", "")
  239. cmd = " sudo rm -rf /data/apps/" + customer_name
  240. shell_execute.execute_command_output_all(cmd)
  241. except CommandException as ce:
  242. myLogger.info_logger("Delete app compose exception")
  243. def uninstall_app(app_id):
  244. app_name = app_id.split('_')[0]
  245. customer_name = app_id.split('_')[1]
  246. app_path = ""
  247. info, code_exist = app_exits_in_docker(app_id)
  248. if code_exist:
  249. app_path = info.split()[-1].rsplit('/', 1)[0]
  250. cmd = "docker compose -f " + app_path + "/docker-compose.yml down -v"
  251. lib_path = '/data/library/apps/' + app_name
  252. if app_path != lib_path:
  253. cmd = cmd + " && sudo rm -rf " + app_path
  254. shell_execute.execute_command_output_all(cmd)
  255. else:
  256. if check_app_rq(app_id):
  257. delete_app_failedjob(app_id)
  258. else:
  259. raise CommandException(const.ERROR_CLIENT_PARAM_NOTEXIST, "AppID is not exist", "")
  260. # Force to delete docker compose
  261. try:
  262. cmd = " sudo rm -rf /data/apps/" + customer_name
  263. shell_execute.execute_command_output_all(cmd)
  264. except CommandException as ce:
  265. myLogger.info_logger("Delete app compose exception")
  266. # Delete proxy config when uninstall app
  267. app_proxy_delete(app_id)
  268. def check_app(app_name, customer_name, app_version):
  269. message = ""
  270. code = None
  271. app_id = app_name + "_" + customer_name
  272. if app_name == None:
  273. code = const.ERROR_CLIENT_PARAM_BLANK
  274. message = "app_name is null"
  275. elif customer_name == None:
  276. code = const.ERROR_CLIENT_PARAM_BLANK
  277. message = "customer_name is null"
  278. elif len(customer_name) < 2:
  279. code = const.ERROR_CLIENT_PARAM_BLANK
  280. message = "customer_name must be longer than 2 chars"
  281. elif app_version == None:
  282. code = const.ERROR_CLIENT_PARAM_BLANK
  283. message = "app_version is null"
  284. elif app_version == "undefined" or app_version == "":
  285. code = const.ERROR_CLIENT_PARAM_BLANK
  286. message = "app_version is null"
  287. elif not docker.check_app_websoft9(app_name):
  288. code = const.ERROR_CLIENT_PARAM_NOTEXIST
  289. message = "It is not support to install " + app_name
  290. elif re.match('^[a-z0-9]+$', customer_name) == None:
  291. code = const.ERROR_CLIENT_PARAM_Format
  292. message = "APP name can only be composed of numbers and lowercase letters"
  293. elif docker.check_directory("/data/apps/" + customer_name):
  294. code = const.ERROR_CLIENT_PARAM_REPEAT
  295. message = "Repeat installation: " + customer_name
  296. elif not docker.check_vm_resource(app_name):
  297. code = const.ERROR_SERVER_RESOURCE
  298. message = "Insufficient system resources (cpu, memory, disk space)"
  299. elif check_app_docker(app_id):
  300. code = const.ERROR_CLIENT_PARAM_REPEAT
  301. message = "Repeat installation: " + customer_name
  302. elif check_app_rq(app_id):
  303. code = const.ERROR_CLIENT_PARAM_REPEAT
  304. message = "Repeat installation: " + customer_name
  305. return code, message
  306. def prepare_app(app_name, customer_name):
  307. library_path = "/data/library/apps/" + app_name
  308. install_path = "/data/apps/" + customer_name
  309. shell_execute.execute_command_output_all("cp -r " + library_path + " " + install_path)
  310. def install_app_delay(app_name, customer_name, app_version):
  311. myLogger.info_logger("-------RQ install start --------")
  312. job_id = app_name + "_" + customer_name
  313. try:
  314. # 因为这个时候还没有复制文件夹,是从/data/library里面文件读取json来检查的,应该是app_name,而不是customer_name
  315. resource_flag = docker.check_vm_resource(app_name)
  316. if resource_flag == True:
  317. myLogger.info_logger("job check ok, continue to install app")
  318. env_path = "/data/apps/" + customer_name + "/.env"
  319. # prepare_app(app_name, customer_name)
  320. docker.check_app_compose(app_name, customer_name)
  321. myLogger.info_logger("start JobID=" + job_id)
  322. docker.modify_env(env_path, 'APP_NAME', customer_name)
  323. docker.modify_env(env_path, "APP_VERSION", app_version)
  324. docker.check_app_url(customer_name)
  325. cmd = "cd /data/apps/" + customer_name + " && sudo docker compose pull && sudo docker compose up -d"
  326. output = shell_execute.execute_command_output_all(cmd)
  327. myLogger.info_logger("-------Install result--------")
  328. myLogger.info_logger(output["code"])
  329. myLogger.info_logger(output["result"])
  330. try:
  331. shell_execute.execute_command_output_all("bash /data/apps/" + customer_name + "/src/after_up.sh")
  332. except Exception as e:
  333. myLogger.info_logger(str(e))
  334. else:
  335. error_info = "##websoft9##" + const.ERROR_SERVER_RESOURCE + "##websoft9##" + "Insufficient system resources (cpu, memory, disk space)" + "##websoft9##" + "Insufficient system resources (cpu, memory, disk space)"
  336. myLogger.info_logger(error_info)
  337. raise Exception(error_info)
  338. except CommandException as ce:
  339. myLogger.info_logger(customer_name + " install failed(docker)!")
  340. delete_app(job_id)
  341. error_info = "##websoft9##" + ce.code + "##websoft9##" + ce.message + "##websoft9##" + ce.detail
  342. myLogger.info_logger(error_info)
  343. raise Exception(error_info)
  344. except Exception as e:
  345. myLogger.info_logger(customer_name + " install failed(system)!")
  346. delete_app(job_id)
  347. error_info = "##websoft9##" + const.ERROR_SERVER_SYSTEM + "##websoft9##" + 'system original error' + "##websoft9##" + str(
  348. e)
  349. myLogger.info_logger(error_info)
  350. raise Exception(error_info)
  351. def app_exits_in_docker(app_id):
  352. customer_name = app_id.split('_')[1]
  353. app_name = app_id.split('_')[0]
  354. flag = False
  355. info = ""
  356. cmd = "docker compose ls -a | grep \'/" + customer_name + "/\'"
  357. try:
  358. output = shell_execute.execute_command_output_all(cmd)
  359. if int(output["code"]) == 0:
  360. info = output["result"]
  361. app_path = info.split()[-1].rsplit('/', 1)[0]
  362. is_official = check_if_official_app(app_path + '/variables.json')
  363. if is_official:
  364. name = docker.read_var(app_path + '/variables.json', 'name')
  365. if name == app_name:
  366. flag = True
  367. elif app_name == customer_name:
  368. flag = True
  369. myLogger.info_logger("APP in docker")
  370. except CommandException as ce:
  371. myLogger.info_logger("APP not in docker")
  372. return info, flag
  373. def split_app_id(app_id):
  374. return app_id.split("_")[1]
  375. def get_createtime(official_app, app_path, customer_name):
  376. data_time = ""
  377. try:
  378. if official_app:
  379. cmd = "docker ps -f name=" + customer_name + " --format {{.RunningFor}} | head -n 1"
  380. result = shell_execute.execute_command_output_all(cmd)["result"].rstrip('\n')
  381. data_time = result
  382. else:
  383. cmd_all = "cd " + app_path + " && docker compose ps -a --format json"
  384. output = shell_execute.execute_command_output_all(cmd_all)
  385. container_name = json.loads(output["result"])[0]["Name"]
  386. cmd = "docker ps -f name=" + container_name + " --format {{.RunningFor}} | head -n 1"
  387. result = shell_execute.execute_command_output_all(cmd)["result"].rstrip('\n')
  388. data_time = result
  389. except Exception as e:
  390. myLogger.info_logger(str(e))
  391. myLogger.info_logger("get_createtime get success" + data_time)
  392. return data_time
  393. def get_apps_from_compose():
  394. myLogger.info_logger("Search all of apps ...")
  395. cmd = "docker compose ls -a --format json"
  396. output = shell_execute.execute_command_output_all(cmd)
  397. output_list = json.loads(output["result"])
  398. myLogger.info_logger(len(output_list))
  399. ip = "localhost"
  400. try:
  401. ip_result = shell_execute.execute_command_output_all("cat /data/apps/w9services/w9appmanage/public_ip")
  402. ip = ip_result["result"].rstrip('\n')
  403. except Exception:
  404. ip = "127.0.0.1"
  405. app_list = []
  406. for app_info in output_list:
  407. volume = app_info["ConfigFiles"]
  408. app_path = volume.rsplit('/', 1)[0]
  409. customer_name = volume.split('/')[-2]
  410. app_id = ""
  411. app_name = ""
  412. trade_mark = ""
  413. port = 0
  414. url = ""
  415. admin_url = ""
  416. image_url = ""
  417. user_name = ""
  418. password = ""
  419. official_app = False
  420. app_version = ""
  421. create_time = ""
  422. volume_data = ""
  423. config_path = app_path
  424. app_https = False
  425. app_replace_url = False
  426. default_domain = ""
  427. admin_path = ""
  428. admin_domain_url = ""
  429. if customer_name in ['w9appmanage', 'w9nginxproxymanager', 'w9redis', 'w9kopia',
  430. 'w9portainer'] or app_path == '/data/apps/w9services/' + customer_name:
  431. continue
  432. var_path = app_path + "/variables.json"
  433. official_app = check_if_official_app(var_path)
  434. status_show = app_info["Status"]
  435. status = app_info["Status"].split("(")[0]
  436. if status == "running" or status == "exited" or status == "restarting":
  437. if "exited" in status_show and "running" in status_show:
  438. if status == "exited":
  439. cmd = "docker ps -a -f name=" + customer_name + " --format {{.Names}}#{{.Status}}|grep Exited"
  440. result = shell_execute.execute_command_output_all(cmd)["result"].rstrip('\n')
  441. container = result.split("#Exited")[0]
  442. if container != customer_name:
  443. status = "running"
  444. if "restarting" in status_show:
  445. about_time = get_createtime(official_app, app_path, customer_name)
  446. if "seconds" in about_time:
  447. status = "restarting"
  448. else:
  449. status = "failed"
  450. elif status == "created":
  451. status = "failed"
  452. else:
  453. continue
  454. if official_app:
  455. app_name = docker.read_var(var_path, 'name')
  456. app_id = app_name + "_" + customer_name # app_id
  457. # get trade_mark
  458. trade_mark = docker.read_var(var_path, 'trademark')
  459. image_url = get_Image_url(app_name)
  460. # get env info
  461. path = app_path + "/.env"
  462. env_map = docker.get_map(path)
  463. try:
  464. myLogger.info_logger("get domain for APP_URL")
  465. domain = env_map.get("APP_URL")
  466. if "appname.example.com" in domain or ip in domain:
  467. default_domain = ""
  468. else:
  469. default_domain = domain
  470. except Exception:
  471. myLogger.info_logger("domain exception")
  472. try:
  473. app_version = env_map.get("APP_VERSION")
  474. volume_data = "/data/apps/" + customer_name + "/data"
  475. user_name = env_map.get("APP_USER", "")
  476. password = env_map.get("POWER_PASSWORD", "")
  477. admin_path = env_map.get("APP_ADMIN_PATH")
  478. if admin_path:
  479. myLogger.info_logger(admin_path)
  480. admin_path = admin_path.replace("\"", "")
  481. else:
  482. admin_path = ""
  483. if default_domain != "" and admin_path != "":
  484. admin_domain_url = "http://" + default_domain + admin_path
  485. except Exception:
  486. myLogger.info_logger("APP_USER POWER_PASSWORD exception")
  487. try:
  488. replace = env_map.get("APP_URL_REPLACE", "false")
  489. myLogger.info_logger("replace=" + replace)
  490. if replace == "true":
  491. app_replace_url = True
  492. https = env_map.get("APP_HTTPS_ACCESS", "false")
  493. if https == "true":
  494. app_https = True
  495. except Exception:
  496. myLogger.info_logger("APP_HTTPS_ACCESS exception")
  497. try:
  498. http_port = env_map.get("APP_HTTP_PORT", "0")
  499. if http_port:
  500. port = int(http_port)
  501. except Exception:
  502. pass
  503. if port != 0:
  504. try:
  505. if app_https:
  506. easy_url = "https://" + ip + ":" + str(port)
  507. else:
  508. easy_url = "http://" + ip + ":" + str(port)
  509. url = easy_url
  510. admin_url = get_admin_url(customer_name, url)
  511. except Exception:
  512. pass
  513. else:
  514. try:
  515. db_port = list(docker.read_env(path, "APP_DB.*_PORT").values())[0]
  516. port = int(db_port)
  517. except Exception:
  518. pass
  519. else:
  520. app_name = customer_name
  521. app_id = customer_name + "_" + customer_name
  522. create_time = get_createtime(official_app, app_path, customer_name)
  523. if status in ['running', 'exited']:
  524. config = Config(port=port, compose_file=volume, url=url, admin_url=admin_url,
  525. admin_domain_url=admin_domain_url,
  526. admin_path=admin_path, admin_username=user_name, admin_password=password,
  527. default_domain=default_domain)
  528. else:
  529. config = None
  530. if status == "failed":
  531. status_reason = StatusReason(Code=const.ERROR_SERVER_SYSTEM, Message="system original error",
  532. Detail="unknown error")
  533. else:
  534. status_reason = None
  535. app = App(app_id=app_id, app_name=app_name, customer_name=customer_name, trade_mark=trade_mark,
  536. app_version=app_version, create_time=create_time, volume_data=volume_data, config_path=config_path,
  537. status=status, status_reason=status_reason, official_app=official_app, image_url=image_url,
  538. app_https=app_https, app_replace_url=app_replace_url, config=config)
  539. app_list.append(app.dict())
  540. return app_list
  541. def check_if_official_app(var_path):
  542. if docker.check_directory(var_path):
  543. if docker.read_var(var_path, 'name') != "" and docker.read_var(var_path, 'trademark') != "" and docker.read_var(
  544. var_path, 'requirements') != "":
  545. requirements = docker.read_var(var_path, 'requirements')
  546. try:
  547. cpu = requirements['cpu']
  548. mem = requirements['memory']
  549. disk = requirements['disk']
  550. return True
  551. except KeyError:
  552. return False
  553. else:
  554. return False
  555. def check_app_docker(app_id):
  556. customer_name = app_id.split('_')[1]
  557. app_name = app_id.split('_')[0]
  558. flag = False
  559. cmd = "docker compose ls -a | grep \'/" + customer_name + "/\'"
  560. try:
  561. shell_execute.execute_command_output_all(cmd)
  562. flag = True
  563. myLogger.info_logger("APP in docker")
  564. except CommandException as ce:
  565. myLogger.info_logger("APP not in docker")
  566. return flag
  567. def check_app_rq(app_id):
  568. myLogger.info_logger("check_app_rq")
  569. started = StartedJobRegistry(queue=q)
  570. failed = FailedJobRegistry(queue=q)
  571. run_job_ids = started.get_job_ids()
  572. failed_job_ids = failed.get_job_ids()
  573. queue_job_ids = q.job_ids
  574. myLogger.info_logger(queue_job_ids)
  575. myLogger.info_logger(run_job_ids)
  576. myLogger.info_logger(failed_job_ids)
  577. if queue_job_ids and app_id in queue_job_ids:
  578. myLogger.info_logger("App in RQ")
  579. return True
  580. if failed_job_ids and app_id in failed_job_ids:
  581. myLogger.info_logger("App in RQ")
  582. return True
  583. if run_job_ids and app_id in run_job_ids:
  584. myLogger.info_logger("App in RQ")
  585. return True
  586. myLogger.info_logger("App not in RQ")
  587. return False
  588. def get_apps_from_queue():
  589. myLogger.info_logger("get queque apps...")
  590. # 获取 StartedJobRegistry 实例
  591. started = StartedJobRegistry(queue=q)
  592. finish = FinishedJobRegistry(queue=q)
  593. deferred = DeferredJobRegistry(queue=q)
  594. failed = FailedJobRegistry(queue=q)
  595. scheduled = ScheduledJobRegistry(queue=q)
  596. cancel = CanceledJobRegistry(queue=q)
  597. # 获取正在执行的作业 ID 列表
  598. run_job_ids = started.get_job_ids()
  599. finish_job_ids = finish.get_job_ids()
  600. wait_job_ids = deferred.get_job_ids()
  601. failed_jobs = failed.get_job_ids()
  602. scheduled_jobs = scheduled.get_job_ids()
  603. cancel_jobs = cancel.get_job_ids()
  604. myLogger.info_logger(q.jobs)
  605. myLogger.info_logger(run_job_ids)
  606. myLogger.info_logger(failed_jobs)
  607. myLogger.info_logger(cancel_jobs)
  608. myLogger.info_logger(wait_job_ids)
  609. myLogger.info_logger(finish_job_ids)
  610. myLogger.info_logger(scheduled_jobs)
  611. installing_list = []
  612. for job_id in run_job_ids:
  613. app = get_rq_app(job_id, 'installing', "", "", "")
  614. installing_list.append(app)
  615. for job in q.jobs:
  616. app = get_rq_app(job.id, 'installing', "", "", "")
  617. installing_list.append(app)
  618. for job_id in failed_jobs:
  619. job = q.fetch_job(job_id)
  620. exc_info = job.exc_info
  621. code = exc_info.split('##websoft9##')[1]
  622. message = exc_info.split('##websoft9##')[2]
  623. detail = exc_info.split('##websoft9##')[3]
  624. app = get_rq_app(job_id, 'failed', code, message, detail)
  625. installing_list.append(app)
  626. return installing_list
  627. def get_rq_app(id, status, code, message, detail):
  628. app_name = id.split('_')[0]
  629. customer_name = id.split('_')[1]
  630. # 当app还在RQ时,可能文件夹还没创建,无法获取trade_mark
  631. trade_mark = ""
  632. app_version = ""
  633. create_time = ""
  634. volume_data = ""
  635. config_path = ""
  636. image_url = get_Image_url(app_name)
  637. config = None
  638. if status == "installing":
  639. status_reason = None
  640. else:
  641. status_reason = StatusReason(Code=code, Message=message, Detail=detail)
  642. app = App(app_id=id, app_name=app_name, customer_name=customer_name, trade_mark=trade_mark,
  643. app_version=app_version, create_time=create_time, volume_data=volume_data, config_path=config_path,
  644. status=status, status_reason=status_reason, official_app=True, image_url=image_url,
  645. app_https=False, app_replace_url=False, config=config)
  646. return app.dict()
  647. def get_Image_url(app_name):
  648. image_url = "static/images/" + app_name + "-websoft9.png"
  649. return image_url
  650. def get_url(app_name, easy_url):
  651. url = easy_url
  652. return url
  653. def get_admin_url(customer_name, url):
  654. admin_url = ""
  655. path = "/data/apps/" + customer_name + "/.env"
  656. try:
  657. admin_path = list(docker.read_env(path, "APP_ADMIN_PATH").values())[0]
  658. admin_path = admin_path.replace("\"", "")
  659. admin_url = url + admin_path
  660. except IndexError:
  661. pass
  662. return admin_url
  663. def get_error_info(code, message, detail):
  664. error = {}
  665. error['Code'] = code
  666. error['Message'] = message
  667. error['Detail'] = detail
  668. return error
  669. def app_domain_list(app_id):
  670. code, message = docker.check_app_id(app_id)
  671. if code == None:
  672. info, flag = app_exits_in_docker(app_id)
  673. if flag:
  674. myLogger.info_logger("Check app_id ok[app_domain_list]")
  675. else:
  676. raise CommandException(const.ERROR_CLIENT_PARAM_NOTEXIST, "APP is not exist", "")
  677. else:
  678. raise CommandException(code, message, "")
  679. domains = get_all_domains(app_id)
  680. myLogger.info_logger(domains)
  681. ret = {}
  682. ret['domains'] = domains
  683. default_domain = ""
  684. if domains != None and len(domains) > 0:
  685. customer_name = app_id.split('_')[1]
  686. app_url = shell_execute.execute_command_output_all("cat /data/apps/" + customer_name + "/.env")["result"]
  687. if "APP_URL" in app_url:
  688. url = shell_execute.execute_command_output_all("cat /data/apps/" + customer_name + "/.env |grep APP_URL=")[
  689. "result"].rstrip('\n')
  690. default_domain = url.split('=')[1]
  691. ret['default_domain'] = default_domain
  692. myLogger.info_logger(ret)
  693. return ret
  694. def app_proxy_delete(app_id):
  695. customer_name = app_id.split('_')[1]
  696. proxy_host = None
  697. token = get_token()
  698. url = const.NGINX_URL+"/api/nginx/proxy-hosts"
  699. headers = {
  700. 'Authorization': token,
  701. 'Content-Type': 'application/json'
  702. }
  703. response = requests.get(url, headers=headers)
  704. for proxy in response.json():
  705. portainer_name = proxy["forward_host"]
  706. if customer_name == portainer_name:
  707. proxy_id = proxy["id"]
  708. token = get_token()
  709. url = const.NGINX_URL+"/api/nginx/proxy-hosts/" + str(proxy_id)
  710. headers = {
  711. 'Authorization': token,
  712. 'Content-Type': 'application/json'
  713. }
  714. response = requests.delete(url, headers=headers)
  715. def app_domain_delete(app_id, domain):
  716. code, message = docker.check_app_id(app_id)
  717. if code == None:
  718. info, flag = app_exits_in_docker(app_id)
  719. if flag:
  720. myLogger.info_logger("Check app_id ok[app_domain_delete]")
  721. else:
  722. raise CommandException(const.ERROR_CLIENT_PARAM_NOTEXIST, "APP is not exist", "")
  723. else:
  724. raise CommandException(code, message, "")
  725. if domain is None or domain == "undefined":
  726. raise CommandException(const.ERROR_CLIENT_PARAM_BLANK, "Domains is blank", "")
  727. old_all_domains = get_all_domains(app_id)
  728. if domain not in old_all_domains:
  729. myLogger.info_logger("delete domain is not binded")
  730. raise CommandException(const.ERROR_CLIENT_PARAM_NOTEXIST, "Domain is not bind.", "")
  731. myLogger.info_logger("Start to delete " + domain)
  732. proxy = get_proxy_domain(app_id, domain)
  733. if proxy != None:
  734. myLogger.info_logger(proxy)
  735. myLogger.info_logger("before update")
  736. domains_old = proxy["domain_names"]
  737. myLogger.info_logger(domains_old)
  738. domains_old.remove(domain)
  739. myLogger.info_logger("after update")
  740. myLogger.info_logger(domains_old)
  741. if len(domains_old) == 0:
  742. proxy_id = proxy["id"]
  743. token = get_token()
  744. url = const.NGINX_URL+"/api/nginx/proxy-hosts/" + str(proxy_id)
  745. headers = {
  746. 'Authorization': token,
  747. 'Content-Type': 'application/json'
  748. }
  749. response = requests.delete(url, headers=headers)
  750. try:
  751. if response.json().get("error"):
  752. raise CommandException(const.ERROR_CONFIG_NGINX, response.json().get("error").get("message"), "")
  753. except Exception:
  754. myLogger.info_logger(response.json())
  755. set_domain("", app_id)
  756. else:
  757. proxy_id = proxy["id"]
  758. token = get_token()
  759. url = const.NGINX_URL+"/api/nginx/proxy-hosts/" + str(proxy_id)
  760. headers = {
  761. 'Authorization': token,
  762. 'Content-Type': 'application/json'
  763. }
  764. port = get_container_port(app_id.split('_')[1])
  765. host = app_id.split('_')[1]
  766. data = {
  767. "domain_names": domains_old,
  768. "forward_scheme": "http",
  769. "forward_host": host,
  770. "forward_port": port,
  771. "access_list_id": "0",
  772. "certificate_id": 0,
  773. "meta": {
  774. "letsencrypt_agree": False,
  775. "dns_challenge": False
  776. },
  777. "advanced_config": "",
  778. "locations": [],
  779. "block_exploits": False,
  780. "caching_enabled": False,
  781. "allow_websocket_upgrade": False,
  782. "http2_support": False,
  783. "hsts_enabled": False,
  784. "hsts_subdomains": False,
  785. "ssl_forced": False
  786. }
  787. response = requests.put(url, data=json.dumps(data), headers=headers)
  788. if response.json().get("error"):
  789. raise CommandException(const.ERROR_CONFIG_NGINX, response.json().get("error").get("message"), "")
  790. domain_set = app_domain_list(app_id)
  791. default_domain = domain_set['default_domain']
  792. # 如果被删除的域名是默认域名,删除后去剩下域名的第一个
  793. if default_domain == domain:
  794. set_domain(domains_old[0], app_id)
  795. else:
  796. raise CommandException(const.ERROR_CLIENT_PARAM_NOTEXIST, "Delete domain is not bind", "")
  797. def app_domain_update(app_id, domain_old, domain_new):
  798. myLogger.info_logger("app_domain_update")
  799. domain_list = []
  800. domain_list.append(domain_old)
  801. domain_list.append(domain_new)
  802. check_domains(domain_list)
  803. code, message = docker.check_app_id(app_id)
  804. if code == None:
  805. info, flag = app_exits_in_docker(app_id)
  806. if flag:
  807. myLogger.info_logger("Check app_id ok")
  808. else:
  809. raise CommandException(const.ERROR_CLIENT_PARAM_NOTEXIST, "APP is not exist", "")
  810. else:
  811. raise CommandException(code, message, "")
  812. proxy = get_proxy_domain(app_id, domain_old)
  813. if proxy != None:
  814. domains_old = proxy["domain_names"]
  815. index = domains_old.index(domain_old)
  816. domains_old[index] = domain_new
  817. proxy_id = proxy["id"]
  818. token = get_token()
  819. url = const.NGINX_URL+"/api/nginx/proxy-hosts/" + str(proxy_id)
  820. headers = {
  821. 'Authorization': token,
  822. 'Content-Type': 'application/json'
  823. }
  824. port = get_container_port(app_id.split('_')[1])
  825. host = app_id.split('_')[1]
  826. data = {
  827. "domain_names": domains_old,
  828. "forward_scheme": "http",
  829. "forward_host": host,
  830. "forward_port": port,
  831. "access_list_id": "0",
  832. "certificate_id": 0,
  833. "meta": {
  834. "letsencrypt_agree": False,
  835. "dns_challenge": False
  836. },
  837. "advanced_config": "",
  838. "locations": [],
  839. "block_exploits": False,
  840. "caching_enabled": False,
  841. "allow_websocket_upgrade": False,
  842. "http2_support": False,
  843. "hsts_enabled": False,
  844. "hsts_subdomains": False,
  845. "ssl_forced": False
  846. }
  847. response = requests.put(url, data=json.dumps(data), headers=headers)
  848. if response.json().get("error"):
  849. raise CommandException(const.ERROR_CONFIG_NGINX, response.json().get("error").get("message"), "")
  850. domain_set = app_domain_list(app_id)
  851. default_domain = domain_set['default_domain']
  852. myLogger.info_logger("default_domain=" + default_domain + ",domain_old=" + domain_old)
  853. # 如果被修改的域名是默认域名,修改后也设置为默认域名
  854. if default_domain == domain_old:
  855. set_domain(domain_new, app_id)
  856. else:
  857. raise CommandException(const.ERROR_CLIENT_PARAM_NOTEXIST, "edit domain is not exist", "")
  858. def app_domain_add(app_id, domain):
  859. temp_domains = []
  860. temp_domains.append(domain)
  861. check_domains(temp_domains)
  862. code, message = docker.check_app_id(app_id)
  863. if code == None:
  864. info, flag = app_exits_in_docker(app_id)
  865. if flag:
  866. myLogger.info_logger("Check app_id ok")
  867. else:
  868. raise CommandException(const.ERROR_CLIENT_PARAM_NOTEXIST, "APP is not exist", "")
  869. else:
  870. raise CommandException(code, message, "")
  871. old_domains = get_all_domains(app_id)
  872. if domain in old_domains:
  873. raise CommandException(const.ERROR_CLIENT_PARAM_NOTEXIST, "Domain is in use", "")
  874. proxy = get_proxy(app_id)
  875. if proxy != None:
  876. domains_old = proxy["domain_names"]
  877. domain_list = domains_old
  878. domain_list.append(domain)
  879. proxy_id = proxy["id"]
  880. token = get_token()
  881. url = const.NGINX_URL+"/api/nginx/proxy-hosts/" + str(proxy_id)
  882. headers = {
  883. 'Authorization': token,
  884. 'Content-Type': 'application/json'
  885. }
  886. port = get_container_port(app_id.split('_')[1])
  887. host = app_id.split('_')[1]
  888. data = {
  889. "domain_names": domain_list,
  890. "forward_scheme": "http",
  891. "forward_host": host,
  892. "forward_port": port,
  893. "access_list_id": "0",
  894. "certificate_id": 0,
  895. "meta": {
  896. "letsencrypt_agree": False,
  897. "dns_challenge": False
  898. },
  899. "advanced_config": "",
  900. "locations": [],
  901. "block_exploits": False,
  902. "caching_enabled": False,
  903. "allow_websocket_upgrade": False,
  904. "http2_support": False,
  905. "hsts_enabled": False,
  906. "hsts_subdomains": False,
  907. "ssl_forced": False
  908. }
  909. response = requests.put(url, data=json.dumps(data), headers=headers)
  910. if response.json().get("error"):
  911. raise CommandException(const.ERROR_CONFIG_NGINX, response.json().get("error").get("message"), "")
  912. else:
  913. # 追加
  914. token = get_token()
  915. url = const.NGINX_URL+"/api/nginx/proxy-hosts"
  916. headers = {
  917. 'Authorization': token,
  918. 'Content-Type': 'application/json'
  919. }
  920. port = get_container_port(app_id.split('_')[1])
  921. host = app_id.split('_')[1]
  922. data = {
  923. "domain_names": temp_domains,
  924. "forward_scheme": "http",
  925. "forward_host": host,
  926. "forward_port": port,
  927. "access_list_id": "0",
  928. "certificate_id": 0,
  929. "meta": {
  930. "letsencrypt_agree": False,
  931. "dns_challenge": False
  932. },
  933. "advanced_config": "",
  934. "locations": [],
  935. "block_exploits": False,
  936. "caching_enabled": False,
  937. "allow_websocket_upgrade": False,
  938. "http2_support": False,
  939. "hsts_enabled": False,
  940. "hsts_subdomains": False,
  941. "ssl_forced": False
  942. }
  943. response = requests.post(url, data=json.dumps(data), headers=headers)
  944. if response.json().get("error"):
  945. raise CommandException(const.ERROR_CONFIG_NGINX, response.json().get("error").get("message"), "")
  946. set_domain(domain, app_id)
  947. return domain
  948. def check_domains(domains):
  949. myLogger.info_logger(domains)
  950. if domains is None or len(domains) == 0:
  951. raise CommandException(const.ERROR_CLIENT_PARAM_BLANK, "Domains is blank", "")
  952. else:
  953. for domain in domains:
  954. if is_valid_domain(domain):
  955. if check_real_domain(domain) == False:
  956. raise CommandException(const.ERROR_CLIENT_PARAM_NOTEXIST, "Domain and server not match", "")
  957. else:
  958. raise CommandException(const.ERROR_CLIENT_PARAM_Format, "Domains format error", "")
  959. def is_valid_domain(domain):
  960. if domain.startswith("http"):
  961. return False
  962. return True
  963. def check_real_domain(domain):
  964. domain_real = True
  965. try:
  966. cmd = "ping -c 1 " + domain + " | grep -Eo '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | uniq"
  967. domain_ip = shell_execute.execute_command_output_all(cmd)["result"].rstrip('\n')
  968. ip_result = shell_execute.execute_command_output_all("cat /data/apps/w9services/w9appmanage/public_ip")
  969. ip_save = ip_result["result"].rstrip('\n')
  970. if domain_ip == ip_save:
  971. myLogger.info_logger("Domain check ok!")
  972. else:
  973. domain_real = False
  974. except CommandException as ce:
  975. domain_real = False
  976. return domain_real
  977. def get_token():
  978. url = const.NGINX_URL+"/api/tokens"
  979. headers = {'Content-type': 'application/json'}
  980. password = db.AppSearchUsers("nginx").get("password")
  981. myLogger.info_logger("token_password: " + password)
  982. param = {
  983. "identity": "help@websoft9.com",
  984. "scope": "user",
  985. "secret": password
  986. }
  987. response = requests.post(url, data=json.dumps(param), headers=headers)
  988. nginx_token = response.json()
  989. myLogger.info_logger(nginx_token)
  990. token = "Bearer " + response.json()["token"]
  991. return token
  992. def get_proxy(app_id):
  993. customer_name = app_id.split('_')[1]
  994. proxy_host = None
  995. token = get_token()
  996. url = const.NGINX_URL+"/api/nginx/proxy-hosts"
  997. headers = {
  998. 'Authorization': token,
  999. 'Content-Type': 'application/json'
  1000. }
  1001. response = requests.get(url, headers=headers)
  1002. for proxy in response.json():
  1003. portainer_name = proxy["forward_host"]
  1004. if customer_name == portainer_name:
  1005. proxy_host = proxy
  1006. break
  1007. return proxy_host
  1008. def get_proxy_domain(app_id, domain):
  1009. customer_name = app_id.split('_')[1]
  1010. proxy_host = None
  1011. token = get_token()
  1012. url = const.NGINX_URL+"/api/nginx/proxy-hosts"
  1013. headers = {
  1014. 'Authorization': token,
  1015. 'Content-Type': 'application/json'
  1016. }
  1017. response = requests.get(url, headers=headers)
  1018. myLogger.info_logger(response.json())
  1019. for proxy in response.json():
  1020. portainer_name = proxy["forward_host"]
  1021. domain_list = proxy["domain_names"]
  1022. if customer_name == portainer_name:
  1023. myLogger.info_logger("-------------------")
  1024. if domain in domain_list:
  1025. myLogger.info_logger("find the domain proxy")
  1026. proxy_host = proxy
  1027. break
  1028. return proxy_host
  1029. def get_all_domains(app_id):
  1030. customer_name = app_id.split('_')[1]
  1031. domains = []
  1032. token = get_token()
  1033. url = const.NGINX_URL+"/api/nginx/proxy-hosts"
  1034. headers = {
  1035. 'Authorization': token,
  1036. 'Content-Type': 'application/json'
  1037. }
  1038. response = requests.get(url, headers=headers)
  1039. for proxy in response.json():
  1040. portainer_name = proxy["forward_host"]
  1041. if customer_name == portainer_name:
  1042. for domain in proxy["domain_names"]:
  1043. domains.append(domain)
  1044. return domains
  1045. def app_domain_set(domain, app_id):
  1046. temp_domains = []
  1047. temp_domains.append(domain)
  1048. check_domains(temp_domains)
  1049. code, message = docker.check_app_id(app_id)
  1050. if code == None:
  1051. info, flag = app_exits_in_docker(app_id)
  1052. if flag:
  1053. myLogger.info_logger("Check app_id ok")
  1054. else:
  1055. raise CommandException(const.ERROR_CLIENT_PARAM_NOTEXIST, "APP is not exist", "")
  1056. else:
  1057. raise CommandException(code, message, "")
  1058. set_domain(domain, app_id)
  1059. def set_domain(domain, app_id):
  1060. myLogger.info_logger("set_domain start")
  1061. old_domains = get_all_domains(app_id)
  1062. if domain != "":
  1063. if domain not in old_domains:
  1064. message = domain + " is not in use"
  1065. raise CommandException(const.ERROR_CLIENT_PARAM_NOTEXIST, message, "")
  1066. customer_name = app_id.split('_')[1]
  1067. app_url = shell_execute.execute_command_output_all("cat /data/apps/" + customer_name + "/.env")["result"]
  1068. if "APP_URL" in app_url:
  1069. myLogger.info_logger("APP_URL is exist")
  1070. if domain == "":
  1071. ip_result = shell_execute.execute_command_output_all("cat /data/apps/w9services/w9appmanage/public_ip")
  1072. domain = ip_result["result"].rstrip('\n')
  1073. cmd = "sed -i 's/APP_URL=.*/APP_URL=" + domain + "/g' /data/apps/" + customer_name + "/.env"
  1074. shell_execute.execute_command_output_all(cmd)
  1075. if "APP_URL_REPLACE=true" in app_url:
  1076. myLogger.info_logger("need up")
  1077. shell_execute.execute_command_output_all("cd /data/apps/" + customer_name + " && docker compose up -d")
  1078. else:
  1079. cmd = "sed -i 's/APP_URL=.*/APP_URL=" + domain + "/g' /data/apps/" + customer_name + "/.env"
  1080. shell_execute.execute_command_output_all(cmd)
  1081. if "APP_URL_REPLACE=true" in app_url:
  1082. myLogger.info_logger("need up")
  1083. shell_execute.execute_command_output_all("cd /data/apps/" + customer_name + " && docker compose up -d")
  1084. else:
  1085. myLogger.info_logger("APP_URL is not exist")
  1086. if domain == "":
  1087. ip_result = shell_execute.execute_command_output_all("cat /data/apps/w9services/w9appmanage/public_ip")
  1088. domain = ip_result["result"].rstrip('\n')
  1089. cmd = "sed -i '/APP_NETWORK/a APP_URL=" + domain + "' /data/apps/" + customer_name + "/.env"
  1090. shell_execute.execute_command_output_all(cmd)
  1091. myLogger.info_logger("set_domain success")
  1092. def get_container_port(container_name):
  1093. port = "80"
  1094. cmd = "docker port " + container_name + " |grep ::"
  1095. result = shell_execute.execute_command_output_all(cmd)["result"]
  1096. myLogger.info_logger(result)
  1097. port = result.split('/')[0]
  1098. myLogger.info_logger(port)
  1099. return port
  1100. def compared_version(ver1, ver2):
  1101. list1 = str(ver1).split(".")
  1102. list2 = str(ver2).split(".")
  1103. # 循环次数为短的列表的len
  1104. for i in range(len(list1)) if len(list1) < len(list2) else range(len(list2)):
  1105. if int(list1[i]) == int(list2[i]):
  1106. pass
  1107. elif int(list1[i]) < int(list2[i]):
  1108. return -1
  1109. else:
  1110. return 1
  1111. # 循环结束,哪个列表长哪个版本号高
  1112. if len(list1) == len(list2):
  1113. return 0
  1114. elif len(list1) < len(list2):
  1115. return -1
  1116. else:
  1117. return 1