This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5k
/
DbConnectionPool.cs
1615 lines (1381 loc) · 65.5 KB
/
DbConnectionPool.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Transactions;
namespace System.Data.ProviderBase
{
sealed internal class DbConnectionPool
{
private enum State
{
Initializing,
Running,
ShuttingDown,
}
// This class is a way to stash our cloned Tx key for later disposal when it's no longer needed.
// We can't get at the key in the dictionary without enumerating entries, so we stash an extra
// copy as part of the value.
sealed private class TransactedConnectionList : List<DbConnectionInternal>
{
private Transaction _transaction;
internal TransactedConnectionList(int initialAllocation, Transaction tx) : base(initialAllocation)
{
_transaction = tx;
}
internal void Dispose()
{
if (null != _transaction)
{
_transaction.Dispose();
}
}
}
private sealed class PendingGetConnection
{
public PendingGetConnection(long dueTime, DbConnection owner, TaskCompletionSource<DbConnectionInternal> completion, DbConnectionOptions userOptions)
{
DueTime = dueTime;
Owner = owner;
Completion = completion;
}
public long DueTime { get; private set; }
public DbConnection Owner { get; private set; }
public TaskCompletionSource<DbConnectionInternal> Completion { get; private set; }
public DbConnectionOptions UserOptions { get; private set; }
}
sealed private class TransactedConnectionPool
{
Dictionary<Transaction, TransactedConnectionList> _transactedCxns;
DbConnectionPool _pool;
private static int _objectTypeCount; // Bid counter
internal readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
internal TransactedConnectionPool(DbConnectionPool pool)
{
Debug.Assert(null != pool, "null pool?");
_pool = pool;
_transactedCxns = new Dictionary<Transaction, TransactedConnectionList>();
}
internal int ObjectID
{
get
{
return _objectID;
}
}
internal DbConnectionPool Pool
{
get
{
return _pool;
}
}
internal DbConnectionInternal GetTransactedObject(Transaction transaction)
{
Debug.Assert(null != transaction, "null transaction?");
DbConnectionInternal transactedObject = null;
TransactedConnectionList connections;
bool txnFound = false;
lock (_transactedCxns)
{
txnFound = _transactedCxns.TryGetValue(transaction, out connections);
}
// NOTE: GetTransactedObject is only used when AutoEnlist = True and the ambient transaction
// (Sys.Txns.Txn.Current) is still valid/non-null. This, in turn, means that we don't need
// to worry about a pending asynchronous TransactionCompletedEvent to trigger processing in
// TransactionEnded below and potentially wipe out the connections list underneath us. It
// is similarly alright if a pending addition to the connections list in PutTransactedObject
// below is not completed prior to the lock on the connections object here...getting a new
// connection is probably better than unnecessarily locking
if (txnFound)
{
Debug.Assert(connections != null);
// synchronize multi-threaded access with PutTransactedObject (TransactionEnded should
// not be a concern, see comments above)
lock (connections)
{
int i = connections.Count - 1;
if (0 <= i)
{
transactedObject = connections[i];
connections.RemoveAt(i);
}
}
}
return transactedObject;
}
internal void PutTransactedObject(Transaction transaction, DbConnectionInternal transactedObject)
{
Debug.Assert(null != transaction, "null transaction?");
Debug.Assert(null != transactedObject, "null transactedObject?");
TransactedConnectionList connections;
bool txnFound = false;
// NOTE: because TransactionEnded is an asynchronous notification, there's no guarantee
// around the order in which PutTransactionObject and TransactionEnded are called.
lock (_transactedCxns)
{
// Check if a transacted pool has been created for this transaction
if (txnFound = _transactedCxns.TryGetValue(transaction, out connections))
{
Debug.Assert(connections != null);
// synchronize multi-threaded access with GetTransactedObject
lock (connections)
{
Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?");
connections.Add(transactedObject);
}
}
}
// CONSIDER: the following code is more complicated than it needs to be to avoid cloning the
// transaction and allocating memory within a lock. Is that complexity really necessary?
if (!txnFound)
{
// create the transacted pool, making sure to clone the associated transaction
// for use as a key in our internal dictionary of transactions and connections
Transaction transactionClone = null;
TransactedConnectionList newConnections = null;
try
{
transactionClone = transaction.Clone();
newConnections = new TransactedConnectionList(2, transactionClone); // start with only two connections in the list; most times we won't need that many.
lock (_transactedCxns)
{
// NOTE: in the interim between the locks on the transacted pool (this) during
// execution of this method, another thread (threadB) may have attempted to
// add a different connection to the transacted pool under the same
// transaction. As a result, threadB may have completed creating the
// transacted pool while threadA was processing the above instructions.
if (txnFound = _transactedCxns.TryGetValue(transaction, out connections))
{
Debug.Assert(connections != null);
// synchronize multi-threaded access with GetTransactedObject
lock (connections)
{
Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?");
connections.Add(transactedObject);
}
}
else
{
// add the connection/transacted object to the list
newConnections.Add(transactedObject);
_transactedCxns.Add(transactionClone, newConnections);
transactionClone = null; // we've used it -- don't throw it or the TransactedConnectionList that references it away.
}
}
}
finally
{
if (null != transactionClone)
{
if (newConnections != null)
{
// another thread created the transaction pool and thus the new
// TransactedConnectionList was not used, so dispose of it and
// the transaction clone that it incorporates.
newConnections.Dispose();
}
else
{
// memory allocation for newConnections failed...clean up unused transactionClone
transactionClone.Dispose();
}
}
}
}
}
internal void TransactionEnded(Transaction transaction, DbConnectionInternal transactedObject)
{
TransactedConnectionList connections;
int entry = -1;
// NOTE: because TransactionEnded is an asynchronous notification, there's no guarantee
// around the order in which PutTransactionObject and TransactionEnded are called. As
// such, it is possible that the transaction does not yet have a pool created.
// TODO: is this a plausible and/or likely scenario? Do we need to have a mechanism to ensure
// TODO: that the pending creation of a transacted pool for this transaction is aborted when
// TODO: PutTransactedObject finally gets some CPU time?
lock (_transactedCxns)
{
if (_transactedCxns.TryGetValue(transaction, out connections))
{
Debug.Assert(connections != null);
bool shouldDisposeConnections = false;
// Lock connections to avoid conflict with GetTransactionObject
lock (connections)
{
entry = connections.IndexOf(transactedObject);
if (entry >= 0)
{
connections.RemoveAt(entry);
}
// Once we've completed all the ended notifications, we can
// safely remove the list from the transacted pool.
if (0 >= connections.Count)
{
_transactedCxns.Remove(transaction);
// we really need to dispose our connection list; it may have
// native resources via the tx and GC may not happen soon enough.
shouldDisposeConnections = true;
}
}
if (shouldDisposeConnections)
{
connections.Dispose();
}
}
}
// If (and only if) we found the connection in the list of
// connections, we'll put it back...
if (0 <= entry)
{
Pool.PutObjectFromTransactedPool(transactedObject);
}
}
}
private sealed class PoolWaitHandles
{
private readonly Semaphore _poolSemaphore;
private readonly ManualResetEvent _errorEvent;
// Using a Mutex requires ThreadAffinity because SQL CLR can swap
// the underlying Win32 thread associated with a managed thread in preemptive mode.
// Using an AutoResetEvent does not have that complication.
private readonly Semaphore _creationSemaphore;
private readonly WaitHandle[] _handlesWithCreate;
private readonly WaitHandle[] _handlesWithoutCreate;
internal PoolWaitHandles()
{
_poolSemaphore = new Semaphore(0, MAX_Q_SIZE);
_errorEvent = new ManualResetEvent(false);
_creationSemaphore = new Semaphore(1, 1);
_handlesWithCreate = new WaitHandle[] { _poolSemaphore, _errorEvent, _creationSemaphore };
_handlesWithoutCreate = new WaitHandle[] { _poolSemaphore, _errorEvent };
}
internal Semaphore CreationSemaphore
{
get { return _creationSemaphore; }
}
internal ManualResetEvent ErrorEvent
{
get { return _errorEvent; }
}
internal Semaphore PoolSemaphore
{
get { return _poolSemaphore; }
}
internal WaitHandle[] GetHandles(bool withCreate)
{
return withCreate ? _handlesWithCreate : _handlesWithoutCreate;
}
}
private const int MAX_Q_SIZE = (int)0x00100000;
// The order of these is important; we want the WaitAny call to be signaled
// for a free object before a creation signal. Only the index first signaled
// object is returned from the WaitAny call.
private const int SEMAPHORE_HANDLE = (int)0x0;
private const int ERROR_HANDLE = (int)0x1;
private const int CREATION_HANDLE = (int)0x2;
private const int BOGUS_HANDLE = (int)0x3;
private const int ERROR_WAIT_DEFAULT = 5 * 1000; // 5 seconds
// we do want a testable, repeatable set of generated random numbers
private static readonly Random s_random = new Random(5101977); // Value obtained from Dave Driver
private readonly int _cleanupWait;
private readonly DbConnectionPoolIdentity _identity;
private readonly DbConnectionFactory _connectionFactory;
private readonly DbConnectionPoolGroup _connectionPoolGroup;
private readonly DbConnectionPoolGroupOptions _connectionPoolGroupOptions;
private DbConnectionPoolProviderInfo _connectionPoolProviderInfo;
private State _state;
private readonly ConcurrentStack<DbConnectionInternal> _stackOld = new ConcurrentStack<DbConnectionInternal>();
private readonly ConcurrentStack<DbConnectionInternal> _stackNew = new ConcurrentStack<DbConnectionInternal>();
private readonly ConcurrentQueue<PendingGetConnection> _pendingOpens = new ConcurrentQueue<PendingGetConnection>();
private int _pendingOpensWaiting = 0;
private readonly WaitCallback _poolCreateRequest;
private int _waitCount;
private readonly PoolWaitHandles _waitHandles;
private Exception _resError;
private volatile bool _errorOccurred;
private int _errorWait;
private Timer _errorTimer;
private Timer _cleanupTimer;
private readonly TransactedConnectionPool _transactedConnectionPool;
private readonly List<DbConnectionInternal> _objectList;
private int _totalObjects;
// only created by DbConnectionPoolGroup.GetConnectionPool
internal DbConnectionPool(
DbConnectionFactory connectionFactory,
DbConnectionPoolGroup connectionPoolGroup,
DbConnectionPoolIdentity identity,
DbConnectionPoolProviderInfo connectionPoolProviderInfo)
{
Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup");
if ((null != identity) && identity.IsRestricted)
{
throw ADP.InternalError(ADP.InternalErrorCode.AttemptingToPoolOnRestrictedToken);
}
_state = State.Initializing;
lock (s_random)
{ // Random.Next is not thread-safe
_cleanupWait = s_random.Next(12, 24) * 10 * 1000; // 2-4 minutes in 10 sec intervals
}
_connectionFactory = connectionFactory;
_connectionPoolGroup = connectionPoolGroup;
_connectionPoolGroupOptions = connectionPoolGroup.PoolGroupOptions;
_connectionPoolProviderInfo = connectionPoolProviderInfo;
_identity = identity;
_waitHandles = new PoolWaitHandles();
_errorWait = ERROR_WAIT_DEFAULT;
_errorTimer = null; // No error yet.
_objectList = new List<DbConnectionInternal>(MaxPoolSize);
if (ADP.IsPlatformNT5)
{
_transactedConnectionPool = new TransactedConnectionPool(this);
}
_poolCreateRequest = new WaitCallback(PoolCreateRequest); // used by CleanupCallback
_state = State.Running;
//_cleanupTimer & QueuePoolCreateRequest is delayed until DbConnectionPoolGroup calls
// StartBackgroundCallbacks after pool is actually in the collection
}
private int CreationTimeout
{
get { return PoolGroupOptions.CreationTimeout; }
}
internal int Count
{
get { return _totalObjects; }
}
internal DbConnectionFactory ConnectionFactory
{
get { return _connectionFactory; }
}
internal bool ErrorOccurred
{
get { return _errorOccurred; }
}
private bool HasTransactionAffinity
{
get { return PoolGroupOptions.HasTransactionAffinity; }
}
internal TimeSpan LoadBalanceTimeout
{
get { return PoolGroupOptions.LoadBalanceTimeout; }
}
private bool NeedToReplenish
{
get
{
if (State.Running != _state) // Don't allow connection create when not running.
return false;
int totalObjects = Count;
if (totalObjects >= MaxPoolSize)
return false;
if (totalObjects < MinPoolSize)
return true;
int freeObjects = (_stackNew.Count + _stackOld.Count);
int waitingRequests = _waitCount;
bool needToReplenish = (freeObjects < waitingRequests) || ((freeObjects == waitingRequests) && (totalObjects > 1));
return needToReplenish;
}
}
internal DbConnectionPoolIdentity Identity
{
get { return _identity; }
}
internal bool IsRunning
{
get { return State.Running == _state; }
}
private int MaxPoolSize
{
get { return PoolGroupOptions.MaxPoolSize; }
}
private int MinPoolSize
{
get { return PoolGroupOptions.MinPoolSize; }
}
internal DbConnectionPoolGroup PoolGroup
{
get { return _connectionPoolGroup; }
}
internal DbConnectionPoolGroupOptions PoolGroupOptions
{
get { return _connectionPoolGroupOptions; }
}
internal DbConnectionPoolProviderInfo ProviderInfo
{
get { return _connectionPoolProviderInfo; }
}
internal bool UseLoadBalancing
{
get { return PoolGroupOptions.UseLoadBalancing; }
}
private bool UsingIntegrateSecurity
{
get { return (null != _identity && DbConnectionPoolIdentity.NoIdentity != _identity); }
}
private void CleanupCallback(Object state)
{
// Called when the cleanup-timer ticks over.
// This is the automatic pruning method. Every period, we will
// perform a two-step process:
//
// First, for each free object above MinPoolSize, we will obtain a
// semaphore representing one object and destroy one from old stack.
// We will continue this until we either reach MinPoolSize, we are
// unable to obtain a free object, or we have exhausted all the
// objects on the old stack.
//
// Second we move all free objects on the new stack to the old stack.
// So, every period the objects on the old stack are destroyed and
// the objects on the new stack are pushed to the old stack. All
// objects that are currently out and in use are not on either stack.
//
// With this logic, objects are pruned from the pool if unused for
// at least one period but not more than two periods.
// Destroy free objects that put us above MinPoolSize from old stack.
while (Count > MinPoolSize)
{ // While above MinPoolSize...
if (_waitHandles.PoolSemaphore.WaitOne(0))
{
// We obtained a objects from the semaphore.
DbConnectionInternal obj;
if (_stackOld.TryPop(out obj))
{
Debug.Assert(obj != null, "null connection is not expected");
// If we obtained one from the old stack, destroy it.
// Transaction roots must survive even aging out (TxEnd event will clean them up).
bool shouldDestroy = true;
lock (obj)
{ // Lock to prevent race condition window between IsTransactionRoot and shouldDestroy assignment
if (obj.IsTransactionRoot)
{
shouldDestroy = false;
}
}
// !!!!!!!!!! WARNING !!!!!!!!!!!!!
// ONLY touch obj after lock release if shouldDestroy is false!!! Otherwise, it may be destroyed
// by transaction-end thread!
// Note that there is a minor race condition between this task and the transaction end event, if the latter runs
// between the lock above and the SetInStasis call below. The reslult is that the stasis counter may be
// incremented without a corresponding decrement (the transaction end task is normally expected
// to decrement, but will only do so if the stasis flag is set when it runs). I've minimized the size
// of the window, but we aren't totally eliminating it due to SetInStasis needing to do bid tracing, which
// we don't want to do under this lock, if possible. It should be possible to eliminate this race condition with
// more substantial re-architecture of the pool, but we don't have the time to do that work for the current release.
if (shouldDestroy)
{
DestroyObject(obj);
}
else
{
obj.SetInStasis();
}
}
else
{
// Else we exhausted the old stack (the object the
// semaphore represents is on the new stack), so break.
_waitHandles.PoolSemaphore.Release(1);
break;
}
}
else
{
break;
}
}
// Push to the old-stack. For each free object, move object from
// new stack to old stack.
if (_waitHandles.PoolSemaphore.WaitOne(0))
{
for (; ;)
{
DbConnectionInternal obj;
if (!_stackNew.TryPop(out obj))
break;
Debug.Assert(obj != null, "null connection is not expected");
Debug.Assert(!obj.IsEmancipated, "pooled object not in pool");
Debug.Assert(obj.CanBePooled, "pooled object is not poolable");
_stackOld.Push(obj);
}
_waitHandles.PoolSemaphore.Release(1);
}
// Queue up a request to bring us up to MinPoolSize
QueuePoolCreateRequest();
}
internal void Clear()
{
DbConnectionInternal obj;
// First, quickly doom everything.
lock (_objectList)
{
int count = _objectList.Count;
for (int i = 0; i < count; ++i)
{
obj = _objectList[i];
if (null != obj)
{
obj.DoNotPoolThisConnection();
}
}
}
// Second, dispose of all the free connections.
while (_stackNew.TryPop(out obj))
{
Debug.Assert(obj != null, "null connection is not expected");
DestroyObject(obj);
}
while (_stackOld.TryPop(out obj))
{
Debug.Assert(obj != null, "null connection is not expected");
DestroyObject(obj);
}
// Finally, reclaim everything that's emancipated (which, because
// it's been doomed, will cause it to be disposed of as well)
ReclaimEmancipatedObjects();
}
private Timer CreateCleanupTimer() =>
ADP.UnsafeCreateTimer(
new TimerCallback(CleanupCallback),
null,
_cleanupWait,
_cleanupWait);
private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
{
DbConnectionInternal newObj = null;
try
{
newObj = _connectionFactory.CreatePooledConnection(this, owningObject, _connectionPoolGroup.ConnectionOptions, _connectionPoolGroup.PoolKey, userOptions);
if (null == newObj)
{
throw ADP.InternalError(ADP.InternalErrorCode.CreateObjectReturnedNull); // CreateObject succeeded, but null object
}
if (!newObj.CanBePooled)
{
throw ADP.InternalError(ADP.InternalErrorCode.NewObjectCannotBePooled); // CreateObject succeeded, but non-poolable object
}
newObj.PrePush(null);
lock (_objectList)
{
if ((oldConnection != null) && (oldConnection.Pool == this))
{
_objectList.Remove(oldConnection);
}
_objectList.Add(newObj);
_totalObjects = _objectList.Count;
}
// If the old connection belonged to another pool, we need to remove it from that
if (oldConnection != null)
{
var oldConnectionPool = oldConnection.Pool;
if (oldConnectionPool != null && oldConnectionPool != this)
{
Debug.Assert(oldConnectionPool._state == State.ShuttingDown, "Old connections pool should be shutting down");
lock (oldConnectionPool._objectList)
{
oldConnectionPool._objectList.Remove(oldConnection);
oldConnectionPool._totalObjects = oldConnectionPool._objectList.Count;
}
}
}
// Reset the error wait:
_errorWait = ERROR_WAIT_DEFAULT;
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
newObj = null; // set to null, so we do not return bad new object
// Failed to create instance
_resError = e;
// Make sure the timer starts even if ThreadAbort occurs after setting the ErrorEvent.
// timer allocation has to be done out of CER block
Timer t = new Timer(new TimerCallback(this.ErrorCallback), null, Timeout.Infinite, Timeout.Infinite);
bool timerIsNotDisposed;
try { }
finally
{
_waitHandles.ErrorEvent.Set();
_errorOccurred = true;
// Enable the timer.
// Note that the timer is created to allow periodic invocation. If ThreadAbort occurs in the middle of ErrorCallback,
// the timer will restart. Otherwise, the timer callback (ErrorCallback) destroys the timer after resetting the error to avoid second callback.
_errorTimer = t;
timerIsNotDisposed = t.Change(_errorWait, _errorWait);
}
Debug.Assert(timerIsNotDisposed, "ErrorCallback timer has been disposed");
if (30000 < _errorWait)
{
_errorWait = 60000;
}
else
{
_errorWait *= 2;
}
throw;
}
return newObj;
}
private void DeactivateObject(DbConnectionInternal obj)
{
obj.DeactivateConnection();
bool returnToGeneralPool = false;
bool destroyObject = false;
bool rootTxn = false;
if (obj.IsConnectionDoomed)
{
// the object is not fit for reuse -- just dispose of it.
destroyObject = true;
}
else
{
// NOTE: constructor should ensure that current state cannot be State.Initializing, so it can only
// be State.Running or State.ShuttingDown
Debug.Assert(_state == State.Running || _state == State.ShuttingDown);
lock (obj)
{
// A connection with a delegated transaction cannot currently
// be returned to a different customer until the transaction
// actually completes, so we send it into Stasis -- the SysTx
// transaction object will ensure that it is owned (not lost),
// and it will be certain to put it back into the pool.
if (_state == State.ShuttingDown)
{
if (obj.IsTransactionRoot)
{
// SQLHotfix# 50003503 - connections that are affiliated with a
// root transaction and that also happen to be in a connection
// pool that is being shutdown need to be put in stasis so that
// the root transaction isn't effectively orphaned with no
// means to promote itself to a full delegated transaction or
// Commit or Rollback
obj.SetInStasis();
rootTxn = true;
}
else
{
// connection is being closed and the pool has been marked as shutting
// down, so destroy this object.
destroyObject = true;
}
}
else
{
if (obj.IsNonPoolableTransactionRoot)
{
obj.SetInStasis();
rootTxn = true;
}
else if (obj.CanBePooled)
{
// We must put this connection into the transacted pool
// while inside a lock to prevent a race condition with
// the transaction asynchronously completing on a second
// thread.
Transaction transaction = obj.EnlistedTransaction;
if (null != transaction)
{
// NOTE: we're not locking on _state, so it's possible that its
// value could change between the conditional check and here.
// Although perhaps not ideal, this is OK because the
// DelegatedTransactionEnded event will clean up the
// connection appropriately regardless of the pool state.
Debug.Assert(_transactedConnectionPool != null, "Transacted connection pool was not expected to be null.");
_transactedConnectionPool.PutTransactedObject(transaction, obj);
rootTxn = true;
}
else
{
// return to general pool
returnToGeneralPool = true;
}
}
else
{
if (obj.IsTransactionRoot && !obj.IsConnectionDoomed)
{
// SQLHotfix# 50003503 - if the object cannot be pooled but is a transaction
// root, then we must have hit one of two race conditions:
// 1) PruneConnectionPoolGroups shutdown the pool and marked this connection
// as non-poolable while we were processing within this lock
// 2) The LoadBalancingTimeout expired on this connection and marked this
// connection as DoNotPool.
//
// This connection needs to be put in stasis so that the root transaction isn't
// effectively orphaned with no means to promote itself to a full delegated
// transaction or Commit or Rollback
obj.SetInStasis();
rootTxn = true;
}
else
{
// object is not fit for reuse -- just dispose of it
destroyObject = true;
}
}
}
}
}
if (returnToGeneralPool)
{
// Only push the connection into the general pool if we didn't
// already push it onto the transacted pool, put it into stasis,
// or want to destroy it.
Debug.Assert(destroyObject == false);
PutNewObject(obj);
}
else if (destroyObject)
{
DestroyObject(obj);
QueuePoolCreateRequest();
}
//-------------------------------------------------------------------------------------
// postcondition
// ensure that the connection was processed
Debug.Assert(rootTxn == true || returnToGeneralPool == true || destroyObject == true);
}
internal void DestroyObject(DbConnectionInternal obj)
{
// A connection with a delegated transaction cannot be disposed of
// until the delegated transaction has actually completed. Instead,
// we simply leave it alone; when the transaction completes, it will
// come back through PutObjectFromTransactedPool, which will call us
// again.
if (!obj.IsTxRootWaitingForTxEnd)
{
bool removed = false;
lock (_objectList)
{
removed = _objectList.Remove(obj);
Debug.Assert(removed, "attempt to DestroyObject not in list");
_totalObjects = _objectList.Count;
}
obj.Dispose();
}
}
private void ErrorCallback(Object state)
{
_errorOccurred = false;
_waitHandles.ErrorEvent.Reset();
// the error state is cleaned, destroy the timer to avoid periodic invocation
Timer t = _errorTimer;
_errorTimer = null;
if (t != null)
{
t.Dispose(); // Cancel timer request.
}
}
private Exception TryCloneCachedException()
// Cached exception can be of any type, so is not always cloneable.
// This functions clones SqlException
// OleDb and Odbc connections are not passing throw this code
{
if (_resError == null)
return null;
var sqlError = _resError as SqlClient.SqlException;
if (sqlError != null)
return sqlError.InternalClone();
return _resError;
}
private void WaitForPendingOpen()
{
PendingGetConnection next;
do
{
bool started = false;
try
{
try { }
finally
{
started = Interlocked.CompareExchange(ref _pendingOpensWaiting, 1, 0) == 0;
}
if (!started)
{
return;
}
while (_pendingOpens.TryDequeue(out next))
{
if (next.Completion.Task.IsCompleted)
{
continue;
}
uint delay;
if (next.DueTime == Timeout.Infinite)
{
delay = unchecked((uint)Timeout.Infinite);
}
else
{
delay = (uint)Math.Max(ADP.TimerRemainingMilliseconds(next.DueTime), 0);
}
DbConnectionInternal connection = null;
bool timeout = false;
Exception caughtException = null;
try
{
bool allowCreate = true;
bool onlyOneCheckConnection = false;
ADP.SetCurrentTransaction(next.Completion.Task.AsyncState as Transactions.Transaction);
timeout = !TryGetConnection(next.Owner, delay, allowCreate, onlyOneCheckConnection, next.UserOptions, out connection);
}
catch (Exception e)
{
caughtException = e;
}
if (caughtException != null)
{
next.Completion.TrySetException(caughtException);
}
else if (timeout)
{