You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ErrorManager.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. /*
  2. * Copyright (c) 2006-2014 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. package com.dmdirc.logger;
  23. import com.dmdirc.events.AppErrorEvent;
  24. import com.dmdirc.events.UserErrorEvent;
  25. import com.dmdirc.interfaces.config.AggregateConfigProvider;
  26. import com.dmdirc.interfaces.config.ConfigChangeListener;
  27. import com.dmdirc.ui.FatalErrorDialog;
  28. import com.dmdirc.util.collections.ListenerList;
  29. import com.google.common.eventbus.EventBus;
  30. import com.google.common.eventbus.Subscribe;
  31. import java.awt.GraphicsEnvironment;
  32. import java.util.Date;
  33. import java.util.LinkedList;
  34. import java.util.List;
  35. import java.util.concurrent.BlockingQueue;
  36. import java.util.concurrent.LinkedBlockingQueue;
  37. import java.util.concurrent.atomic.AtomicLong;
  38. import net.kencochrane.raven.DefaultRavenFactory;
  39. import net.kencochrane.raven.RavenFactory;
  40. /**
  41. * Error manager.
  42. */
  43. public class ErrorManager implements ConfigChangeListener {
  44. /** Previously instantiated instance of ErrorManager. */
  45. private static ErrorManager me;
  46. /** A list of exceptions which we don't consider bugs and thus don't report. */
  47. private static final Class<?>[] BANNED_EXCEPTIONS = new Class<?>[]{
  48. NoSuchMethodError.class, NoClassDefFoundError.class,
  49. UnsatisfiedLinkError.class, AbstractMethodError.class,
  50. IllegalAccessError.class, OutOfMemoryError.class,
  51. NoSuchFieldError.class,};
  52. /** Whether or not to send error reports. */
  53. private boolean sendReports;
  54. /** Whether or not to log error reports. */
  55. private boolean logReports;
  56. /** Queue of errors to be reported. */
  57. private final BlockingQueue<ProgramError> reportQueue = new LinkedBlockingQueue<>();
  58. /** Thread used for sending errors. */
  59. private volatile Thread reportThread;
  60. /** Error list. */
  61. private final List<ProgramError> errors;
  62. /** Listener list. */
  63. private final ListenerList errorListeners = new ListenerList();
  64. /** Next error ID. */
  65. private final AtomicLong nextErrorID;
  66. /** Config to read settings from. */
  67. private AggregateConfigProvider config;
  68. /** Directory to store errors in. */
  69. private String errorsDirectory;
  70. /** Creates a new instance of ErrorListDialog. */
  71. public ErrorManager() {
  72. errors = new LinkedList<>();
  73. nextErrorID = new AtomicLong();
  74. }
  75. /**
  76. * Initialises the error manager.
  77. *
  78. * @param globalConfig The configuration to read settings from.
  79. * @param directory The directory to store errors in, if enabled.
  80. * @param eventBus The event bus to listen for error events on.
  81. */
  82. public void initialise(final AggregateConfigProvider globalConfig, final String directory,
  83. final EventBus eventBus) {
  84. eventBus.register(this);
  85. RavenFactory.registerFactory(new DefaultRavenFactory());
  86. config = globalConfig;
  87. config.addChangeListener("general", "logerrors", this);
  88. config.addChangeListener("general", "submitErrors", this);
  89. config.addChangeListener("temp", "noerrorreporting", this);
  90. updateSettings();
  91. errorsDirectory = directory;
  92. // Loop through any existing errors and send/save them per the config.
  93. for (ProgramError error : errors) {
  94. if (sendReports && error.getReportStatus() == ErrorReportStatus.WAITING) {
  95. sendError(error);
  96. }
  97. if (logReports) {
  98. error.save(errorsDirectory);
  99. }
  100. }
  101. }
  102. /**
  103. * Returns the instance of ErrorManager.
  104. *
  105. * @return Instance of ErrorManager
  106. */
  107. public static synchronized ErrorManager getErrorManager() {
  108. if (me == null) {
  109. me = new ErrorManager();
  110. }
  111. return me;
  112. }
  113. /**
  114. * Sets the singleton instance of the error manager.
  115. *
  116. * @param errorManager The error manager to use.
  117. */
  118. public static void setErrorManager(final ErrorManager errorManager) {
  119. me = errorManager;
  120. }
  121. @Subscribe
  122. public void handleAppErrorEvent(final AppErrorEvent appError) {
  123. addError(appError.getLevel(), appError.getMessage(), appError.getThrowable(),
  124. appError.getDetails(), true, isValidError(appError.getThrowable()));
  125. }
  126. @Subscribe
  127. public void handleUserErrorEvent(final UserErrorEvent userError) {
  128. addError(userError.getLevel(), userError.getMessage(), userError.getThrowable(),
  129. userError.getDetails(), false, isValidError(userError.getThrowable()));
  130. }
  131. /**
  132. * Adds a new error to the manager with the specified details. It is assumed that errors without
  133. * exceptions or details are not application errors.
  134. *
  135. * @param level The severity of the error
  136. * @param message The error message
  137. *
  138. * @since 0.6.3m1
  139. */
  140. protected void addError(final ErrorLevel level, final String message) {
  141. addError(level, message, (String) null, false);
  142. }
  143. /**
  144. * Adds a new error to the manager with the specified details.
  145. *
  146. * @param level The severity of the error
  147. * @param message The error message
  148. * @param exception The exception that caused this error
  149. * @param appError Whether or not this is an application error
  150. *
  151. * @since 0.6.3m1
  152. */
  153. protected void addError(final ErrorLevel level, final String message,
  154. final Throwable exception, final boolean appError) {
  155. addError(level, message, exception, null, appError, isValidError(exception));
  156. }
  157. /**
  158. * Adds a new error to the manager with the specified details.
  159. *
  160. * @param level The severity of the error
  161. * @param message The error message
  162. * @param details The details of the exception
  163. * @param appError Whether or not this is an application error
  164. *
  165. * @since 0.6.3m1
  166. */
  167. protected void addError(final ErrorLevel level, final String message, final String details,
  168. final boolean appError) {
  169. addError(level, message, null, details, appError, true);
  170. }
  171. /**
  172. * Adds a new error to the manager with the specified details.
  173. *
  174. * @param level The severity of the error
  175. * @param message The error message
  176. * @param exception The exception that caused the error, if any.
  177. * @param details The details of the exception, if any.
  178. * @param appError Whether or not this is an application error
  179. * @param canReport Whether or not this error can be reported
  180. *
  181. * @since 0.6.3m1
  182. */
  183. protected void addError(final ErrorLevel level, final String message,
  184. final Throwable exception, final String details, final boolean appError,
  185. final boolean canReport) {
  186. addError(getError(level, message, exception, details), appError, canReport);
  187. }
  188. protected void addError(
  189. final ProgramError error,
  190. final boolean appError,
  191. final boolean canReport) {
  192. final boolean dupe = addError(error);
  193. if (error.getLevel().equals(ErrorLevel.FATAL)) {
  194. if (dupe) {
  195. error.setReportStatus(ErrorReportStatus.NOT_APPLICABLE);
  196. }
  197. } else if (!canReport || (appError && !error.isValidSource())) {
  198. error.setReportStatus(ErrorReportStatus.NOT_APPLICABLE);
  199. } else if (!appError) {
  200. error.setReportStatus(ErrorReportStatus.NOT_APPLICABLE);
  201. } else if (dupe) {
  202. error.setReportStatus(ErrorReportStatus.NOT_APPLICABLE);
  203. } else if (sendReports) {
  204. sendError(error);
  205. }
  206. if (logReports) {
  207. error.save(errorsDirectory);
  208. }
  209. if (!dupe) {
  210. if (error.getLevel() == ErrorLevel.FATAL) {
  211. fireFatalError(error);
  212. } else {
  213. fireErrorAdded(error);
  214. }
  215. }
  216. }
  217. /**
  218. * Adds the specified error to the list of known errors and determines if it was previously
  219. * added.
  220. *
  221. * @param error The error to be added
  222. *
  223. * @return True if a duplicate error has already been registered, false otherwise
  224. */
  225. protected boolean addError(final ProgramError error) {
  226. int index;
  227. synchronized (errors) {
  228. index = errors.indexOf(error);
  229. if (index == -1) {
  230. errors.add(error);
  231. } else {
  232. errors.get(index).updateLastDate();
  233. }
  234. }
  235. return index > -1;
  236. }
  237. /**
  238. * Retrieves a {@link ProgramError} that represents the specified details.
  239. *
  240. * @param level The severity of the error
  241. * @param message The error message
  242. * @param exception The exception that caused the error.
  243. * @param details The details of the exception
  244. *
  245. * @since 0.6.3m1
  246. * @return A corresponding ProgramError
  247. */
  248. protected ProgramError getError(final ErrorLevel level, final String message,
  249. final Throwable exception, final String details) {
  250. return new ProgramError(nextErrorID.getAndIncrement(), level, message, exception,
  251. details, new Date());
  252. }
  253. /**
  254. * Determines whether or not the specified exception is one that we are willing to report.
  255. *
  256. * @param exception The exception to test
  257. *
  258. * @since 0.6.3m1
  259. * @return True if the exception may be reported, false otherwise
  260. */
  261. protected boolean isValidError(final Throwable exception) {
  262. Throwable target = exception;
  263. while (target != null) {
  264. for (Class<?> bad : BANNED_EXCEPTIONS) {
  265. if (bad.equals(target.getClass())) {
  266. return false;
  267. }
  268. }
  269. target = target.getCause();
  270. }
  271. return true;
  272. }
  273. /**
  274. * Sends an error to the developers.
  275. *
  276. * @param error error to be sent
  277. */
  278. public void sendError(final ProgramError error) {
  279. if (error.getReportStatus() != ErrorReportStatus.ERROR
  280. && error.getReportStatus() != ErrorReportStatus.WAITING) {
  281. return;
  282. }
  283. error.setReportStatus(ErrorReportStatus.QUEUED);
  284. reportQueue.add(error);
  285. if (reportThread == null || !reportThread.isAlive()) {
  286. reportThread = new ErrorReportingThread(reportQueue);
  287. reportThread.start();
  288. }
  289. }
  290. /**
  291. * Called when an error needs to be deleted from the list.
  292. *
  293. * @param error ProgramError that changed
  294. */
  295. public void deleteError(final ProgramError error) {
  296. synchronized (errors) {
  297. errors.remove(error);
  298. }
  299. fireErrorDeleted(error);
  300. }
  301. /**
  302. * Deletes all errors from the manager.
  303. *
  304. * @since 0.6.3m1
  305. */
  306. public void deleteAll() {
  307. synchronized (errors) {
  308. for (ProgramError error : errors) {
  309. fireErrorDeleted(error);
  310. }
  311. errors.clear();
  312. }
  313. }
  314. /**
  315. * Returns the number of errors.
  316. *
  317. * @return Number of ProgramErrors
  318. */
  319. public int getErrorCount() {
  320. return errors.size();
  321. }
  322. /**
  323. * Returns the list of program errors.
  324. *
  325. * @return Program error list
  326. */
  327. public List<ProgramError> getErrors() {
  328. synchronized (errors) {
  329. return new LinkedList<>(errors);
  330. }
  331. }
  332. /**
  333. * Adds an ErrorListener to the listener list.
  334. *
  335. * @param listener Listener to add
  336. */
  337. public void addErrorListener(final ErrorListener listener) {
  338. if (listener == null) {
  339. return;
  340. }
  341. errorListeners.add(ErrorListener.class, listener);
  342. }
  343. /**
  344. * Removes an ErrorListener from the listener list.
  345. *
  346. * @param listener Listener to remove
  347. */
  348. public void removeErrorListener(final ErrorListener listener) {
  349. errorListeners.remove(ErrorListener.class, listener);
  350. }
  351. /**
  352. * Fired when the program encounters an error.
  353. *
  354. * @param error Error that occurred
  355. */
  356. protected void fireErrorAdded(final ProgramError error) {
  357. for (ErrorListener listener : errorListeners.get(ErrorListener.class)) {
  358. if (listener.isReady()) {
  359. error.setHandled();
  360. listener.errorAdded(error);
  361. }
  362. }
  363. if (!error.isHandled()) {
  364. System.err.println("An error has occurred: " + error.getLevel()
  365. + ": " + error.getMessage());
  366. for (String line : error.getTrace()) {
  367. System.err.println("\t" + line);
  368. }
  369. }
  370. }
  371. /**
  372. * Fired when the program encounters a fatal error.
  373. *
  374. * @param error Error that occurred
  375. */
  376. protected void fireFatalError(final ProgramError error) {
  377. final boolean restart;
  378. if (GraphicsEnvironment.isHeadless()) {
  379. System.err.println("A fatal error has occurred: " + error.getMessage());
  380. for (String line : error.getTrace()) {
  381. System.err.println("\t" + line);
  382. }
  383. restart = false;
  384. } else {
  385. final FatalErrorDialog fed = new FatalErrorDialog(error);
  386. fed.setVisible(true);
  387. try {
  388. synchronized (fed) {
  389. while (fed.isWaiting()) {
  390. fed.wait();
  391. }
  392. }
  393. } catch (InterruptedException ex) {
  394. //Oh well, carry on
  395. }
  396. restart = fed.getRestart();
  397. }
  398. try {
  399. synchronized (error) {
  400. while (!error.getReportStatus().isTerminal()) {
  401. error.wait();
  402. }
  403. }
  404. } catch (InterruptedException ex) {
  405. // Do nothing
  406. }
  407. if (restart) {
  408. System.exit(42);
  409. } else {
  410. System.exit(1);
  411. }
  412. }
  413. /**
  414. * Fired when an error is deleted.
  415. *
  416. * @param error Error that has been deleted
  417. */
  418. protected void fireErrorDeleted(final ProgramError error) {
  419. for (ErrorListener listener : errorListeners.get(ErrorListener.class)) {
  420. listener.errorDeleted(error);
  421. }
  422. }
  423. /**
  424. * Fired when an error's status is changed.
  425. *
  426. * @param error Error that has been altered
  427. */
  428. protected void fireErrorStatusChanged(final ProgramError error) {
  429. for (ErrorListener listener : errorListeners.get(ErrorListener.class)) {
  430. listener.errorStatusChanged(error);
  431. }
  432. }
  433. @Override
  434. public void configChanged(final String domain, final String key) {
  435. updateSettings();
  436. }
  437. /** Updates the settings used by this error manager. */
  438. protected void updateSettings() {
  439. try {
  440. sendReports = config.getOptionBool("general", "submitErrors")
  441. && !config.getOptionBool("temp", "noerrorreporting");
  442. logReports = config.getOptionBool("general", "logerrors");
  443. } catch (IllegalArgumentException ex) {
  444. sendReports = false;
  445. logReports = true;
  446. }
  447. }
  448. }