docker.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import os, io, sys, platform, shutil, time, json, datetime
  2. import re,docker
  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. http_port = read_env(path, "APP_HTTP_PORT")
  16. print("curl localhost:" + http_port)
  17. output = shell_execute.execute_command_output_all("curl localhost:" + http_port)
  18. code = output["code"]
  19. print(output["result"])
  20. if int(code) == 0 and output["result"].find("Failed") != -1:
  21. process_now = "running"
  22. return process_now
  23. def check_vm_resource():
  24. # 服务器剩余资源是否足够安装,如cpu,内存,硬盘
  25. return true
  26. def check_app_directory(app_name):
  27. # 判断/data/apps/app_name是否已经存在,如果已经存在,方法结束
  28. print("checking dir...")
  29. path = "/data/apps/"+app_name
  30. isexsits = os.path.exists(path)
  31. return isexsits
  32. def check_app_compose(app_name):
  33. print("checking port...")
  34. path = "/data/apps/" + app_name + "/.env"
  35. http_port = read_env(path, "APP_HTTP_PORT")
  36. db_port = read_env(path, "APP_DB.*_PORT")
  37. #1.判断/data/apps/app_name/.env中的port是否占用,没有被占用,方法结束(network.py的get_start_port方法)
  38. if http_port != "":
  39. print("check http port...")
  40. http_port = network.get_start_port(http_port)
  41. modify_env(path, "APP_HTTP_PORT", http_port)
  42. if db_port != "":
  43. print("check db port...")
  44. db_port = network.get_start_port(db_port)
  45. modify_env(path, "APP_DB.*_PORT", db_port)
  46. print("port check complete")
  47. return
  48. def read_env(path, key):
  49. output = shell_execute.execute_command_output_all("cat " + path + "|grep "+ key+ "|head -1")
  50. code = output["code"]
  51. ret = "" #the value of environment var
  52. if int(code) == 0 and output["result"] != "":
  53. ret = output["result"]
  54. ret = ret.split("=")[1]
  55. ret = re.sub("'","",ret)
  56. ret = re.sub("\n","",ret)
  57. return ret
  58. def modify_env(path, env_name, value):
  59. file_data = ""
  60. with open(path, "r", encoding="utf-8") as f:
  61. for line in f:
  62. if re.match(env_name, line) != None:
  63. env_name = line.split("=")[0]
  64. line = line.replace(line, env_name + "=" + value+"\n")
  65. file_data += line
  66. with open(path, "w", encoding="utf-8") as f:
  67. f.write(file_data)