environment.py 2.3 KB

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