docker.py 2.6 KB

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