environment.py 2.4 KB

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