manage.py 46 KB

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