magic_trace.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  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. from contextlib import contextmanager
  7. import os
  8. import subprocess
  9. import signal
  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(['wget', '-O', magic_trace_cache, '-q',
  16. 'https://github.com/janestreet/magic-trace/releases/download/v1.0.2/magic-trace'])
  17. subprocess.run(['chmod', '+x', magic_trace_cache])
  18. args = [magic_trace_cache, 'attach', '-pid', str(pid), '-o', output]
  19. p = subprocess.Popen(args, stderr=subprocess.PIPE, encoding='utf-8')
  20. while True:
  21. x = p.stderr.readline()
  22. print(x)
  23. if 'Attached' in x:
  24. break
  25. try:
  26. yield
  27. finally:
  28. p.send_signal(signal.SIGINT)
  29. r = p.wait()
  30. print(p.stderr.read())
  31. p.stderr.close()
  32. if r != 0:
  33. raise ValueError(f'magic_trace exited abnormally: {r}')