-
Notifications
You must be signed in to change notification settings - Fork 136
/
ConnectionPool.java
1560 lines (1360 loc) · 61.9 KB
/
ConnectionPool.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 (c) 2022, 2024 Contributors to the Eclipse Foundation
* Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package com.sun.enterprise.resource.pool;
import com.sun.appserv.connectors.internal.api.PoolingException;
import com.sun.enterprise.connectors.ConnectorConnectionPool;
import com.sun.enterprise.connectors.ConnectorRuntime;
import com.sun.enterprise.resource.ResourceHandle;
import com.sun.enterprise.resource.ResourceSpec;
import com.sun.enterprise.resource.ResourceState;
import com.sun.enterprise.resource.allocator.ResourceAllocator;
import com.sun.enterprise.resource.listener.PoolLifeCycleListener;
import com.sun.enterprise.resource.pool.datastructure.DataStructure;
import com.sun.enterprise.resource.pool.datastructure.DataStructureFactory;
import com.sun.enterprise.resource.pool.resizer.Resizer;
import com.sun.enterprise.resource.pool.waitqueue.PoolWaitQueue;
import com.sun.enterprise.resource.pool.waitqueue.PoolWaitQueueFactory;
import com.sun.enterprise.transaction.api.JavaEETransaction;
import com.sun.logging.LogDomains;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ManagedConnection;
import jakarta.resource.spi.RetryableUnavailableException;
import jakarta.transaction.Transaction;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.logging.Logger;
import javax.naming.NamingException;
import org.glassfish.resourcebase.resources.api.PoolInfo;
import static com.sun.appserv.connectors.internal.spi.BadConnectionEventListener.POOL_RECONFIGURED_ERROR_CODE;
import static com.sun.enterprise.connectors.service.ConnectorAdminServiceUtils.getReservePrefixedJNDINameForPool;
import static java.util.logging.Level.FINE;
import static java.util.logging.Level.FINEST;
import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING;
/**
* Connection Pool for Connector & JDBC resources<br>
*
* @author Jagadish Ramu
*/
public class ConnectionPool implements ResourcePool, ConnectionLeakListener, ResourceHandler, PoolProperties {
private static final Logger LOG = LogDomains.getLogger(ConnectionPool.class, LogDomains.RSR_LOGGER);
// pool life-cycle config properties
protected int maxPoolSize;
protected int steadyPoolSize;
/** used by resizer to downsize the pool */
protected int resizeQuantity;
/** The total time a thread is willing to wait for a resource object. */
protected int maxWaitTime;
/** time (in ms) before destroying a free resource */
protected long idletime;
// pool config properties
protected boolean failAllConnections;
protected boolean matchConnections;
protected boolean validation;
protected boolean preferValidateOverRecreate;
// hold on to the resizer task so we can cancel/reschedule it.
protected Resizer resizerTask;
protected volatile boolean poolInitialized;
protected Timer timer;
// advanced pool config properties
protected boolean connectionCreationRetry_;
protected int connectionCreationRetryAttempts_;
protected long conCreationRetryInterval_;
protected long validateAtmostPeriodInMilliSeconds_;
protected int maxConnectionUsage_;
// To validate a Sun RA Pool Connection if it hasnot been validated
// in the past x sec. (x=idle-timeout)
// The property will be set from system property -
// com.sun.enterprise.connectors.ValidateAtmostEveryIdleSecs=true
private boolean validateAtmostEveryIdleSecs;
protected String resourceSelectionStrategyClass;
protected PoolLifeCycleListener poolLifeCycleListener;
// Gateway used to control the concurrency within the round-trip of resource access.
protected ResourceGateway gateway;
protected String resourceGatewayClass;
protected ConnectionLeakDetector leakDetector;
protected DataStructure dataStructure;
protected String dataStructureType;
protected String dataStructureParameters;
protected PoolWaitQueue waitQueue;
protected PoolWaitQueue reconfigWaitQueue;
private long reconfigWaitTime;
protected String poolWaitQueueClass;
protected final PoolInfo poolInfo; // poolName
private final PoolTxHelper poolTxHelper;
// NOTE: This resource allocator may not be the same as the allocator passed in to getResource()
protected ResourceAllocator allocator;
private boolean selfManaged_;
private boolean blocked;
public ConnectionPool(PoolInfo poolInfo, Hashtable env) throws PoolingException {
this.poolInfo = poolInfo;
setPoolConfiguration(env);
initializePoolDataStructure();
initializeResourceSelectionStrategy();
initializePoolWaitQueue();
poolTxHelper = new PoolTxHelper(this.poolInfo);
gateway = ResourceGateway.getInstance(resourceGatewayClass);
LOG.log(FINE, "Connection Pool: {0}", this.poolInfo);
}
protected void initializePoolWaitQueue() throws PoolingException {
waitQueue = PoolWaitQueueFactory.createPoolWaitQueue(poolWaitQueueClass);
reconfigWaitQueue = PoolWaitQueueFactory.createPoolWaitQueue(poolWaitQueueClass);
}
protected void initializePoolDataStructure() throws PoolingException {
dataStructure =
DataStructureFactory.getDataStructure(
dataStructureType,
dataStructureParameters, maxPoolSize, this,
resourceSelectionStrategyClass);
}
protected void initializeResourceSelectionStrategy() {
// do nothing
}
private void setPoolConfiguration(Hashtable env) throws PoolingException {
ConnectorConnectionPool poolResource = getPoolConfigurationFromJndi(env);
idletime = Integer.parseInt(poolResource.getIdleTimeoutInSeconds()) * 1000L;
maxPoolSize = Integer.parseInt(poolResource.getMaxPoolSize());
steadyPoolSize = Integer.parseInt(poolResource.getSteadyPoolSize());
if (maxPoolSize < steadyPoolSize) {
maxPoolSize = steadyPoolSize;
}
resizeQuantity = Integer.parseInt(poolResource.getPoolResizeQuantity());
maxWaitTime = Integer.parseInt(poolResource.getMaxWaitTimeInMillis());
// Make sure it's not negative.
if (maxWaitTime < 0) {
maxWaitTime = 0;
}
failAllConnections = poolResource.isFailAllConnections();
validation = poolResource.isIsConnectionValidationRequired();
validateAtmostEveryIdleSecs = poolResource.isValidateAtmostEveryIdleSecs();
dataStructureType = poolResource.getPoolDataStructureType();
dataStructureParameters = poolResource.getDataStructureParameters();
poolWaitQueueClass = poolResource.getPoolWaitQueue();
resourceSelectionStrategyClass = poolResource.getResourceSelectionStrategyClass();
resourceGatewayClass = poolResource.getResourceGatewayClass();
reconfigWaitTime = poolResource.getDynamicReconfigWaitTimeout();
setAdvancedPoolConfiguration(poolResource);
}
protected ConnectorConnectionPool getPoolConfigurationFromJndi(Hashtable env) throws PoolingException {
try {
return (ConnectorConnectionPool)
ConnectorRuntime.getRuntime()
.getResourceNamingService()
.lookup(
poolInfo,
getReservePrefixedJNDINameForPool(poolInfo),
env);
} catch (NamingException ex) {
throw new PoolingException(ex);
}
}
// This method does not need to be synchronized since all caller methods are,
// but it does not hurt. Just to be safe.
protected synchronized void initPool(ResourceAllocator allocator) throws PoolingException {
if (poolInitialized) {
return;
}
this.allocator = allocator;
createResources(this.allocator, steadyPoolSize - dataStructure.getResourcesSize());
// if the idle time out is 0, then don't schedule the resizer task
if (idletime > 0) {
scheduleResizerTask();
}
// Need to set the numConnFree of monitoring statistics to the steadyPoolSize
// as monitoring might be ON during the initialization of pool.
// Need not worry about the numConnUsed here as it would be initialized to
// 0 automatically.
if (poolLifeCycleListener != null) {
poolLifeCycleListener.connectionsFreed(steadyPoolSize);
}
poolInitialized = true;
}
/**
* Schedules the resizer timer task. If a task is currently scheduled, it would be canceled and a new one is scheduled.
*/
private void scheduleResizerTask() {
if (resizerTask != null) {
// cancel the current task
resizerTask.cancel();
resizerTask = null;
}
resizerTask = initializeResizer();
if (timer == null) {
timer = ConnectorRuntime.getRuntime().getTimer();
}
timer.scheduleAtFixedRate(resizerTask, idletime, idletime);
LOG.log(FINE, "Scheduled resizer task with the idle time {0} ms", idletime);
}
protected Resizer initializeResizer() {
return new Resizer(poolInfo, dataStructure, this, this, preferValidateOverRecreate);
}
/**
* add a resource with status busy and not enlisted
*
* @param alloc ResourceAllocator
* @throws PoolingException when unable to add a resource
*/
public void addResource(ResourceAllocator alloc) throws PoolingException {
int numResCreated = dataStructure.addResource(alloc, 1);
if (numResCreated > 0) {
for (int i = 0; i < numResCreated; i++) {
if (poolLifeCycleListener != null) {
poolLifeCycleListener.incrementNumConnFree(false, steadyPoolSize);
}
}
}
LOG.log(FINE, "Pool: resource added");
}
/**
* marks resource as free. This method should be used instead of directly calling
* resoureHandle.getResourceState().setBusy(false) OR getResourceState(resourceHandle).setBusy(false) as this method
* handles stopping of connection leak tracing If connection leak tracing is enabled, takes care of stopping connection
* leak tracing
*
* @param resourceHandle Resource
*/
protected void setResourceStateToFree(ResourceHandle resourceHandle) {
getResourceState(resourceHandle).setBusy(false);
leakDetector.stopConnectionLeakTracing(resourceHandle, this);
}
/**
* marks resource as busy. This method should be used instead of directly calling
* resoureHandle.getResourceState().setBusy(true) OR getResourceState(resourceHandle).setBusy(true) as this method
* handles starting of connection leak tracing If connection leak tracing is enabled, takes care of starting connection
* leak tracing
*
* @param resourceHandle Resource
*/
protected void setResourceStateToBusy(ResourceHandle resourceHandle) {
getResourceState(resourceHandle).setBusy(true);
leakDetector.startConnectionLeakTracing(resourceHandle, this);
}
/**
* returns resource from the pool.
*
* @return a free pooled resource object matching the ResourceSpec
* @throws PoolingException - if any error occurrs - or the pool has reached its max size and the
* max-connection-wait-time-in-millis has expired.
*/
@Override
public ResourceHandle getResource(ResourceSpec spec, ResourceAllocator alloc, Transaction transaction) throws PoolingException, RetryableUnavailableException {
// Note: this method should not be synchronized or the
// startTime would be incorrect for threads waiting to enter
/*
* Here are all the comments for the method put together for easy reference. 1. // - Try to get a free resource. Note:
* internalGetResource() // will create a new resource if none is free and the max has // not been reached. // - If
* can't get one, get on the wait queue. // - Repeat this until maxWaitTime expires. // - If maxWaitTime == 0, repeat
* indefinitely.
*
* 2. //the doFailAllConnectionsProcessing method would already //have been invoked by now. //We simply go ahead and
* create a new resource here //from the allocator that we have and adjust the resources //list accordingly so as to not
* exceed the maxPoolSize ever //(i.e if steadyPoolSize == maxPoolSize ) ///Also since we are creating the resource out
* of the allocator //that we came into this method with, we need not worry about //matching
*/
ResourceHandle result = null;
long startTime = System.currentTimeMillis();
long elapsedWaitTime;
long remainingWaitTime = 0;
while (true) {
if (gateway.allowed()) {
// See comment #1 above
JavaEETransaction javaEETransaction = ((JavaEETransaction) transaction);
final Set resourcesSet = javaEETransaction == null ? null : javaEETransaction.getResources(poolInfo);
// Allow when the pool is not blocked or at-least one resource is
// already obtained in the current transaction.
if (!blocked || (resourcesSet != null && !resourcesSet.isEmpty())) {
try {
result = internalGetResource(spec, alloc, transaction);
} finally {
gateway.acquiredResource();
}
}
}
if (result != null) {
// got one, return it
if (poolLifeCycleListener != null) {
poolLifeCycleListener.connectionAcquired(result.getId());
elapsedWaitTime = System.currentTimeMillis() - startTime;
poolLifeCycleListener.connectionRequestServed(elapsedWaitTime);
if (LOG.isLoggable(FINE)) {
LOG.log(FINE,
"Resource Pool: elapsed time (ms) to get connection for [" + spec + "] : " + elapsedWaitTime);
}
}
// got one - seems we are not doing validation or matching
// return it
break;
}
// did not get a resource.
if (maxWaitTime > 0) {
elapsedWaitTime = System.currentTimeMillis() - startTime;
if (elapsedWaitTime < maxWaitTime) {
// time has not expired, determine remaining wait time.
remainingWaitTime = maxWaitTime - elapsedWaitTime;
} else if (!blocked) {
// wait time has expired
if (poolLifeCycleListener != null) {
poolLifeCycleListener.connectionTimedOut();
}
throw new PoolingException("No available resources and wait time " + maxWaitTime + " ms expired.");
}
}
if (!blocked) {
// add to wait-queue
Object waitMonitor = new Object();
if (poolLifeCycleListener != null) {
poolLifeCycleListener.connectionRequestQueued();
}
synchronized (waitMonitor) {
waitQueue.addToQueue(waitMonitor);
try {
LOG.log(FINE, "Resource Pool: getting on wait queue");
waitMonitor.wait(remainingWaitTime);
} catch (InterruptedException ex) {
// Could be system shutdown.
break;
}
// Try to remove in case that the monitor has timed out. We don't expect the queue to grow to great numbers
// so the overhead for removing inexistant objects is low.
LOG.log(FINE, "removing wait monitor from queue: {0}", waitMonitor);
if (waitQueue.removeFromQueue(waitMonitor)) {
if (poolLifeCycleListener != null) {
poolLifeCycleListener.connectionRequestDequeued();
}
}
}
} else {
// Add to reconfig-wait-queue
Object reconfigWaitMonitor = new Object();
synchronized (reconfigWaitMonitor) {
reconfigWaitQueue.addToQueue(reconfigWaitMonitor);
try {
if (reconfigWaitTime > 0) {
LOG.log(FINEST, "[DRC] getting into reconfig wait queue for time [{0}]", reconfigWaitTime);
reconfigWaitMonitor.wait(reconfigWaitTime);
}
} catch (InterruptedException ex) {
// Could be system shutdown.
break;
}
// Try to remove in case that the monitor has timed
// out. We don't expect the queue to grow to great numbers
// so the overhead for removing inexistent objects is low.
LOG.log(FINEST, "[DRC] removing wait monitor from reconfig-wait-queue: {0}", reconfigWaitMonitor);
reconfigWaitQueue.removeFromQueue(reconfigWaitMonitor);
LOG.log(FINEST, "[DRC] throwing Retryable-Unavailable-Exception");
RetryableUnavailableException rue = new RetryableUnavailableException(
"Pool Reconfigured, Connection Factory can retry the lookup");
rue.setErrorCode(POOL_RECONFIGURED_ERROR_CODE);
throw rue;
}
}
}
alloc.fillInResourceObjects(result);
return result;
}
/**
* Overridden in AssocWithThreadResourcePool to fetch the resource cached in the ThreadLocal In ConnectionPool this
* simply returns null.
*
* @param spec ResourceSpec
* @param alloc ResourceAllocator to create a resource
* @param tran Transaction
* @return ResourceHandle resource from ThreadLocal
*/
protected ResourceHandle prefetch(ResourceSpec spec, ResourceAllocator alloc, Transaction tran) {
return null;
}
protected ResourceHandle internalGetResource(ResourceSpec resourceSpec, ResourceAllocator resourceAllocator, Transaction transaction) throws PoolingException {
if (!poolInitialized) {
initPool(resourceAllocator);
}
ResourceHandle resourceHandle = getResourceFromTransaction(transaction, resourceAllocator, resourceSpec);
if (resourceHandle != null) {
return resourceHandle;
}
resourceHandle = prefetch(resourceSpec, resourceAllocator, transaction);
if (resourceHandle != null) {
return resourceHandle;
}
// We didnt get a connection that is already enlisted in the current transaction (if any).
resourceHandle = getUnenlistedResource(resourceSpec, resourceAllocator, transaction);
if (resourceHandle != null) {
if (maxConnectionUsage_ > 0) {
resourceHandle.incrementUsageCount();
}
if (poolLifeCycleListener != null) {
poolLifeCycleListener.connectionUsed(resourceHandle.getId());
// Decrement numConnFree
poolLifeCycleListener.decrementNumConnFree();
}
}
return resourceHandle;
}
/**
* Try to get a resource from current transaction if it is shareable<br>
*
* @param transaction Current Transaction
* @param resourceAllocator ResourceAllocator
* @param resourceSpec ResourceSpec
* @return result ResourceHandle
*/
private ResourceHandle getResourceFromTransaction(Transaction transaction, ResourceAllocator resourceAllocator, ResourceSpec resourceSpec) {
ResourceHandle resourceFromTransaction = null;
try {
// comment-1: sharing is possible only if caller is marked
// shareable, so abort right here if that's not the case
if (transaction != null && resourceAllocator.shareableWithinComponent()) {
// TODO should be handled by PoolTxHelper
JavaEETransaction javaEETransaction = (JavaEETransaction) transaction;
// case 1. look for free and enlisted in same tx
Set set = javaEETransaction.getResources(poolInfo);
if (set != null) {
Iterator iter = set.iterator();
while (iter.hasNext()) {
ResourceHandle resourceHandle = (ResourceHandle) iter.next();
if (resourceHandle.hasConnectionErrorOccurred()) {
iter.remove();
continue;
}
ResourceState state = resourceHandle.getResourceState();
/*
* One can share a resource only for the following conditions:
*
* 1. The caller resource is shareable (look at the outermost if marked comment-1
*
* 2. The resource enlisted inside the transaction is shareable
*
* 3. We are dealing with XA resources OR we are dealing with a non-XA resource that's not in use
* Note that sharing a non-xa resource that's in use involves associating physical connections.
*
* 4. The credentials of the resources match
*/
if (resourceHandle.getResourceAllocator().shareableWithinComponent()) {
if (resourceSpec.isXA() || poolTxHelper.isNonXAResourceAndFree(javaEETransaction, resourceHandle)) {
if (matchConnections) {
if (!resourceAllocator.matchConnection(resourceHandle)) {
if (poolLifeCycleListener != null) {
poolLifeCycleListener.connectionNotMatched();
}
continue;
}
if (resourceHandle.hasConnectionErrorOccurred()) {
if (failAllConnections) {
// if failAllConnections has happened, we flushed the
// pool, so we don't have to do iter.remove else we
// will get a ConncurrentModificationException
resourceFromTransaction = null;
break;
}
iter.remove();
continue;
}
if (poolLifeCycleListener != null) {
poolLifeCycleListener.connectionMatched();
}
}
if (state.isFree()) {
setResourceStateToBusy(resourceHandle);
}
resourceFromTransaction = resourceHandle;
break;
}
}
}
}
}
} catch (ClassCastException e) {
if (LOG.isLoggable(FINE)) {
LOG.log(FINE, "Pool: getResource : transaction is not JavaEETransaction but a "
+ transaction.getClass().getName(), e);
}
}
return resourceFromTransaction;
}
/**
* To provide an unenlisted, valid, matched resource from pool.
*
* @param resourceSpec ResourceSpec
* @param resourceAllocator ResourceAllocator
* @param transaction Transaction
* @return ResourceHandle resource from pool
* @throws PoolingException Exception while getting resource from pool
*/
protected ResourceHandle getUnenlistedResource(ResourceSpec resourceSpec, ResourceAllocator resourceAllocator, Transaction transaction) throws PoolingException {
return getResourceFromPool(resourceAllocator, resourceSpec);
}
/**
* Check whether the connection is valid
*
* @param resourceHandle Resource to be validated
* @param resourceAllocator Allocator to validate the resource
* @return boolean representing validation result
*/
protected boolean isConnectionValid(ResourceHandle resourceHandle, ResourceAllocator resourceAllocator) {
boolean connectionValid = true;
if (validation || validateAtmostEveryIdleSecs) {
long validationPeriod;
// validation period is idle timeout if validateAtmostEveryIdleSecs is set to true
// else it is validateAtmostPeriodInMilliSeconds_
if (validation) {
validationPeriod = validateAtmostPeriodInMilliSeconds_;
} else {
validationPeriod = idletime;
}
boolean validationRequired = true;
long currentTime = resourceHandle.getLastValidated();
if (validationPeriod > 0) {
currentTime = System.currentTimeMillis();
long timeSinceValidation = currentTime - resourceHandle.getLastValidated();
if (timeSinceValidation < validationPeriod) {
validationRequired = false;
}
}
if (validationRequired) {
if (!resourceAllocator.isConnectionValid(resourceHandle)) {
connectionValid = false;
incrementNumConnFailedValidation();
} else {
resourceHandle.setLastValidated(currentTime);
}
}
}
return connectionValid;
}
/**
* check whether the connection retrieved from the pool matches with the request.
*
* @param resource Resource to be matched
* @param alloc ResourceAllocator used to match the connection
* @return boolean representing the match status of the connection
*/
protected boolean matchConnection(ResourceHandle resource, ResourceAllocator alloc) {
boolean matched = true;
if (matchConnections) {
matched = alloc.matchConnection(resource);
if (poolLifeCycleListener != null) {
if (matched) {
poolLifeCycleListener.connectionMatched();
} else {
poolLifeCycleListener.connectionNotMatched();
}
}
}
return matched;
}
/**
* return resource in free list. If none is found, try to scale up the pool/purge pool and <br>
* return a new resource. returns null if the pool new resources cannot be created. <br>
*
* @param resourceAllocator ResourceAllocator
* @return ResourceHandle resource from pool
* @throws PoolingException if unable to create a new resource
*/
protected ResourceHandle getResourceFromPool(ResourceAllocator resourceAllocator, ResourceSpec resourceSpec) throws PoolingException {
// The order of serving a resource request
// 1. free and enlisted in the same transaction
// 2. free and unenlisted
// Do NOT give out a connection that is
// free and enlisted in a different transaction
ResourceHandle resourceFromPool = null;
ResourceHandle resourceHandle;
List<ResourceHandle> freeResources = new ArrayList<>();
try {
while ((resourceHandle = dataStructure.getResource()) != null) {
if (resourceHandle.hasConnectionErrorOccurred()) {
dataStructure.removeResource(resourceHandle);
continue;
}
if (matchConnection(resourceHandle, resourceAllocator)) {
boolean isValid = isConnectionValid(resourceHandle, resourceAllocator);
if (resourceHandle.hasConnectionErrorOccurred() || !isValid) {
if (failAllConnections) {
resourceFromPool = createSingleResourceAndAdjustPool(resourceAllocator, resourceSpec);
// No need to match since the resource is created with the allocator of caller.
break;
}
dataStructure.removeResource(resourceHandle);
// Resource is invalid, continue iteration.
continue;
}
if (resourceHandle.isShareable() == resourceAllocator.shareableWithinComponent()) {
// Got a matched, valid resource
resourceFromPool = resourceHandle;
break;
}
freeResources.add(resourceHandle);
} else {
freeResources.add(resourceHandle);
}
}
} finally {
// Return all unmatched, free resources
for (ResourceHandle freeResource : freeResources) {
dataStructure.returnResource(freeResource);
}
freeResources.clear();
}
if (resourceFromPool != null) {
// Set correct state
setResourceStateToBusy(resourceFromPool);
} else {
resourceFromPool = resizePoolAndGetNewResource(resourceAllocator);
}
return resourceFromPool;
}
/**
* Scale-up the pool to serve the new request. <br>
* If pool is at max-pool-size and free resources are found, purge unmatched<br>
* resources, create new connections and serve the request.<br>
*
* @param resourceAllocator ResourceAllocator used to create new resources
* @return ResourceHandle newly created resource
* @throws PoolingException when not able to create resources
*/
private ResourceHandle resizePoolAndGetNewResource(ResourceAllocator resourceAllocator) throws PoolingException {
// Must be called from the thread holding the lock to this pool.
ResourceHandle newResource = null;
int numOfConnsToCreate = 0;
if (dataStructure.getResourcesSize() < steadyPoolSize) {
// May be all invalid resources are destroyed as
// a result no free resource found and no. of resources is less than steady-pool-size
numOfConnsToCreate = steadyPoolSize - dataStructure.getResourcesSize();
} else if (dataStructure.getResourcesSize() + resizeQuantity <= maxPoolSize) {
// Create and add resources of quantity "resizeQuantity"
numOfConnsToCreate = resizeQuantity;
} else if (dataStructure.getResourcesSize() < maxPoolSize) {
// This else if "test condition" is not needed. Just to be safe.
// still few more connections (less than "resizeQuantity" and to reach the count of maxPoolSize)
// can be added
numOfConnsToCreate = maxPoolSize - dataStructure.getResourcesSize();
}
if (numOfConnsToCreate > 0) {
createResources(resourceAllocator, numOfConnsToCreate);
newResource = getMatchedResourceFromPool(resourceAllocator);
} else if (dataStructure.getFreeListSize() > 0) {
// pool cannot create more connections as it is at max-pool-size.
// If there are free resources at max-pool-size, then none of the free resources
// has matched this allocator's request (credential). Hence purge free resources
// of size <=resizeQuantity
if (purgeResources(resizeQuantity) > 0) {
newResource = resizePoolAndGetNewResource(resourceAllocator);
}
}
return newResource;
}
// TODO can't this be replaced by getResourceFromPool ?
private ResourceHandle getMatchedResourceFromPool(ResourceAllocator alloc) {
ResourceHandle matchedResourceFromPool = null;
List<ResourceHandle> activeResources = new ArrayList<>();
try {
ResourceHandle handle;
while ((handle = dataStructure.getResource()) != null) {
if (matchConnection(handle, alloc)) {
matchedResourceFromPool = handle;
setResourceStateToBusy(matchedResourceFromPool);
break;
}
activeResources.add(handle);
}
} finally {
// Return unmatched resources
for (ResourceHandle activeResource : activeResources) {
dataStructure.returnResource(activeResource);
}
activeResources.clear();
}
return matchedResourceFromPool;
}
/**
* Try to purge resources by size <= quantity <br>
*
* @param quantity maximum no. of resources to remove. <br>
* @return resourceCount No. of resources actually removed. <br>
*/
private int purgeResources(int quantity) {
// Must be called from the thread holding the lock to this pool.
int totalResourcesRemoved = 0;
int freeResourcesCount = dataStructure.getFreeListSize();
int resourcesCount = (freeResourcesCount >= quantity) ? quantity : freeResourcesCount;
LOG.log(FINE, "Purging resources of size: {0}", resourcesCount);
for (int i = resourcesCount - 1; i >= 0; i--) {
ResourceHandle resource = dataStructure.getResource();
if (resource != null) {
dataStructure.removeResource(resource);
totalResourcesRemoved += 1;
}
}
return totalResourcesRemoved;
}
/**
* This method will be called from the getUnenlistedResource method if we detect a failAllConnection flag. Here we
* simply create a new resource and replace a free resource in the pool by this resource and then give it out. This
* replacement is required since the steadypoolsize might equal maxpoolsize and in that case if we were not to remove a
* resource from the pool, our resource would be above maxPoolSize
*
* @param resourceAllocator ResourceAllocator to create resource
* @param resourceSpec ResourceSpec
* @return newly created resource
* @throws PoolingException when unable to create a resource
*/
protected ResourceHandle createSingleResourceAndAdjustPool(ResourceAllocator resourceAllocator, ResourceSpec resourceSpec) throws PoolingException {
ResourceHandle handle = dataStructure.getResource();
if (handle != null) {
dataStructure.removeResource(handle);
}
return getNewResource(resourceAllocator);
}
/**
* Method to be used to create resource, instead of calling ResourceAllocator.createConfigBean(). This method handles
* the connection creation retrial in case of failure
*
* @param resourceAllocator ResourceAllocator
* @return ResourceHandle newly created resource
* @throws PoolingException when unable create a resource
*/
protected ResourceHandle createSingleResource(ResourceAllocator resourceAllocator) throws PoolingException {
int count = 0;
long startTime = System.currentTimeMillis();
while (true) {
try {
count++;
ResourceHandle resourceHandle = resourceAllocator.createResource();
long now = System.currentTimeMillis();
LOG.log(FINE,
() -> "Time taken to create a single resource: " + resourceHandle.getResourceSpec().getResourceId()
+ " and adding to the pool: " + (now - startTime) + " ms.");
if (validation || validateAtmostEveryIdleSecs) {
resourceHandle.setLastValidated(now);
}
return resourceHandle;
} catch (Exception ex) {
if (!connectionCreationRetry_ || count > connectionCreationRetryAttempts_) {
throw new PoolingException("Connection creation failed for " + count + " times.", ex);
}
LOG.log(WARNING, "Connection creation failed for " + count + " times. It will be retried in "
+ conCreationRetryInterval_ + " ms.", ex);
try {
Thread.sleep(conCreationRetryInterval_);
} catch (InterruptedException ie) {
// ignore this exception
}
}
}
}
/**
* Create specified number of resources.
*
* @param alloc ResourceAllocator
* @param size number of resources to create.
* @throws PoolingException When unable to create a resource
*/
private void createResources(ResourceAllocator alloc, int size) throws PoolingException {
for (int i = 0; i < size; i++) {
createResourceAndAddToPool(alloc);
}
}
@Override
public void setPoolLifeCycleListener(PoolLifeCycleListener listener) {
this.poolLifeCycleListener = listener;
}
@Override
public void removePoolLifeCycleListener() {
poolLifeCycleListener = null;
}
@Override
public void deleteResource(ResourceHandle resourceHandle) {
try {
resourceHandle.getResourceAllocator().destroyResource(resourceHandle);
} catch (Exception ex) {
LOG.log(WARNING, "Unexpected exception while destroying resource from pool " + poolInfo.getName(), ex);
} finally {
// if connection leak tracing is running on connection being
// destroyed due to error, then stop it
if (resourceHandle.getResourceState().isBusy()) {
leakDetector.stopConnectionLeakTracing(resourceHandle, this);
}
if (poolLifeCycleListener != null) {
poolLifeCycleListener.connectionDestroyed(resourceHandle.getId());
if (resourceHandle.getResourceState().isBusy()) {
// Destroying a Connection due to error
poolLifeCycleListener.decrementConnectionUsed(resourceHandle.getId());
if (!resourceHandle.isMarkedForReclaim()) {
// If a connection is not reclaimed (in case of a reconfig)
// increment numConnFree
poolLifeCycleListener.incrementNumConnFree(true, steadyPoolSize);
}
} else {
// Destroying a free Connection
poolLifeCycleListener.decrementNumConnFree();
}
}
}
}
/**
* this method is called to indicate that the resource is not used by a bean/application anymore
*/
@Override
public void resourceClosed(ResourceHandle handle) throws IllegalStateException {
LOG.log(FINE, "Resource was closed, processing handle: {0}", handle);
ResourceState state = getResourceState(handle);
if (state == null) {
throw new IllegalStateException("State is null");
}
if (!state.isBusy()) {
// Do not throw an exception, the current transaction should not fail if the state is already 'free'.
LOG.log(WARNING, "resourceClosed - Expecting 'state.isBusy(): false', but was true for handle: {0}", handle);
}
// mark as not busy
setResourceStateToFree(handle);
state.touchTimestamp();
if (state.isUnenlisted() || (poolTxHelper.isNonXAResource(handle) && poolTxHelper.isLocalTransactionInProgress()
&& poolTxHelper.isLocalResourceEligibleForReuse(handle))) {
freeUnenlistedResource(handle);
}
if (poolLifeCycleListener != null && !handle.getDestroyByLeakTimeOut()) {
poolLifeCycleListener.connectionReleased(handle.getId());
}
LOG.log(FINE, "Resource was freed after it`s closure: {0}", handle);
}
/**
* If the resource is used for <i>maxConnectionUsage</i> times, destroy and create one
*
* @param handle Resource to be checked
*/
protected void performMaxConnectionUsageOperation(ResourceHandle handle) {
dataStructure.removeResource(handle);
LOG.log(INFO, "Destroying connection {0} since it has reached the maximum usage of: {1}",
new Object[] {handle.getId(), handle.getUsageCount()});
if (poolLifeCycleListener != null) {
poolLifeCycleListener.decrementConnectionUsed(handle.getId());
}
// compensate with a new resource only when the pool-size is less than steady-pool-size
if (dataStructure.getResourcesSize() < steadyPoolSize) {
try {
createResourceAndAddToPool(handle.getResourceAllocator());
} catch (Exception e) {
LOG.log(WARNING, "Unable to create a new resource.", e);
}
}
}
protected void freeUnenlistedResource(ResourceHandle h) {
freeResource(h);
}
protected void freeResource(ResourceHandle resourceHandle) {
if (cleanupResource(resourceHandle)) {
// Only when resource handle usage count is more than maxConnUsage
if (maxConnectionUsage_ > 0 && resourceHandle.getUsageCount() >= maxConnectionUsage_) {
performMaxConnectionUsageOperation(resourceHandle);