manage.py 45 KB

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