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