docker.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import os, io, sys, platform, shutil, time, json, datetime
  2. import re
  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 create_app_directory(app_name):
  9. # 判断/data/apps/app_name是否已经存在,如果已经存在,方法结束
  10. print("checking dir...")
  11. path = "/data/apps/"+app_name
  12. isexsits = os.path.exists(path)
  13. return isexsits
  14. def check_app_compose(app_name):
  15. print("checking port...")
  16. path = "/data/apps/" + app_name + "/.env"
  17. http_port_env, http_port = read_env(path, "APP_HTTP_PORT")
  18. db_port_env, db_port = read_env(path, "APP_DB.*_PORT")
  19. #1.判断/data/apps/app_name/.env中的port是否占用,没有被占用,方法结束(network.py的get_start_port方法)
  20. if http_port != "":
  21. print("check http port...")
  22. http_port = network.get_start_port(http_port)
  23. modify_port(path, http_port_env, http_port)
  24. if db_port != "":
  25. print("check db port...")
  26. db_port = network.get_start_port(db_port)
  27. modify_port(path, db_port_env, db_port)
  28. print("port check complete")
  29. return
  30. def read_env(path, key):
  31. output = shell_execute.execute_command_output_all("cat " + path + "|grep "+ key+ "|head -1")
  32. code = output["code"]
  33. env = "" #the name of environment var
  34. ret = "" #the value of environment var
  35. if int(code) == 0 and output["result"] != "":
  36. ret = output["result"]
  37. env = ret.split("=")[0]
  38. ret = ret.split("=")[1]
  39. ret = re.sub("'","",ret)
  40. ret = re.sub("\n","",ret)
  41. return env, ret
  42. def modify_port(path, env_name, port):
  43. file_data = ""
  44. with open(path, "r", encoding="utf-8") as f:
  45. for line in f:
  46. if env_name in line:
  47. line = line.replace(line, env_name + "=" + port+"\n")
  48. file_data += line
  49. with open(path, "w", encoding="utf-8") as f:
  50. f.write(file_data)