manage.py 46 KB

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