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."""
6import signal
7import sys
8
9from telemetry.internal.util import exception_formatter
10
11
12def InstallHooks():
13  InstallUnhandledExceptionFormatter()
14  InstallStackDumpOnSigusr1()
15  InstallTerminationHook()
16
17def InstallUnhandledExceptionFormatter():
18  """Print prettier exceptions that also contain the stack frame's locals."""
19  sys.excepthook = exception_formatter.PrintFormattedException
20
21
22def InstallStackDumpOnSigusr1():
23  """Catch SIGUSR1 and print a stack trace."""
24  # Windows doesn't define SIGUSR1.
25  if not hasattr(signal, 'SIGUSR1'):
26    return
27
28  def PrintDiagnostics(_, stack_frame):
29    exception_string = 'SIGUSR1 received, printed stack trace'
30    exception_formatter.PrintFormattedFrame(stack_frame, exception_string)
31  signal.signal(signal.SIGUSR1, PrintDiagnostics)
32
33
34def InstallTerminationHook():
35  """Catch SIGTERM, print a stack trace, and exit."""
36  def PrintStackAndExit(sig, stack_frame):
37    exception_string = 'Received signal %s, exiting' % sig
38    exception_formatter.PrintFormattedFrame(stack_frame, exception_string)
39    sys.exit(-1)
40  signal.signal(signal.SIGTERM, PrintStackAndExit)
41