Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / tools / telemetry / telemetry / util / global_hooks.py
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.
4
5 """Hooks that apply globally to all scripts that import or use Telemetry."""
6
7 import os
8 import signal
9 import sys
10
11 from telemetry.core import util
12 from telemetry.util import exception_formatter
13
14
15 def InstallHooks():
16   RemoveAllStalePycFiles(util.GetTelemetryDir())
17   RemoveAllStalePycFiles(util.GetBaseDir())
18   InstallUnhandledExceptionFormatter()
19   InstallStackDumpOnSigusr1()
20   InstallTerminationHook()
21
22
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:
27       continue
28     for filename in filenames:
29       root, ext = os.path.splitext(filename)
30       if ext != '.pyc':
31         continue
32
33       pyc_path = os.path.join(dirname, filename)
34       py_path = os.path.join(dirname, root + '.py')
35
36       try:
37         if not os.path.exists(py_path):
38           os.remove(pyc_path)
39       except OSError:
40         # Wrap OS calls in try/except in case another process touched this file.
41         pass
42
43     try:
44       os.removedirs(dirname)
45     except OSError:
46       # Wrap OS calls in try/except in case another process touched this dir.
47       pass
48
49
50 def InstallUnhandledExceptionFormatter():
51   """Print prettier exceptions that also contain the stack frame's locals."""
52   sys.excepthook = exception_formatter.PrintFormattedException
53
54
55 def InstallStackDumpOnSigusr1():
56   """Catch SIGUSR1 and print a stack trace."""
57   # Windows doesn't define SIGUSR1.
58   if not hasattr(signal, 'SIGUSR1'):
59     return
60
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)
65
66
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)
72     sys.exit(-1)
73   signal.signal(signal.SIGTERM, PrintStackAndExit)