manage.py 46 KB

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