magic_trace.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. # Copyright (c) Facebook, Inc. and its affiliates.
  2. # All rights reserved.
  3. #
  4. # This source code is licensed under the BSD-style license found in the
  5. # LICENSE file in the root directory of this source tree.
  6. import os
  7. import signal
  8. import subprocess
  9. from collections.abc import Generator
  10. from contextlib import contextmanager
  11. @contextmanager
  12. def magic_trace(
  13. output: str = "trace.fxt", magic_trace_cache: str = "/tmp/magic-trace"
  14. ) -> Generator[None, None, None]:
  15. pid = os.getpid()
  16. if not os.path.exists(magic_trace_cache):
  17. print(f"Downloading magic_trace to: {magic_trace_cache}")
  18. subprocess.run(
  19. [
  20. "wget",
  21. "-O",
  22. magic_trace_cache,
  23. "-q",
  24. "https://github.com/janestreet/magic-trace/releases/download/v1.0.2/magic-trace",
  25. ]
  26. )
  27. subprocess.run(["chmod", "+x", magic_trace_cache])
  28. args = [magic_trace_cache, "attach", "-pid", str(pid), "-o", output]
  29. p = subprocess.Popen(args, stderr=subprocess.PIPE, encoding="utf-8")
  30. if p.stderr is None:
  31. raise AssertionError("Expected stderr to be non-None")
  32. while True:
  33. x = p.stderr.readline()
  34. print(x)
  35. if "Attached" in x:
  36. break
  37. try:
  38. yield
  39. finally:
  40. p.send_signal(signal.SIGINT)
  41. r = p.wait()
  42. if p.stderr is not None:
  43. print(p.stderr.read())
  44. p.stderr.close()
  45. if r != 0:
  46. raise ValueError(f"magic_trace exited abnormally: {r}")