manage.py 46 KB

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