-
Notifications
You must be signed in to change notification settings - Fork 88
/
ClassLoaderLeakPreventor.java
1197 lines (1027 loc) · 44.8 KB
/
ClassLoaderLeakPreventor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2012 Mattias Jiderhamn
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package se.jiderhamn.classloader.leak.prevention;
import java.beans.PropertyEditorManager;
import java.lang.management.ManagementFactory;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Authenticator;
import java.net.URL;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.ThreadPoolExecutor;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.servlet.*;
/**
* This class helps prevent classloader leaks.
* <h1>Basic setup</h1>
* <p>Activate protection by adding this class as a context listener
* in your <code>web.xml</code>, like this:</p>
* <pre>
* <listener>
* <listener-class>se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor</listener-class>
* </listener>
* </pre>
*
* You should usually declare this <code>listener</code> before any other listeners, to make it "outermost".
*
* <h1>Configuration</h1>
* The context listener has a number of settings that can be configured with context parameters in <code>web.xml</code>,
* i.e.:
*
* <pre>
* <context-param>
* <param-name>ClassLoaderLeakPreventor.stopThreads</param-name>
* <param-value>false</param-value>
* </context-param>
* </pre>
*
* The available settings are
* <table border="1">
* <tr>
* <th>Parameter name</th>
* <th>Default value</th>
* <th>Description</th>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.stopThreads</code></td>
* <td><code>true</code></td>
* <td>Should threads tied to the web app classloader be forced to stop at application shutdown?</td>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.stopTimerThreads</code></td>
* <td><code>true</code></td>
* <td>Should Timer threads tied to the web app classloader be forced to stop at application shutdown?</td>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.executeShutdownHooks</td>
* <td><code>true</code></td>
* <td>Should shutdown hooks registered from the application be executed at application shutdown?</td>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.threadWaitMs</td>
* <td><code>5000</code> (5 seconds)</td>
* <td>No of milliseconds to wait for threads to finish execution, before stopping them.</td>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.shutdownHookWaitMs</code></td>
* <td><code>10000</code> (10 seconds)</td>
* <td>
* No of milliseconds to wait for shutdown hooks to finish execution, before stopping them.
* If set to -1 there will be no waiting at all, but Thread is allowed to run until finished.
* </td>
* </tr>
* </table>
*
*
* <h1>License</h1>
* <p>This code is licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2</a> license,
* which allows you to include modified versions of the code in your distributed software, without having to release
* your source code.</p>
*
* <h1>More info</h1>
* <p>For more info, see
* <a href="http://java.jiderhamn.se/2012/03/04/classloader-leaks-vi-this-means-war-leak-prevention-library/">here</a>.
* </p>
*
* <h1>Design goals</h1>
* <p>If you want to help improve this component, you should be aware of the design goals</p>
* <p>
* Primary design goal: Zero dependencies. The component should build and run using nothing but the JDK and the
* Servlet API. Specifically we should <b>not</b> depend on any logging framework, since they are part of the problem.
* We also don't want to use any utility libraries, in order not to impose any further dependencies into any project
* that just wants to get rid of classloader leaks.
* Access to anything outside of the standard JDK (in order to prevent a known leak) should be managed
* with reflection.
* </p>
* <p>
* Secondary design goal: Keep the runtime component in a single <code>.java</code> file. It should be possible to
* just add this one <code>.java</code> file into your own source tree.
* </p>
*
* @author Mattias Jiderhamn, 2012
*/
public class ClassLoaderLeakPreventor implements javax.servlet.ServletContextListener {
/** Default no of milliseconds to wait for threads to finish execution */
public static final int THREAD_WAIT_MS_DEFAULT = 5 * 1000; // 5 seconds
/** Default no of milliseconds to wait for shutdown hook to finish execution */
public static final int SHUTDOWN_HOOK_WAIT_MS_DEFAULT = 10 * 1000; // 10 seconds
///////////
// Settings
/** Should threads tied to the web app classloader be forced to stop at application shutdown? */
protected boolean stopThreads = true;
/** Should Timer threads tied to the web app classloader be forced to stop at application shutdown? */
protected boolean stopTimerThreads = true;
/** Should shutdown hooks registered from the application be executed at application shutdown? */
protected boolean executeShutdownHooks = true;
/**
* No of milliseconds to wait for threads to finish execution, before stopping them.
*/
protected int threadWaitMs = SHUTDOWN_HOOK_WAIT_MS_DEFAULT;
/**
* No of milliseconds to wait for shutdown hooks to finish execution, before stopping them.
* If set to -1 there will be no waiting at all, but Thread is allowed to run until finished.
*/
protected int shutdownHookWaitMs = SHUTDOWN_HOOK_WAIT_MS_DEFAULT;
/** Is it possible, that we are running under JBoss? */
private boolean mayBeJBoss = false;
protected final Field java_lang_Thread_threadLocals;
protected final Field java_lang_Thread_inheritableThreadLocals;
protected final Field java_lang_ThreadLocal$ThreadLocalMap_table;
protected Field java_lang_ThreadLocal$ThreadLocalMap$Entry_value;
public ClassLoaderLeakPreventor() {
// Initialize some reflection variables
java_lang_Thread_threadLocals = findField(Thread.class, "threadLocals");
java_lang_Thread_inheritableThreadLocals = findField(Thread.class, "inheritableThreadLocals");
java_lang_ThreadLocal$ThreadLocalMap_table = findFieldOfClass("java.lang.ThreadLocal$ThreadLocalMap", "table");
if(java_lang_Thread_threadLocals == null)
error("java.lang.Thread.threadLocals not found; something is seriously wrong!");
if(java_lang_Thread_inheritableThreadLocals == null)
error("java.lang.Thread.inheritableThreadLocals not found; something is seriously wrong!");
if(java_lang_ThreadLocal$ThreadLocalMap_table == null)
error("java.lang.ThreadLocal$ThreadLocalMap.table not found; something is seriously wrong!");
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Implement javax.servlet.ServletContextListener
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public void contextInitialized(ServletContextEvent servletContextEvent) {
final ServletContext servletContext = servletContextEvent.getServletContext();
stopThreads = ! "false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopThreads"));
stopTimerThreads = ! "false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopTimerThreads"));
executeShutdownHooks = ! "false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.executeShutdownHooks"));
threadWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.threadWaitMs", THREAD_WAIT_MS_DEFAULT);
shutdownHookWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.shutdownHookWaitMs", SHUTDOWN_HOOK_WAIT_MS_DEFAULT);
info("Settings for " + this.getClass().getName() + " (CL: 0x" +
Integer.toHexString(System.identityHashCode(getWebApplicationClassLoader())) + "):");
info(" stopThreads = " + stopThreads);
info(" stopTimerThreads = " + stopTimerThreads);
info(" executeShutdownHooks = " + executeShutdownHooks);
info(" threadWaitMs = " + threadWaitMs + " ms");
info(" shutdownHookWaitMs = " + shutdownHookWaitMs + " ms");
final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
try {
// If package org.jboss is found, we may be running under JBoss
mayBeJBoss = (contextClassLoader.getResource("org/jboss") != null);
}
catch(Exception ex) {
// Do nothing
}
info("Initializing context by loading some known offenders with system classloader");
// This part is heavily inspired by Tomcats JreMemoryLeakPreventionListener
// See http://svn.apache.org/viewvc/tomcat/trunk/java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java?view=markup
try {
// Switch to system classloader in before we load/call some JRE stuff that will cause
// the current classloader to be available for gerbage collection
Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
java.awt.Toolkit.getDefaultToolkit(); // Will start a Thread
java.security.Security.getProviders();
java.sql.DriverManager.getDrivers(); // Load initial drivers using system classloader
javax.imageio.ImageIO.getCacheDirectory(); // Will call sun.awt.AppContext.getAppContext()
try {
Class.forName("javax.security.auth.Policy")
.getMethod("getPolicy")
.invoke(null);
}
catch (IllegalAccessException iaex) {
error(iaex);
}
catch (InvocationTargetException itex) {
error(itex);
}
catch (NoSuchMethodException nsmex) {
error(nsmex);
}
catch (ClassNotFoundException e) {
// Ignore silently - class is deprecated
}
try {
javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder();
}
catch (Exception ex) { // Example: ParserConfigurationException
error(ex);
}
try {
Class.forName("javax.xml.bind.DatatypeConverterImpl"); // Since JDK 1.6. May throw java.lang.Error
}
catch (ClassNotFoundException e) {
// Do nothing
}
try {
Class.forName("javax.security.auth.login.Configuration", true, ClassLoader.getSystemClassLoader());
}
catch (ClassNotFoundException e) {
// Do nothing
}
// This probably does not affect classloaders, but prevents some problems with .jar files
try {
// URL needs to be well-formed, but does not need to exist
new URL("jar:file://dummy.jar!/").openConnection().setDefaultUseCaches(false);
}
catch (Exception ex) {
error(ex);
}
/////////////////////////////////////////////////////
// Load Sun specific classes that may cause leaks
final boolean isSunJRE = System.getProperty("java.vendor").startsWith("Sun");
try {
Class.forName("com.sun.jndi.ldap.LdapPoolManager");
}
catch(ClassNotFoundException cnfex) {
if(isSunJRE)
error(cnfex);
}
try {
Class.forName("sun.java2d.Disposer"); // Will start a Thread
}
catch (ClassNotFoundException cnfex) {
if(isSunJRE && ! mayBeJBoss) // JBoss blocks this package/class, so don't warn
error(cnfex);
}
try {
Class<?> gcClass = Class.forName("sun.misc.GC");
final Method requestLatency = gcClass.getDeclaredMethod("requestLatency", long.class);
requestLatency.invoke(null, 3600000L);
}
catch (ClassNotFoundException cnfex) {
if(isSunJRE)
error(cnfex);
}
catch (NoSuchMethodException nsmex) {
error(nsmex);
}
catch (IllegalAccessException iaex) {
error(iaex);
}
catch (InvocationTargetException itex) {
error(itex);
}
}
finally {
// Reset original classloader
Thread.currentThread().setContextClassLoader(contextClassLoader);
}
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
final boolean jvmIsShuttingDown = isJvmShuttingDown();
if(jvmIsShuttingDown) {
info("JVM is shutting down - skip cleanup");
return; // Don't do anything more
}
info(getClass().getName() + " shutting down context by removing known leaks (CL: 0x" +
Integer.toHexString(System.identityHashCode(getWebApplicationClassLoader())) + ")");
//////////////////
// Fix known leaks
//////////////////
java.beans.Introspector.flushCaches(); // Clear cache of strong references
// Apache Commons Pool can leave unfinished threads. Anything specific we can do?
clearBeanELResolverCache();
fixBeanValidationApiLeak();
fixGeoToolsLeak();
// Can we do anything about Google Guice ?
// Can we do anything about Groovy http://jira.codehaus.org/browse/GROOVY-4154 ?
clearIntrospectionUtilsCache();
// Can we do anything about Logback http://jira.qos.ch/browse/LBCORE-205 ?
////////////////////
// Fix generic leaks
// Deregister JDBC drivers contained in web application
deregisterJdbcDrivers();
// Unregister MBeans loaded by the web application class loader
unregisterMBeans();
// Deregister shutdown hooks - execute them immediately
deregisterShutdownHooks();
deregisterPropertyEditors();
deregisterSecurityProviders();
clearDefaultAuthenticator();
deregisterRmiTargets();
clearThreadLocalsOfAllThreads();
stopThreads();
unsetCachedKeepAliveTimer();
try {
try { // First try Java 1.6 method
final Method clearCache16 = ResourceBundle.class.getMethod("clearCache", ClassLoader.class);
debug("Since Java 1.6+ is used, we can call " + clearCache16);
clearCache16.invoke(null, getWebApplicationClassLoader());
}
catch (NoSuchMethodException e) {
// Not Java 1.6+, we have to clear manually
final Map<?,?> cacheList = getStaticFieldValue(ResourceBundle.class, "cacheList"); // Java 5: SoftCache extends AbstractMap
final Iterator<?> iter = cacheList.keySet().iterator();
Field loaderRefField = null;
while(iter.hasNext()) {
Object key = iter.next(); // CacheKey
if(loaderRefField == null) { // First time
loaderRefField = key.getClass().getDeclaredField("loaderRef");
loaderRefField.setAccessible(true);
}
WeakReference<ClassLoader> loaderRef = (WeakReference<ClassLoader>) loaderRefField.get(key); // LoaderReference extends WeakReference
ClassLoader classLoader = loaderRef.get();
if(isWebAppClassLoaderOrChild(classLoader)) {
info("Removing ResourceBundle from cache: " + key);
iter.remove();
}
}
}
}
catch(Exception ex) {
error(ex);
}
// (CacheKey of java.util.ResourceBundle.NONEXISTENT_BUNDLE will point to first referring classloader...)
// Release this classloader from Apache Commons Logging (ACL) by calling
// LogFactory.release(getCurrentClassLoader());
// Use reflection in case ACL is not present.
// Do this last, in case other shutdown procedures want to log something.
final Class logFactory = findClass("org.apache.commons.logging.LogFactory");
if(logFactory != null) { // Apache Commons Logging present
info("Releasing web app classloader from Apache Commons Logging");
try {
logFactory.getMethod("release", java.lang.ClassLoader.class)
.invoke(null, getWebApplicationClassLoader());
}
catch (Exception ex) {
error(ex);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Fix generic leaks
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/** Deregister JDBC drivers loaded by web app classloader */
public void deregisterJdbcDrivers() {
final List<Driver> driversToDeregister = new ArrayList<Driver>();
final Enumeration<Driver> allDrivers = DriverManager.getDrivers();
while(allDrivers.hasMoreElements()) {
final Driver driver = allDrivers.nextElement();
if(isLoadedInWebApplication(driver)) // Should be true for all returned by DriverManager.getDrivers()
driversToDeregister.add(driver);
}
for(Driver driver : driversToDeregister) {
try {
warn("JDBC driver loaded by web app deregistered: " + driver.getClass());
DriverManager.deregisterDriver(driver);
}
catch (SQLException e) {
error(e);
}
}
}
/** Unregister MBeans loaded by the web application class loader */
protected void unregisterMBeans() {
try {
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
final Set<ObjectName> allMBeanNames = mBeanServer.queryNames(new ObjectName("*:*"), null);
for(ObjectName objectName : allMBeanNames) {
try {
final ClassLoader mBeanClassLoader = mBeanServer.getClassLoaderFor(objectName);
if(isWebAppClassLoaderOrChild(mBeanClassLoader)) { // MBean loaded in web application
warn("MBean '" + objectName + "' was loaded in web application; unregistering");
mBeanServer.unregisterMBean(objectName);
}
}
catch(Exception e) { // MBeanRegistrationException / InstanceNotFoundException
error(e);
}
}
}
catch (Exception e) { // MalformedObjectNameException
error(e);
}
}
/** Find and deregister shutdown hooks. Will by default execute the hooks after removing them. */
protected void deregisterShutdownHooks() {
// We will not remove known shutdown hooks, since loading the owning class of the hook,
// may register the hook if previously unregistered
Map<Thread, Thread> shutdownHooks = (Map<Thread, Thread>) getStaticFieldValue("java.lang.ApplicationShutdownHooks", "hooks");
if(shutdownHooks != null) { // Could be null during JVM shutdown, which we already avoid, but be extra precautious
// Iterate copy to avoid ConcurrentModificationException
for(Thread shutdownHook : new ArrayList<Thread>(shutdownHooks.keySet())) {
if(isThreadInWebApplication(shutdownHook)) { // Planned to run in web app
removeShutdownHook(shutdownHook);
}
}
}
}
/** Deregister shutdown hook and execute it immediately */
@SuppressWarnings("deprecation")
protected void removeShutdownHook(Thread shutdownHook) {
final String displayString = "'" + shutdownHook + "' of type " + shutdownHook.getClass().getName();
error("Removing shutdown hook: " + displayString);
Runtime.getRuntime().removeShutdownHook(shutdownHook);
if(executeShutdownHooks) { // Shutdown hooks should be executed
info("Executing shutdown hook now: " + displayString);
// Make sure it's from this web app instance
shutdownHook.start(); // Run cleanup immediately
if(shutdownHookWaitMs > 0) { // Wait for shutdown hook to finish
try {
shutdownHook.join(shutdownHookWaitMs); // Wait for thread to run
}
catch (InterruptedException e) {
// Do nothing
}
if(shutdownHook.isAlive()) {
warn(shutdownHook + "still running after " + shutdownHookWaitMs + " ms - Stopping!");
shutdownHook.stop();
}
}
}
}
/** Deregister custom property editors */
protected void deregisterPropertyEditors() {
final Field registryField = findField(PropertyEditorManager.class, "registry");
if(registryField == null) {
error("Internal registry of " + PropertyEditorManager.class.getName() + " not found");
}
else {
try {
synchronized (PropertyEditorManager.class) {
final Map<Class<?>, Class<?>> registry = (Map) registryField.get(null);
if(registry != null) { // Initialized
final Set<Class> toRemove = new HashSet<Class>();
for(Map.Entry<Class<?>, Class<?>> entry : registry.entrySet()) {
if(isLoadedByWebApplication(entry.getKey()) ||
isLoadedByWebApplication(entry.getValue())) { // More likely
toRemove.add(entry.getKey());
}
}
for(Class clazz : toRemove) {
warn("Property editor for type " + clazz + " = " + registry.get(clazz) + " needs to be deregistered");
PropertyEditorManager.registerEditor(clazz, null); // Deregister
}
}
}
}
catch (Exception e) { // Such as IllegalAccessException
error(e);
}
}
}
/** Deregister custom security providers */
protected void deregisterSecurityProviders() {
final Set<String> providersToRemove = new HashSet<String>();
for(java.security.Provider provider : java.security.Security.getProviders()) {
if(isLoadedInWebApplication(provider)) {
providersToRemove.add(provider.getName());
}
}
if(! providersToRemove.isEmpty()) {
warn("Removing security providers loaded in web app: " + providersToRemove);
for(String providerName : providersToRemove) {
java.security.Security.removeProvider(providerName);
}
}
}
/** Clear the default java.net.Authenticator (in case current one is loaded in web app) */
protected void clearDefaultAuthenticator() {
final Authenticator defaultAuthenticator = getStaticFieldValue(Authenticator.class, "theAuthenticator");
if(defaultAuthenticator == null || // Can both mean not set, or error retrieving, so unset anyway to be safe
isLoadedInWebApplication(defaultAuthenticator)) {
Authenticator.setDefault(null);
}
}
/** This method is heavily inspired by org.apache.catalina.loader.WebappClassLoader.clearReferencesRmiTargets() */
protected void deregisterRmiTargets() {
try {
final Class objectTableClass = findClass("sun.rmi.transport.ObjectTable");
if(objectTableClass != null) {
clearRmiTargetsMap((Map<?, ?>) getStaticFieldValue(objectTableClass, "objTable"));
clearRmiTargetsMap((Map<?, ?>) getStaticFieldValue(objectTableClass, "implTable"));
}
}
catch (Exception ex) {
error(ex);
}
}
/** Iterate RMI Targets Map and remove entries loaded by web app classloader */
protected void clearRmiTargetsMap(Map<?, ?> rmiTargetsMap) {
try {
final Field cclField = findFieldOfClass("sun.rmi.transport.Target", "ccl");
debug("Looping " + rmiTargetsMap.size() + " RMI Targets to find leaks");
for(Iterator<?> iter = rmiTargetsMap.values().iterator(); iter.hasNext(); ) {
Object target = iter.next(); // sun.rmi.transport.Target
ClassLoader ccl = (ClassLoader) cclField.get(target);
if(isWebAppClassLoaderOrChild(ccl)) {
warn("Removing RMI Target: " + target);
iter.remove();
}
}
}
catch (Exception ex) {
error(ex);
}
}
protected void clearThreadLocalsOfAllThreads() {
final ThreadLocalProcessor clearingThreadLocalProcessor = new ClearingThreadLocalProcessor();
for(Thread thread : getAllThreads()) {
forEachThreadLocalInThread(thread, clearingThreadLocalProcessor);
}
}
/**
* Partially inspired by org.apache.catalina.loader.WebappClassLoader.clearReferencesThreads()
*/
@SuppressWarnings("deprecation")
protected void stopThreads() {
final Class<?> workerClass = findClass("java.util.concurrent.ThreadPoolExecutor$Worker");
final Field targetField = findField(Thread.class, "target");
for(Thread thread : getAllThreads()) {
final Runnable target = getFieldValue(targetField, thread);
if(thread != Thread.currentThread() && // Ignore current thread
(isThreadInWebApplication(thread) || isLoadedInWebApplication(target))) {
if(thread.getThreadGroup() != null &&
("system".equals(thread.getThreadGroup().getName()) || // System thread
"RMI Runtime".equals(thread.getThreadGroup().getName()))) { // RMI thread (honestly, just copied from Tomcat)
if("Keep-Alive-Timer".equals(thread.getName())) {
thread.setContextClassLoader(getWebApplicationClassLoader().getParent());
debug("Changed contextClassLoader of HTTP keep alive thread");
}
}
else if(thread.isAlive()) { // Non-system, running in web app
if("java.util.TimerThread".equals(thread.getClass().getName())) {
if(stopTimerThreads) {
warn("Stopping Timer thread running in classloader.");
stopTimerThread(thread);
}
else {
info("Timer thread is running in classloader, but will not be stopped");
}
}
else {
// If threads is running an java.util.concurrent.ThreadPoolExecutor.Worker try shutting down the executor
if(workerClass != null && workerClass.isInstance(target)) {
if(stopThreads) {
warn("Shutting down " + ThreadPoolExecutor.class.getName() + " running within the classloader.");
try {
// java.util.concurrent.ThreadPoolExecutor, introduced in Java 1.5
final Field workerExecutor = findField(workerClass, "this$0");
final ThreadPoolExecutor executor = getFieldValue(workerExecutor, target);
executor.shutdownNow();
}
catch (Exception ex) {
error(ex);
}
}
else
info(ThreadPoolExecutor.class.getName() + " running within the classloader will not be shut down.");
}
final String displayString = "'" + thread + "' of type " + thread.getClass().getName();
if(stopThreads) {
final String waitString = (threadWaitMs > 0) ? "after " + threadWaitMs + " ms " : "";
warn("Stopping Thread " + displayString + " running in web app " + waitString);
if(threadWaitMs > 0) {
try {
thread.join(threadWaitMs); // Wait for thread to run
}
catch (InterruptedException e) {
// Do nothing
}
}
// Normally threads should not be stopped (method is deprecated), since it may cause an inconsistent state.
// In this case however, the alternative is a classloader leak, which may or may not be considered worse.
if(thread.isAlive())
thread.stop();
}
else {
warn("Thread " + displayString + " is still running in web app");
}
}
}
}
}
}
protected void stopTimerThread(Thread thread) {
// Seems it is not possible to access Timer of TimerThread, so we need to mimic Timer.cancel()
/**
try {
Timer timer = (Timer) findField(thread.getClass(), "this$0").get(thread); // This does not work!
warn("Cancelling Timer " + timer + " / TimeThread '" + thread + "'");
timer.cancel();
}
catch (IllegalAccessException iaex) {
error(iaex);
}
*/
try {
final Field newTasksMayBeScheduled = findField(thread.getClass(), "newTasksMayBeScheduled");
final Object queue = findField(thread.getClass(), "queue").get(thread); // java.lang.TaskQueue
final Method clear = queue.getClass().getDeclaredMethod("clear");
clear.setAccessible(true);
// Do what java.util.Timer.cancel() does
//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized (queue) {
newTasksMayBeScheduled.set(thread, false);
clear.invoke(queue);
queue.notify(); // "In case queue was already empty."
}
// We shouldn't need to join() here, thread will finish soon enough
}
catch (Exception ex) {
error(ex);
}
}
/**
* Since Keep-Alive-Timer thread may have terminated, but still be referenced, we need to make sure it does not
* reference this classloader.
*/
protected void unsetCachedKeepAliveTimer() {
Object keepAliveCache = getStaticFieldValue("sun.net.www.http.HttpClient", "kac");
if(keepAliveCache != null) {
final Thread keepAliveTimer = getFieldValue(keepAliveCache, "keepAliveTimer");
if(keepAliveTimer != null) {
if(isWebAppClassLoaderOrChild(keepAliveTimer.getContextClassLoader())) {
keepAliveTimer.setContextClassLoader(getWebApplicationClassLoader().getParent());
error("ContextClassLoader of sun.net.www.http.HttpClient cached Keep-Alive-Timer set to parent instead");
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Fix specific leaks
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/** Clean the cache of BeanELResolver */
protected void clearBeanELResolverCache() {
final Class beanElResolverClass = findClass("javax.el.BeanELResolver");
if(beanElResolverClass != null) {
boolean cleared = false;
try {
final Method purgeBeanClasses = beanElResolverClass.getDeclaredMethod("purgeBeanClasses", ClassLoader.class);
purgeBeanClasses.setAccessible(true);
purgeBeanClasses.invoke(beanElResolverClass.newInstance(), getWebApplicationClassLoader());
cleared = true;
}
catch (NoSuchMethodException e) {
// Version of javax.el probably > 2.2; no real need to clear
}
catch (Exception e) {
error(e);
}
if(! cleared) {
// Fallback, if purgeBeanClasses() could not be called
final Field propertiesField = findField(beanElResolverClass, "properties");
if(propertiesField != null) {
try {
final Map properties = (Map) propertiesField.get(null);
properties.clear();
}
catch (Exception e) {
error(e);
}
}
}
}
}
public void fixBeanValidationApiLeak() {
Class offendingClass = findClass("javax.validation.Validation$DefaultValidationProviderResolver");
if(offendingClass != null) { // Class is present on class path
Field offendingField = findField(offendingClass, "providersPerClassloader");
if(offendingField != null) {
final Object providersPerClassloader = getStaticFieldValue(offendingField);
if(providersPerClassloader instanceof Map) { // Map<ClassLoader, List<ValidationProvider<?>>> in offending code
//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized (providersPerClassloader) {
// Fix the leak!
((Map)providersPerClassloader).remove(getWebApplicationClassLoader());
}
}
}
}
}
/** Shutdown GeoTools cleaner thread as of http://jira.codehaus.org/browse/GEOT-2742 */
protected void fixGeoToolsLeak() {
final Class weakCollectionCleanerClass = findClass("org.geotools.util.WeakCollectionCleaner");
if(weakCollectionCleanerClass != null) {
try {
weakCollectionCleanerClass.getMethod("exit").invoke(null);
}
catch (Exception ex) {
error(ex);
}
}
}
/** Clear IntrospectionUtils caches of Tomcat and Apache Commons Modeler */
protected void clearIntrospectionUtilsCache() {
// Tomcat
final Class tomcatIntrospectionUtils = findClass("org.apache.tomcat.util.IntrospectionUtils");
if(tomcatIntrospectionUtils != null) {
try {
tomcatIntrospectionUtils.getMethod("clear").invoke(null);
}
catch (Exception ex) {
if(! mayBeJBoss) // JBoss includes this class, but no cache and no clear() method
error(ex);
}
}
// Apache Commons Modeler
final Class modelIntrospectionUtils = findClass("org.apache.commons.modeler.util.IntrospectionUtils");
if(modelIntrospectionUtils != null && ! isWebAppClassLoaderOrChild(modelIntrospectionUtils.getClassLoader())) { // Loaded outside web app
try {
modelIntrospectionUtils.getMethod("clear").invoke(null);
}
catch (Exception ex) {
warn("org.apache.commons.modeler.util.IntrospectionUtils needs to be cleared but there was an error, " +
"consider upgrading Apache Commons Modeler");
error(ex);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Utility methods
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
protected ClassLoader getWebApplicationClassLoader() {
return ClassLoaderLeakPreventor.class.getClassLoader();
// Alternative return Thread.currentThread().getContextClassLoader();
}
/** Test if provided object is loaded with web application classloader */
protected boolean isLoadedInWebApplication(Object o) {
return o != null && isLoadedByWebApplication(o.getClass());
}
/** Test if provided class is loaded with web application classloader */
protected boolean isLoadedByWebApplication(Class clazz) {
return clazz != null && isWebAppClassLoaderOrChild(clazz.getClassLoader());
}
/** Test if provided ClassLoader is the classloader of the web application, or a child thereof */
protected boolean isWebAppClassLoaderOrChild(ClassLoader cl) {
final ClassLoader webAppCL = getWebApplicationClassLoader();
// final ClassLoader webAppCL = Thread.currentThread().getContextClassLoader();
while(cl != null) {
if(cl == webAppCL)
return true;
cl = cl.getParent();
}
return false;
}
protected boolean isThreadInWebApplication(Thread thread) {
return isLoadedInWebApplication(thread) || // Custom Thread class in web app
isWebAppClassLoaderOrChild(thread.getContextClassLoader()); // Running in web application
}
protected <E> E getStaticFieldValue(Class clazz, String fieldName) {
Field staticField = findField(clazz, fieldName);
return (staticField != null) ? (E) getStaticFieldValue(staticField) : null;
}
protected <E> E getStaticFieldValue(String className, String fieldName) {
Field staticField = findFieldOfClass(className, fieldName);
return (staticField != null) ? (E) getStaticFieldValue(staticField) : null;
}
protected Field findFieldOfClass(String className, String fieldName) {
Class clazz = findClass(className);
if(clazz != null) {
return findField(clazz, fieldName);
}
else
return null;
}
protected Class findClass(String className) {
try {
return Class.forName(className);
}
// catch (NoClassDefFoundError e) {
// // Silently ignore
// return null;
// }
catch (ClassNotFoundException e) {
// Silently ignore
return null;
}
catch (Exception ex) { // Example SecurityException
warn(ex);
return null;
}
}
protected Field findField(Class clazz, String fieldName) {
if(clazz == null)
return null;
try {
final Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true); // (Field is probably private)
return field;
}
catch (NoSuchFieldException ex) {
// Silently ignore
return null;
}
catch (Exception ex) { // Example SecurityException
warn(ex);
return null;
}
}
protected <T> T getStaticFieldValue(Field field) {
try {
return (T) field.get(null);
}
catch (Exception ex) {
warn(ex);
// Silently ignore
return null;
}
}
protected <T> T getFieldValue(Object obj, String fieldName) {
final Field field = findField(obj.getClass(), fieldName);
return (T) getFieldValue(field, obj);
}
protected <T> T getFieldValue(Field field, Object obj) {
try {
return (T) field.get(obj);
}
catch (Exception ex) {
warn(ex);
// Silently ignore
return null;
}
}
/** Is the JVM currently shutting down? */
protected boolean isJvmShuttingDown() {
try {
final Thread dummy = new Thread(); // Will never be started
Runtime.getRuntime().removeShutdownHook(dummy);
return false;
}
catch (IllegalStateException isex) {
return true; // Shutting down
}
catch (Throwable t) { // Any other Exception, assume we are not shutting down
return false;
}
}
/** Get a Collection with all Threads.
* This method is heavily inspired by org.apache.catalina.loader.WebappClassLoader.getThreads() */
protected Collection<Thread> getAllThreads() {