__init__.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import os.path
  2. import psutil
  3. import socket
  4. import subprocess
  5. import time
  6. import yatest.common
  7. def find_free_ports(count):
  8. sockets = []
  9. ports = []
  10. for _ in range(count):
  11. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  12. sock.bind(('', 0))
  13. ports.append(sock.getsockname()[1])
  14. sockets.append(sock)
  15. for sock in sockets:
  16. sock.close()
  17. return ports
  18. def start_daemon(command, environment, is_alive_check, pid_file_name, timeout=60, daemon_name=None):
  19. daemon_name = daemon_name or os.path.basename(command[0])
  20. stdout_path = yatest.common.output_path('{}.out.log').format(daemon_name)
  21. stderr_path = yatest.common.output_path('{}.err.log').format(daemon_name)
  22. process = subprocess.Popen(
  23. command,
  24. stdout=open(stdout_path, 'w'),
  25. stderr=open(stderr_path, 'w'),
  26. env=environment)
  27. with open(pid_file_name, 'w') as fout:
  28. fout.write(str(process.pid))
  29. for attempts in range(timeout):
  30. result = process.poll()
  31. if result is not None:
  32. raise RuntimeError(
  33. 'Could not launch "{}" with exit code {}\nStdout: {}\nStderr: {}'
  34. .format(daemon_name, result, stdout_path, stderr_path)
  35. )
  36. if is_alive_check():
  37. return
  38. time.sleep(1)
  39. raise RuntimeError(
  40. 'Could not launch "{}" for {} seconds\nStdout: {}\nStderr: {}'
  41. .format(daemon_name, timeout, stdout_path, stderr_path)
  42. )
  43. def pid_exists(pid):
  44. try:
  45. if psutil.Process(pid).status() == psutil.STATUS_ZOMBIE:
  46. return False
  47. except psutil.NoSuchProcess:
  48. return False
  49. return True
  50. def stop_daemon(pid, signal=15):
  51. pid = int(pid)
  52. if not pid_exists(pid):
  53. return False
  54. os.kill(pid, signal)
  55. while pid_exists(pid):
  56. time.sleep(1)
  57. return True