environment.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import os
  2. import socket
  3. import subprocess
  4. import time
  5. from contextlib import closing
  6. from signal import SIGKILL
  7. def before_scenario(context, scenario):
  8. print(f"\x1b[33;42mStarting new scenario: {scenario.name}!\x1b[0m")
  9. port = 8080
  10. if 'PORT' in os.environ:
  11. port = int(os.environ['PORT'])
  12. if is_server_listening("localhost", port):
  13. assert False, "Server already started"
  14. def after_scenario(context, scenario):
  15. if scenario.status == "failed":
  16. if 'GITHUB_ACTIONS' in os.environ:
  17. print(f"\x1b[33;101mSCENARIO FAILED: {scenario.name} server logs:\x1b[0m\n\n")
  18. if os.path.isfile('llama.log'):
  19. with closing(open('llama.log', 'r')) as f:
  20. for line in f:
  21. print(line)
  22. if not is_server_listening(context.server_fqdn, context.server_port):
  23. print("\x1b[33;101mERROR: Server stopped listening\x1b[0m")
  24. if not pid_exists(context.server_process.pid):
  25. assert False, f"Server not running pid={context.server_process.pid} ..."
  26. print(f"stopping server pid={context.server_process.pid} ...")
  27. context.server_process.kill()
  28. # Wait few for socket to free up
  29. time.sleep(0.05)
  30. attempts = 0
  31. while is_server_listening(context.server_fqdn, context.server_port):
  32. print(f"stopping server pid={context.server_process.pid} ...")
  33. os.kill(context.server_process.pid, SIGKILL)
  34. time.sleep(0.1)
  35. attempts += 1
  36. if attempts > 5:
  37. print(f"Server dangling exits, killing all {context.server_path} ...")
  38. process = subprocess.run(['killall', '-9', context.server_path],
  39. stderr=subprocess.PIPE,
  40. universal_newlines=True)
  41. print(process)
  42. def is_server_listening(server_fqdn, server_port):
  43. with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
  44. result = sock.connect_ex((server_fqdn, server_port))
  45. return result == 0
  46. def pid_exists(pid):
  47. """Check whether pid exists in the current process table."""
  48. import errno
  49. if pid < 0:
  50. return False
  51. try:
  52. os.kill(pid, 0)
  53. except OSError as e:
  54. return e.errno == errno.EPERM
  55. else:
  56. return True