CrashHandler.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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 not be considered "fatal" and abort the program.
  34. # These are primarily some exception types that we simply skip
  35. skip_exception_types = [
  36. SystemExit,
  37. KeyboardInterrupt,
  38. GeneratorExit
  39. ]
  40. class CrashHandler:
  41. crash_url = "https://stats.ultimaker.com/api/cura"
  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. # While we create the GUI, the information will be stored for sending afterwards
  49. self.data = dict()
  50. self.data["time_stamp"] = time.time()
  51. Logger.log("c", "An uncaught error has occurred!")
  52. for line in traceback.format_exception(exception_type, value, tb):
  53. for part in line.rstrip("\n").split("\n"):
  54. Logger.log("c", part)
  55. # If Cura has fully started, we only show fatal errors.
  56. # If Cura has not fully started yet, we always show the early crash dialog. Otherwise, Cura will just crash
  57. # without any information.
  58. if has_started and exception_type in skip_exception_types:
  59. return
  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. except:
  146. self.cura_version = catalog.i18nc("@label unknown version of Cura", "Unknown")
  147. crash_info = "<b>" + catalog.i18nc("@label Cura version number", "Cura version") + ":</b> " + str(self.cura_version) + "<br/>"
  148. crash_info += "<b>" + catalog.i18nc("@label Type of platform", "Platform") + ":</b> " + str(platform.platform()) + "<br/>"
  149. crash_info += "<b>" + catalog.i18nc("@label", "Qt version") + ":</b> " + str(QT_VERSION_STR) + "<br/>"
  150. crash_info += "<b>" + catalog.i18nc("@label", "PyQt version") + ":</b> " + str(PYQT_VERSION_STR) + "<br/>"
  151. crash_info += "<b>" + catalog.i18nc("@label OpenGL version", "OpenGL") + ":</b> " + str(self._getOpenGLInfo()) + "<br/>"
  152. label.setText(crash_info)
  153. layout.addWidget(label)
  154. group.setLayout(layout)
  155. self.data["cura_version"] = self.cura_version
  156. self.data["os"] = {"type": platform.system(), "version": platform.version()}
  157. self.data["qt_version"] = QT_VERSION_STR
  158. self.data["pyqt_version"] = PYQT_VERSION_STR
  159. return group
  160. def _getOpenGLInfo(self):
  161. opengl_instance = OpenGL.getInstance()
  162. if not opengl_instance:
  163. self.data["opengl"] = {"version": "n/a", "vendor": "n/a", "type": "n/a"}
  164. return catalog.i18nc("@label", "Not yet initialized<br/>")
  165. info = "<ul>"
  166. info += catalog.i18nc("@label OpenGL version", "<li>OpenGL Version: {version}</li>").format(version = opengl_instance.getOpenGLVersion())
  167. info += catalog.i18nc("@label OpenGL vendor", "<li>OpenGL Vendor: {vendor}</li>").format(vendor = opengl_instance.getGPUVendorName())
  168. info += catalog.i18nc("@label OpenGL renderer", "<li>OpenGL Renderer: {renderer}</li>").format(renderer = opengl_instance.getGPUType())
  169. info += "</ul>"
  170. self.data["opengl"] = {"version": opengl_instance.getOpenGLVersion(), "vendor": opengl_instance.getGPUVendorName(), "type": opengl_instance.getGPUType()}
  171. return info
  172. def _exceptionInfoWidget(self):
  173. group = QGroupBox()
  174. group.setTitle(catalog.i18nc("@title:groupbox", "Error traceback"))
  175. layout = QVBoxLayout()
  176. text_area = QTextEdit()
  177. trace_list = traceback.format_exception(self.exception_type, self.value, self.traceback)
  178. trace = "".join(trace_list)
  179. text_area.setText(trace)
  180. text_area.setReadOnly(True)
  181. layout.addWidget(text_area)
  182. group.setLayout(layout)
  183. # Parsing all the information to fill the dictionary
  184. summary = ""
  185. if len(trace_list) >= 1:
  186. summary = trace_list[len(trace_list)-1].rstrip("\n")
  187. module = [""]
  188. if len(trace_list) >= 2:
  189. module = trace_list[len(trace_list)-2].rstrip("\n").split("\n")
  190. module_split = module[0].split(", ")
  191. filepath_directory_split = module_split[0].split("\"")
  192. filepath = ""
  193. if len(filepath_directory_split) > 1:
  194. filepath = filepath_directory_split[1]
  195. directory, filename = os.path.split(filepath)
  196. line = ""
  197. if len(module_split) > 1:
  198. line = int(module_split[1].lstrip("line "))
  199. function = ""
  200. if len(module_split) > 2:
  201. function = module_split[2].lstrip("in ")
  202. code = ""
  203. if len(module) > 1:
  204. code = module[1].lstrip(" ")
  205. # Using this workaround for a cross-platform path splitting
  206. split_path = []
  207. folder_name = ""
  208. # Split until reach folder "cura"
  209. while folder_name != "cura":
  210. directory, folder_name = os.path.split(directory)
  211. if not folder_name:
  212. break
  213. split_path.append(folder_name)
  214. # Look for plugins. If it's not a plugin, the current cura version is set
  215. isPlugin = False
  216. module_version = self.cura_version
  217. module_name = "Cura"
  218. if split_path.__contains__("plugins"):
  219. isPlugin = True
  220. # Look backwards until plugin.json is found
  221. directory, name = os.path.split(filepath)
  222. while not os.listdir(directory).__contains__("plugin.json"):
  223. directory, name = os.path.split(directory)
  224. json_metadata_file = os.path.join(directory, "plugin.json")
  225. try:
  226. with open(json_metadata_file, "r", encoding = "utf-8") as f:
  227. try:
  228. metadata = json.loads(f.read())
  229. module_version = metadata["version"]
  230. module_name = metadata["name"]
  231. except json.decoder.JSONDecodeError:
  232. # Not throw new exceptions
  233. Logger.logException("e", "Failed to parse plugin.json for plugin %s", name)
  234. except:
  235. # Not throw new exceptions
  236. pass
  237. exception_dict = dict()
  238. exception_dict["traceback"] = {"summary": summary, "full_trace": trace}
  239. exception_dict["location"] = {"path": filepath, "file": filename, "function": function, "code": code, "line": line,
  240. "module_name": module_name, "version": module_version, "is_plugin": isPlugin}
  241. self.data["exception"] = exception_dict
  242. return group
  243. def _logInfoWidget(self):
  244. group = QGroupBox()
  245. group.setTitle(catalog.i18nc("@title:groupbox", "Logs"))
  246. layout = QVBoxLayout()
  247. text_area = QTextEdit()
  248. tmp_file_fd, tmp_file_path = tempfile.mkstemp(prefix = "cura-crash", text = True)
  249. os.close(tmp_file_fd)
  250. with open(tmp_file_path, "w", encoding = "utf-8") as f:
  251. faulthandler.dump_traceback(f, all_threads=True)
  252. with open(tmp_file_path, "r", encoding = "utf-8") as f:
  253. logdata = f.read()
  254. text_area.setText(logdata)
  255. text_area.setReadOnly(True)
  256. layout.addWidget(text_area)
  257. group.setLayout(layout)
  258. self.data["log"] = logdata
  259. return group
  260. def _userDescriptionWidget(self):
  261. group = QGroupBox()
  262. group.setTitle(catalog.i18nc("@title:groupbox", "User description" +
  263. " (Note: Developers may not speak your language, please use English if possible)"))
  264. layout = QVBoxLayout()
  265. # When sending the report, the user comments will be collected
  266. self.user_description_text_area = QTextEdit()
  267. self.user_description_text_area.setFocus(True)
  268. layout.addWidget(self.user_description_text_area)
  269. group.setLayout(layout)
  270. return group
  271. def _buttonsWidget(self):
  272. buttons = QDialogButtonBox()
  273. buttons.addButton(QDialogButtonBox.Close)
  274. # Like above, this will be served as a separate detailed report dialog if the application has not yet been
  275. # fully loaded. In this case, "send report" will be a check box in the early crash dialog, so there is no
  276. # need for this extra button.
  277. if self.has_started:
  278. buttons.addButton(catalog.i18nc("@action:button", "Send report"), QDialogButtonBox.AcceptRole)
  279. buttons.accepted.connect(self._sendCrashReport)
  280. buttons.rejected.connect(self.dialog.close)
  281. return buttons
  282. def _sendCrashReport(self):
  283. # Before sending data, the user comments are stored
  284. self.data["user_info"] = self.user_description_text_area.toPlainText()
  285. # Convert data to bytes
  286. binary_data = json.dumps(self.data).encode("utf-8")
  287. # Submit data
  288. kwoptions = {"data": binary_data, "timeout": 5}
  289. if Platform.isOSX():
  290. kwoptions["context"] = ssl._create_unverified_context()
  291. Logger.log("i", "Sending crash report info to [%s]...", self.crash_url)
  292. if not self.has_started:
  293. print("Sending crash report info to [%s]...\n" % self.crash_url)
  294. try:
  295. f = urllib.request.urlopen(self.crash_url, **kwoptions)
  296. Logger.log("i", "Sent crash report info.")
  297. if not self.has_started:
  298. print("Sent crash report info.\n")
  299. f.close()
  300. except urllib.error.HTTPError as e:
  301. Logger.logException("e", "An HTTP error occurred while trying to send crash report")
  302. if not self.has_started:
  303. print("An HTTP error occurred while trying to send crash report: %s" % e)
  304. except Exception as e: # We don't want any exception to cause problems
  305. Logger.logException("e", "An exception occurred while trying to send crash report")
  306. if not self.has_started:
  307. print("An exception occurred while trying to send crash report: %s" % e)
  308. os._exit(1)
  309. def show(self):
  310. # must run the GUI code on the Qt thread, otherwise the widgets on the dialog won't react correctly.
  311. Application.getInstance().callLater(self._show)
  312. def _show(self):
  313. # When the exception is in the skip_exception_types list, the dialog is not created, so we don't need to show it
  314. if self.dialog:
  315. self.dialog.exec_()
  316. os._exit(1)