docker.py 2.8 KB

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