manage.py 46 KB

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