1 # Copyright 2014 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
5 """Hooks that apply globally to all scripts that import or use Telemetry."""
11 from telemetry.core import util
12 from telemetry.util import exception_formatter
16 RemoveAllStalePycFiles(util.GetTelemetryDir())
17 RemoveAllStalePycFiles(util.GetBaseDir())
18 InstallUnhandledExceptionFormatter()
19 InstallStackDumpOnSigusr1()
20 InstallTerminationHook()
23 def RemoveAllStalePycFiles(base_dir):
24 """Scan directories for old .pyc files without a .py file and delete them."""
25 for dirname, _, filenames in os.walk(base_dir):
26 if '.svn' in dirname or '.git' in dirname:
28 for filename in filenames:
29 root, ext = os.path.splitext(filename)
33 pyc_path = os.path.join(dirname, filename)
34 py_path = os.path.join(dirname, root + '.py')
37 if not os.path.exists(py_path):
40 # Wrap OS calls in try/except in case another process touched this file.
44 os.removedirs(dirname)
46 # Wrap OS calls in try/except in case another process touched this dir.
50 def InstallUnhandledExceptionFormatter():
51 """Print prettier exceptions that also contain the stack frame's locals."""
52 sys.excepthook = exception_formatter.PrintFormattedException
55 def InstallStackDumpOnSigusr1():
56 """Catch SIGUSR1 and print a stack trace."""
57 # Windows doesn't define SIGUSR1.
58 if not hasattr(signal, 'SIGUSR1'):
61 def PrintDiagnostics(_, stack_frame):
62 exception_string = 'SIGUSR1 received, printed stack trace'
63 exception_formatter.PrintFormattedFrame(stack_frame, exception_string)
64 signal.signal(signal.SIGUSR1, PrintDiagnostics)
67 def InstallTerminationHook():
68 """Catch SIGTERM, print a stack trace, and exit."""
69 def PrintStackAndExit(sig, stack_frame):
70 exception_string = 'Received signal %s, exiting' % sig
71 exception_formatter.PrintFormattedFrame(stack_frame, exception_string)
73 signal.signal(signal.SIGTERM, PrintStackAndExit)