CrashHandler.py 16 KB

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