CrashHandler.py 17 KB

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