manage.py 48 KB

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