CrashHandler.py 17 KB

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