CrashHandler.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. # Copyright (c) 2019 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import platform
  4. import traceback
  5. import faulthandler
  6. import tempfile
  7. import os
  8. import os.path
  9. import uuid
  10. import json
  11. import locale
  12. from typing import cast
  13. try:
  14. from sentry_sdk.hub import Hub
  15. from sentry_sdk.utils import event_from_exception
  16. from sentry_sdk import configure_scope
  17. with_sentry_sdk = True
  18. except ImportError:
  19. with_sentry_sdk = False
  20. from PyQt5.QtCore import QT_VERSION_STR, PYQT_VERSION_STR, QUrl
  21. from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QVBoxLayout, QLabel, QTextEdit, QGroupBox, QCheckBox, QPushButton
  22. from PyQt5.QtGui import QDesktopServices
  23. from UM.Application import Application
  24. from UM.Logger import Logger
  25. from UM.View.GL.OpenGL import OpenGL
  26. from UM.i18n import i18nCatalog
  27. from UM.Resources import Resources
  28. from cura import ApplicationMetadata
  29. catalog = i18nCatalog("cura")
  30. MYPY = False
  31. if MYPY:
  32. CuraDebugMode = False
  33. else:
  34. try:
  35. from cura.CuraVersion import CuraDebugMode
  36. except ImportError:
  37. CuraDebugMode = False # [CodeStyle: Reflecting imported value]
  38. # List of exceptions that should not be considered "fatal" and abort the program.
  39. # These are primarily some exception types that we simply skip
  40. skip_exception_types = [
  41. SystemExit,
  42. KeyboardInterrupt,
  43. GeneratorExit
  44. ]
  45. class CrashHandler:
  46. def __init__(self, exception_type, value, tb, has_started = True):
  47. self.exception_type = exception_type
  48. self.value = value
  49. self.traceback = tb
  50. self.has_started = has_started
  51. self.dialog = None # Don't create a QDialog before there is a QApplication
  52. self.cura_version = None
  53. self.cura_locale = None
  54. Logger.log("c", "An uncaught error has occurred!")
  55. for line in traceback.format_exception(exception_type, value, tb):
  56. for part in line.rstrip("\n").split("\n"):
  57. Logger.log("c", part)
  58. self.data = {}
  59. # If Cura has fully started, we only show fatal errors.
  60. # If Cura has not fully started yet, we always show the early crash dialog. Otherwise, Cura will just crash
  61. # without any information.
  62. if has_started and exception_type in skip_exception_types:
  63. return
  64. if with_sentry_sdk:
  65. with configure_scope() as scope:
  66. scope.set_tag("during_startup", not has_started)
  67. if not has_started:
  68. self._send_report_checkbox = None
  69. self.early_crash_dialog = self._createEarlyCrashDialog()
  70. self.dialog = QDialog()
  71. self._createDialog()
  72. def _createEarlyCrashDialog(self):
  73. dialog = QDialog()
  74. dialog.setMinimumWidth(500)
  75. dialog.setMinimumHeight(170)
  76. dialog.setWindowTitle(catalog.i18nc("@title:window", "Cura can't start"))
  77. dialog.finished.connect(self._closeEarlyCrashDialog)
  78. layout = QVBoxLayout(dialog)
  79. label = QLabel()
  80. label.setText(catalog.i18nc("@label crash message", """<p><b>Oops, Ultimaker Cura has encountered something that doesn't seem right.</p></b>
  81. <p>We encountered an unrecoverable error during start up. It was possibly caused by some incorrect configuration files. We suggest to backup and reset your configuration.</p>
  82. <p>Backups can be found in the configuration folder.</p>
  83. <p>Please send us this Crash Report to fix the problem.</p>
  84. """))
  85. label.setWordWrap(True)
  86. layout.addWidget(label)
  87. # "send report" check box and show details
  88. self._send_report_checkbox = QCheckBox(catalog.i18nc("@action:button", "Send crash report to Ultimaker"), dialog)
  89. self._send_report_checkbox.setChecked(True)
  90. show_details_button = QPushButton(catalog.i18nc("@action:button", "Show detailed crash report"), dialog)
  91. show_details_button.setMaximumWidth(200)
  92. show_details_button.clicked.connect(self._showDetailedReport)
  93. show_configuration_folder_button = QPushButton(catalog.i18nc("@action:button", "Show configuration folder"), dialog)
  94. show_configuration_folder_button.setMaximumWidth(200)
  95. show_configuration_folder_button.clicked.connect(self._showConfigurationFolder)
  96. layout.addWidget(self._send_report_checkbox)
  97. layout.addWidget(show_details_button)
  98. layout.addWidget(show_configuration_folder_button)
  99. # "backup and start clean" and "close" buttons
  100. buttons = QDialogButtonBox()
  101. buttons.addButton(QDialogButtonBox.Close)
  102. buttons.addButton(catalog.i18nc("@action:button", "Backup and Reset Configuration"), QDialogButtonBox.AcceptRole)
  103. buttons.rejected.connect(self._closeEarlyCrashDialog)
  104. buttons.accepted.connect(self._backupAndStartClean)
  105. layout.addWidget(buttons)
  106. return dialog
  107. def _closeEarlyCrashDialog(self):
  108. if self._send_report_checkbox.isChecked():
  109. self._sendCrashReport()
  110. os._exit(1)
  111. ## Backup the current resource directories and create clean ones.
  112. def _backupAndStartClean(self):
  113. Resources.factoryReset()
  114. self.early_crash_dialog.close()
  115. def _showConfigurationFolder(self):
  116. path = Resources.getConfigStoragePath()
  117. QDesktopServices.openUrl(QUrl.fromLocalFile( path ))
  118. def _showDetailedReport(self):
  119. self.dialog.exec_()
  120. ## Creates a modal dialog.
  121. def _createDialog(self):
  122. self.dialog.setMinimumWidth(640)
  123. self.dialog.setMinimumHeight(640)
  124. self.dialog.setWindowTitle(catalog.i18nc("@title:window", "Crash Report"))
  125. # if the application has not fully started, this will be a detailed report dialog which should not
  126. # close the application when it's closed.
  127. if self.has_started:
  128. self.dialog.finished.connect(self._close)
  129. layout = QVBoxLayout(self.dialog)
  130. layout.addWidget(self._messageWidget())
  131. layout.addWidget(self._informationWidget())
  132. layout.addWidget(self._exceptionInfoWidget())
  133. layout.addWidget(self._logInfoWidget())
  134. layout.addWidget(self._userDescriptionWidget())
  135. layout.addWidget(self._buttonsWidget())
  136. def _close(self):
  137. os._exit(1)
  138. def _messageWidget(self):
  139. label = QLabel()
  140. label.setText(catalog.i18nc("@label crash message", """<p><b>A fatal error has occurred in Cura. Please send us this Crash Report to fix the problem</p></b>
  141. <p>Please use the "Send report" button to post a bug report automatically to our servers</p>
  142. """))
  143. return label
  144. def _informationWidget(self):
  145. group = QGroupBox()
  146. group.setTitle(catalog.i18nc("@title:groupbox", "System information"))
  147. layout = QVBoxLayout()
  148. label = QLabel()
  149. try:
  150. from UM.Application import Application
  151. self.cura_version = Application.getInstance().getVersion()
  152. self.cura_locale = Application.getInstance().getPreferences().getValue("general/language")
  153. except:
  154. self.cura_version = catalog.i18nc("@label unknown version of Cura", "Unknown")
  155. self.cura_locale = "??_??"
  156. self.data["cura_version"] = self.cura_version
  157. self.data["os"] = {"type": platform.system(), "version": platform.version()}
  158. self.data["qt_version"] = QT_VERSION_STR
  159. self.data["pyqt_version"] = PYQT_VERSION_STR
  160. self.data["locale_os"] = locale.getlocale(locale.LC_MESSAGES)[0] if hasattr(locale, "LC_MESSAGES") else \
  161. locale.getdefaultlocale()[0]
  162. self.data["locale_cura"] = self.cura_locale
  163. crash_info = "<b>" + catalog.i18nc("@label Cura version number", "Cura version") + ":</b> " + str(self.cura_version) + "<br/>"
  164. crash_info += "<b>" + catalog.i18nc("@label", "Cura language") + ":</b> " + str(self.cura_locale) + "<br/>"
  165. crash_info += "<b>" + catalog.i18nc("@label", "OS language") + ":</b> " + str(self.data["locale_os"]) + "<br/>"
  166. crash_info += "<b>" + catalog.i18nc("@label Type of platform", "Platform") + ":</b> " + str(platform.platform()) + "<br/>"
  167. crash_info += "<b>" + catalog.i18nc("@label", "Qt version") + ":</b> " + str(QT_VERSION_STR) + "<br/>"
  168. crash_info += "<b>" + catalog.i18nc("@label", "PyQt version") + ":</b> " + str(PYQT_VERSION_STR) + "<br/>"
  169. crash_info += "<b>" + catalog.i18nc("@label OpenGL version", "OpenGL") + ":</b> " + str(self._getOpenGLInfo()) + "<br/>"
  170. label.setText(crash_info)
  171. layout.addWidget(label)
  172. group.setLayout(layout)
  173. if with_sentry_sdk:
  174. with configure_scope() as scope:
  175. scope.set_tag("qt_version", QT_VERSION_STR)
  176. scope.set_tag("pyqt_version", PYQT_VERSION_STR)
  177. scope.set_tag("os", platform.system())
  178. scope.set_tag("os_version", platform.version())
  179. scope.set_tag("locale_os", self.data["locale_os"])
  180. scope.set_tag("locale_cura", self.cura_locale)
  181. scope.set_tag("is_enterprise", ApplicationMetadata.IsEnterpriseVersion)
  182. scope.set_user({"id": str(uuid.getnode())})
  183. return group
  184. def _getOpenGLInfo(self):
  185. opengl_instance = OpenGL.getInstance()
  186. if not opengl_instance:
  187. self.data["opengl"] = {"version": "n/a", "vendor": "n/a", "type": "n/a"}
  188. return catalog.i18nc("@label", "Not yet initialized<br/>")
  189. info = "<ul>"
  190. info += catalog.i18nc("@label OpenGL version", "<li>OpenGL Version: {version}</li>").format(version = opengl_instance.getOpenGLVersion())
  191. info += catalog.i18nc("@label OpenGL vendor", "<li>OpenGL Vendor: {vendor}</li>").format(vendor = opengl_instance.getGPUVendorName())
  192. info += catalog.i18nc("@label OpenGL renderer", "<li>OpenGL Renderer: {renderer}</li>").format(renderer = opengl_instance.getGPUType())
  193. info += "</ul>"
  194. self.data["opengl"] = {"version": opengl_instance.getOpenGLVersion(), "vendor": opengl_instance.getGPUVendorName(), "type": opengl_instance.getGPUType()}
  195. active_machine_definition_id = "unknown"
  196. active_machine_manufacturer = "unknown"
  197. try:
  198. from cura.CuraApplication import CuraApplication
  199. application = cast(CuraApplication, Application.getInstance())
  200. machine_manager = application.getMachineManager()
  201. global_stack = machine_manager.activeMachine
  202. if global_stack is None:
  203. active_machine_definition_id = "empty"
  204. active_machine_manufacturer = "empty"
  205. else:
  206. active_machine_definition_id = global_stack.definition.getId()
  207. active_machine_manufacturer = global_stack.definition.getMetaDataEntry("manufacturer", "unknown")
  208. except:
  209. pass
  210. if with_sentry_sdk:
  211. with configure_scope() as scope:
  212. scope.set_tag("opengl_version", opengl_instance.getOpenGLVersion())
  213. scope.set_tag("gpu_vendor", opengl_instance.getGPUVendorName())
  214. scope.set_tag("gpu_type", opengl_instance.getGPUType())
  215. scope.set_tag("active_machine", active_machine_definition_id)
  216. scope.set_tag("active_machine_manufacturer", active_machine_manufacturer)
  217. return info
  218. def _exceptionInfoWidget(self):
  219. group = QGroupBox()
  220. group.setTitle(catalog.i18nc("@title:groupbox", "Error traceback"))
  221. layout = QVBoxLayout()
  222. text_area = QTextEdit()
  223. trace_list = traceback.format_exception(self.exception_type, self.value, self.traceback)
  224. trace = "".join(trace_list)
  225. text_area.setText(trace)
  226. text_area.setReadOnly(True)
  227. layout.addWidget(text_area)
  228. group.setLayout(layout)
  229. # Parsing all the information to fill the dictionary
  230. summary = ""
  231. if len(trace_list) >= 1:
  232. summary = trace_list[len(trace_list)-1].rstrip("\n")
  233. module = [""]
  234. if len(trace_list) >= 2:
  235. module = trace_list[len(trace_list)-2].rstrip("\n").split("\n")
  236. module_split = module[0].split(", ")
  237. filepath_directory_split = module_split[0].split("\"")
  238. filepath = ""
  239. if len(filepath_directory_split) > 1:
  240. filepath = filepath_directory_split[1]
  241. directory, filename = os.path.split(filepath)
  242. line = ""
  243. if len(module_split) > 1:
  244. line = int(module_split[1].lstrip("line "))
  245. function = ""
  246. if len(module_split) > 2:
  247. function = module_split[2].lstrip("in ")
  248. code = ""
  249. if len(module) > 1:
  250. code = module[1].lstrip(" ")
  251. # Using this workaround for a cross-platform path splitting
  252. split_path = []
  253. folder_name = ""
  254. # Split until reach folder "cura"
  255. while folder_name != "cura":
  256. directory, folder_name = os.path.split(directory)
  257. if not folder_name:
  258. break
  259. split_path.append(folder_name)
  260. # Look for plugins. If it's not a plugin, the current cura version is set
  261. isPlugin = False
  262. module_version = self.cura_version
  263. module_name = "Cura"
  264. if split_path.__contains__("plugins"):
  265. isPlugin = True
  266. # Look backwards until plugin.json is found
  267. directory, name = os.path.split(filepath)
  268. while not os.listdir(directory).__contains__("plugin.json"):
  269. directory, name = os.path.split(directory)
  270. json_metadata_file = os.path.join(directory, "plugin.json")
  271. try:
  272. with open(json_metadata_file, "r", encoding = "utf-8") as f:
  273. try:
  274. metadata = json.loads(f.read())
  275. module_version = metadata["version"]
  276. module_name = metadata["name"]
  277. except json.decoder.JSONDecodeError:
  278. # Not throw new exceptions
  279. Logger.logException("e", "Failed to parse plugin.json for plugin %s", name)
  280. except:
  281. # Not throw new exceptions
  282. pass
  283. exception_dict = dict()
  284. exception_dict["traceback"] = {"summary": summary, "full_trace": trace}
  285. exception_dict["location"] = {"path": filepath, "file": filename, "function": function, "code": code, "line": line,
  286. "module_name": module_name, "version": module_version, "is_plugin": isPlugin}
  287. self.data["exception"] = exception_dict
  288. if with_sentry_sdk:
  289. with configure_scope() as scope:
  290. scope.set_tag("is_plugin", isPlugin)
  291. scope.set_tag("module", module_name)
  292. return group
  293. def _logInfoWidget(self):
  294. group = QGroupBox()
  295. group.setTitle(catalog.i18nc("@title:groupbox", "Logs"))
  296. layout = QVBoxLayout()
  297. text_area = QTextEdit()
  298. tmp_file_fd, tmp_file_path = tempfile.mkstemp(prefix = "cura-crash", text = True)
  299. os.close(tmp_file_fd)
  300. with open(tmp_file_path, "w", encoding = "utf-8") as f:
  301. faulthandler.dump_traceback(f, all_threads=True)
  302. with open(tmp_file_path, "r", encoding = "utf-8") as f:
  303. logdata = f.read()
  304. text_area.setText(logdata)
  305. text_area.setReadOnly(True)
  306. layout.addWidget(text_area)
  307. group.setLayout(layout)
  308. self.data["log"] = logdata
  309. return group
  310. def _userDescriptionWidget(self):
  311. group = QGroupBox()
  312. group.setTitle(catalog.i18nc("@title:groupbox", "User description" +
  313. " (Note: Developers may not speak your language, please use English if possible)"))
  314. layout = QVBoxLayout()
  315. # When sending the report, the user comments will be collected
  316. self.user_description_text_area = QTextEdit()
  317. self.user_description_text_area.setFocus(True)
  318. layout.addWidget(self.user_description_text_area)
  319. group.setLayout(layout)
  320. return group
  321. def _buttonsWidget(self):
  322. buttons = QDialogButtonBox()
  323. buttons.addButton(QDialogButtonBox.Close)
  324. # Like above, this will be served as a separate detailed report dialog if the application has not yet been
  325. # fully loaded. In this case, "send report" will be a check box in the early crash dialog, so there is no
  326. # need for this extra button.
  327. if self.has_started:
  328. buttons.addButton(catalog.i18nc("@action:button", "Send report"), QDialogButtonBox.AcceptRole)
  329. buttons.accepted.connect(self._sendCrashReport)
  330. buttons.rejected.connect(self.dialog.close)
  331. return buttons
  332. def _sendCrashReport(self):
  333. # Before sending data, the user comments are stored
  334. self.data["user_info"] = self.user_description_text_area.toPlainText()
  335. if with_sentry_sdk:
  336. try:
  337. hub = Hub.current
  338. event, hint = event_from_exception((self.exception_type, self.value, self.traceback))
  339. hub.capture_event(event, hint=hint)
  340. hub.flush()
  341. except Exception as e: # We don't want any exception to cause problems
  342. Logger.logException("e", "An exception occurred while trying to send crash report")
  343. if not self.has_started:
  344. print("An exception occurred while trying to send crash report: %s" % e)
  345. else:
  346. msg = "SentrySDK is not available and the report could not be sent."
  347. Logger.logException("e", msg)
  348. if not self.has_started:
  349. print(msg)
  350. print("Exception type: {}".format(self.exception_type))
  351. print("Value: {}".format(self.value))
  352. print("Traceback: {}".format(self.traceback))
  353. os._exit(1)
  354. def show(self):
  355. # must run the GUI code on the Qt thread, otherwise the widgets on the dialog won't react correctly.
  356. Application.getInstance().callLater(self._show)
  357. def _show(self):
  358. # When the exception is in the skip_exception_types list, the dialog is not created, so we don't need to show it
  359. if self.dialog:
  360. self.dialog.exec_()
  361. os._exit(1)