crashhandler.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. # encoding: utf-8
  2. """sys.excepthook for IPython itself, leaves a detailed report on disk.
  3. Authors:
  4. * Fernando Perez
  5. * Brian E. Granger
  6. """
  7. #-----------------------------------------------------------------------------
  8. # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
  9. # Copyright (C) 2008-2011 The IPython Development Team
  10. #
  11. # Distributed under the terms of the BSD License. The full license is in
  12. # the file COPYING, distributed as part of this software.
  13. #-----------------------------------------------------------------------------
  14. #-----------------------------------------------------------------------------
  15. # Imports
  16. #-----------------------------------------------------------------------------
  17. import sys
  18. import traceback
  19. from pprint import pformat
  20. from pathlib import Path
  21. import builtins as builtin_mod
  22. from IPython.core import ultratb
  23. from IPython.core.application import Application
  24. from IPython.core.release import author_email
  25. from IPython.utils.sysinfo import sys_info
  26. from IPython.core.release import __version__ as version
  27. from typing import Optional, Dict
  28. import types
  29. #-----------------------------------------------------------------------------
  30. # Code
  31. #-----------------------------------------------------------------------------
  32. # Template for the user message.
  33. _default_message_template = """\
  34. Oops, {app_name} crashed. We do our best to make it stable, but...
  35. A crash report was automatically generated with the following information:
  36. - A verbatim copy of the crash traceback.
  37. - A copy of your input history during this session.
  38. - Data on your current {app_name} configuration.
  39. It was left in the file named:
  40. \t'{crash_report_fname}'
  41. If you can email this file to the developers, the information in it will help
  42. them in understanding and correcting the problem.
  43. You can mail it to: {contact_name} at {contact_email}
  44. with the subject '{app_name} Crash Report'.
  45. If you want to do it now, the following command will work (under Unix):
  46. mail -s '{app_name} Crash Report' {contact_email} < {crash_report_fname}
  47. In your email, please also include information about:
  48. - The operating system under which the crash happened: Linux, macOS, Windows,
  49. other, and which exact version (for example: Ubuntu 16.04.3, macOS 10.13.2,
  50. Windows 10 Pro), and whether it is 32-bit or 64-bit;
  51. - How {app_name} was installed: using pip or conda, from GitHub, as part of
  52. a Docker container, or other, providing more detail if possible;
  53. - How to reproduce the crash: what exact sequence of instructions can one
  54. input to get the same crash? Ideally, find a minimal yet complete sequence
  55. of instructions that yields the crash.
  56. To ensure accurate tracking of this issue, please file a report about it at:
  57. {bug_tracker}
  58. """
  59. _lite_message_template = """
  60. If you suspect this is an IPython {version} bug, please report it at:
  61. https://github.com/ipython/ipython/issues
  62. or send an email to the mailing list at {email}
  63. You can print a more detailed traceback right now with "%tb", or use "%debug"
  64. to interactively debug it.
  65. Extra-detailed tracebacks for bug-reporting purposes can be enabled via:
  66. {config}Application.verbose_crash=True
  67. """
  68. class CrashHandler:
  69. """Customizable crash handlers for IPython applications.
  70. Instances of this class provide a :meth:`__call__` method which can be
  71. used as a ``sys.excepthook``. The :meth:`__call__` signature is::
  72. def __call__(self, etype, evalue, etb)
  73. """
  74. message_template = _default_message_template
  75. section_sep = '\n\n'+'*'*75+'\n\n'
  76. info: Dict[str, Optional[str]]
  77. def __init__(
  78. self,
  79. app: Application,
  80. contact_name: Optional[str] = None,
  81. contact_email: Optional[str] = None,
  82. bug_tracker: Optional[str] = None,
  83. show_crash_traceback: bool = True,
  84. call_pdb: bool = False,
  85. ):
  86. """Create a new crash handler
  87. Parameters
  88. ----------
  89. app : Application
  90. A running :class:`Application` instance, which will be queried at
  91. crash time for internal information.
  92. contact_name : str
  93. A string with the name of the person to contact.
  94. contact_email : str
  95. A string with the email address of the contact.
  96. bug_tracker : str
  97. A string with the URL for your project's bug tracker.
  98. show_crash_traceback : bool
  99. If false, don't print the crash traceback on stderr, only generate
  100. the on-disk report
  101. call_pdb
  102. Whether to call pdb on crash
  103. Attributes
  104. ----------
  105. These instances contain some non-argument attributes which allow for
  106. further customization of the crash handler's behavior. Please see the
  107. source for further details.
  108. """
  109. self.crash_report_fname = "Crash_report_%s.txt" % app.name
  110. self.app = app
  111. self.call_pdb = call_pdb
  112. #self.call_pdb = True # dbg
  113. self.show_crash_traceback = show_crash_traceback
  114. self.info = dict(app_name = app.name,
  115. contact_name = contact_name,
  116. contact_email = contact_email,
  117. bug_tracker = bug_tracker,
  118. crash_report_fname = self.crash_report_fname)
  119. def __call__(
  120. self,
  121. etype: type[BaseException],
  122. evalue: BaseException,
  123. etb: types.TracebackType,
  124. ) -> None:
  125. """Handle an exception, call for compatible with sys.excepthook"""
  126. # do not allow the crash handler to be called twice without reinstalling it
  127. # this prevents unlikely errors in the crash handling from entering an
  128. # infinite loop.
  129. sys.excepthook = sys.__excepthook__
  130. # Report tracebacks shouldn't use color in general (safer for users)
  131. color_scheme = 'NoColor'
  132. # Use this ONLY for developer debugging (keep commented out for release)
  133. # color_scheme = 'Linux' # dbg
  134. ipython_dir = getattr(self.app, "ipython_dir", None)
  135. if ipython_dir is not None:
  136. assert isinstance(ipython_dir, str)
  137. rptdir = Path(ipython_dir)
  138. else:
  139. rptdir = Path.cwd()
  140. if not rptdir.is_dir():
  141. rptdir = Path.cwd()
  142. report_name = rptdir / self.crash_report_fname
  143. # write the report filename into the instance dict so it can get
  144. # properly expanded out in the user message template
  145. self.crash_report_fname = str(report_name)
  146. self.info["crash_report_fname"] = str(report_name)
  147. TBhandler = ultratb.VerboseTB(
  148. color_scheme=color_scheme,
  149. long_header=True,
  150. call_pdb=self.call_pdb,
  151. )
  152. if self.call_pdb:
  153. TBhandler(etype,evalue,etb)
  154. return
  155. else:
  156. traceback = TBhandler.text(etype,evalue,etb,context=31)
  157. # print traceback to screen
  158. if self.show_crash_traceback:
  159. print(traceback, file=sys.stderr)
  160. # and generate a complete report on disk
  161. try:
  162. report = open(report_name, "w", encoding="utf-8")
  163. except:
  164. print('Could not create crash report on disk.', file=sys.stderr)
  165. return
  166. with report:
  167. # Inform user on stderr of what happened
  168. print('\n'+'*'*70+'\n', file=sys.stderr)
  169. print(self.message_template.format(**self.info), file=sys.stderr)
  170. # Construct report on disk
  171. report.write(self.make_report(str(traceback)))
  172. builtin_mod.input("Hit <Enter> to quit (your terminal may close):")
  173. def make_report(self, traceback: str) -> str:
  174. """Return a string containing a crash report."""
  175. sec_sep = self.section_sep
  176. report = ['*'*75+'\n\n'+'IPython post-mortem report\n\n']
  177. rpt_add = report.append
  178. rpt_add(sys_info())
  179. try:
  180. config = pformat(self.app.config)
  181. rpt_add(sec_sep)
  182. rpt_add("Application name: %s\n\n" % self.app.name)
  183. rpt_add("Current user configuration structure:\n\n")
  184. rpt_add(config)
  185. except:
  186. pass
  187. rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
  188. return ''.join(report)
  189. def crash_handler_lite(
  190. etype: type[BaseException], evalue: BaseException, tb: types.TracebackType
  191. ) -> None:
  192. """a light excepthook, adding a small message to the usual traceback"""
  193. traceback.print_exception(etype, evalue, tb)
  194. from IPython.core.interactiveshell import InteractiveShell
  195. if InteractiveShell.initialized():
  196. # we are in a Shell environment, give %magic example
  197. config = "%config "
  198. else:
  199. # we are not in a shell, show generic config
  200. config = "c."
  201. print(_lite_message_template.format(email=author_email, config=config, version=version), file=sys.stderr)