magic_trace.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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 contextlib import contextmanager
  10. @contextmanager
  11. def magic_trace(output="trace.fxt", magic_trace_cache="/tmp/magic-trace"):
  12. pid = os.getpid()
  13. if not os.path.exists(magic_trace_cache):
  14. print(f"Downloading magic_trace to: {magic_trace_cache}")
  15. subprocess.run(
  16. [
  17. "wget",
  18. "-O",
  19. magic_trace_cache,
  20. "-q",
  21. "https://github.com/janestreet/magic-trace/releases/download/v1.0.2/magic-trace",
  22. ]
  23. )
  24. subprocess.run(["chmod", "+x", magic_trace_cache])
  25. args = [magic_trace_cache, "attach", "-pid", str(pid), "-o", output]
  26. p = subprocess.Popen(args, stderr=subprocess.PIPE, encoding="utf-8")
  27. while True:
  28. x = p.stderr.readline()
  29. print(x)
  30. if "Attached" in x:
  31. break
  32. try:
  33. yield
  34. finally:
  35. p.send_signal(signal.SIGINT)
  36. r = p.wait()
  37. print(p.stderr.read())
  38. p.stderr.close()
  39. if r != 0:
  40. raise ValueError(f"magic_trace exited abnormally: {r}")