ports.py 1.0 KB

123456789101112131415161718192021222324252627282930313233
  1. import os
  2. import sys
  3. import subprocess
  4. import time
  5. from yatest.common.network import PortManager
  6. def __get_port_range():
  7. port_count = int(sys.argv[1])
  8. pid_filename = sys.argv[2]
  9. port_manager = PortManager()
  10. start_port = port_manager.get_port_range(None, port_count)
  11. sys.stderr.write(str(start_port) + "\n")
  12. with open(pid_filename, 'w') as afile:
  13. afile.write(str(os.getpid()))
  14. while 1:
  15. time.sleep(1)
  16. def get_port_range(port_count=1, pid_filename="recipe_port.pid"):
  17. env = os.environ.copy()
  18. env["Y_PYTHON_ENTRY_POINT"] = "library.python.testing.recipe.ports:__get_port_range"
  19. res = subprocess.Popen([sys.argv[0], str(port_count), pid_filename], env=env, cwd=os.getcwd(), stderr=subprocess.PIPE)
  20. while not os.path.exists(pid_filename):
  21. time.sleep(0.01)
  22. port_start = int(res.stderr.readline())
  23. return port_start
  24. def release_port_range(pid_filename="recipe_port.pid"):
  25. with open(pid_filename, 'r') as afile:
  26. os.kill(int(afile.read()), 9)