docker.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import os, io, sys, platform, shutil, time, json, datetime
  2. import re,docker,requests
  3. from api.utils import shell_execute
  4. from api.utils import network
  5. from dotenv import load_dotenv, find_dotenv
  6. import dotenv
  7. from pathlib import Path
  8. def get_process_perc(app_name):
  9. process_now = "pulling"
  10. output = shell_execute.execute_command_output_all("sudo docker image list |grep " + app_name)
  11. code = output["code"]
  12. if int(code) == 0 and output["result"] != "":
  13. process_now = "starting"
  14. path = "/data/apps/" + app_name + "/.env"
  15. port = read_env(path, "APP_HTTP_PORT")
  16. if port == "":
  17. port = read_env(path, "APP_DB_PORT")
  18. else:
  19. port = "9001"
  20. url = "http://localhost:" + port
  21. r = requests.get(url, timeout=5)
  22. code = r.status_code
  23. if code == 200:
  24. process_now = "running"
  25. else:
  26. print "网站初始化未完成,不能访问!"
  27. return process_now
  28. def check_vm_resource():
  29. # 服务器剩余资源是否足够安装,如cpu,内存,硬盘
  30. return true
  31. def check_app_directory(app_name):
  32. # 判断/data/apps/app_name是否已经存在,如果已经存在,方法结束
  33. print("checking dir...")
  34. path = "/data/apps/"+app_name
  35. isexsits = os.path.exists(path)
  36. return isexsits
  37. def check_app_compose(app_name):
  38. print("checking port...")
  39. path = "/data/apps/" + app_name + "/.env"
  40. http_port = read_env(path, "APP_HTTP_PORT")
  41. db_port = read_env(path, "APP_DB.*_PORT")
  42. #1.判断/data/apps/app_name/.env中的port是否占用,没有被占用,方法结束(network.py的get_start_port方法)
  43. if http_port != "":
  44. print("check http port...")
  45. http_port = network.get_start_port(http_port)
  46. modify_env(path, "APP_HTTP_PORT", http_port)
  47. if db_port != "":
  48. print("check db port...")
  49. db_port = network.get_start_port(db_port)
  50. modify_env(path, "APP_DB.*_PORT", db_port)
  51. print("port check complete")
  52. return
  53. def read_env(path, key):
  54. output = shell_execute.execute_command_output_all("cat " + path + "|grep "+ key+ "|head -1")
  55. code = output["code"]
  56. ret = "" #the value of environment var
  57. if int(code) == 0 and output["result"] != "":
  58. ret = output["result"]
  59. ret = ret.split("=")[1]
  60. ret = re.sub("'","",ret)
  61. ret = re.sub("\n","",ret)
  62. return ret
  63. def modify_env(path, env_name, value):
  64. file_data = ""
  65. with open(path, "r", encoding="utf-8") as f:
  66. for line in f:
  67. if re.match(env_name, line) != None:
  68. env_name = line.split("=")[0]
  69. line = line.replace(line, env_name + "=" + value+"\n")
  70. file_data += line
  71. with open(path, "w", encoding="utf-8") as f:
  72. f.write(file_data)