-
Notifications
You must be signed in to change notification settings - Fork 335
Expand file tree
/
Copy pathDbConnectionInternal.cs
More file actions
1123 lines (961 loc) · 49.3 KB
/
Copy pathDbConnectionInternal.cs
File metadata and controls
1123 lines (961 loc) · 49.3 KB
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;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using Microsoft.Data.Common;
using Microsoft.Data.SqlClient;
using Microsoft.Data.SqlClient.ConnectionPool;
using Microsoft.Data.SqlClient.Diagnostics;
using Microsoft.Data.SqlClient.Internal;
#if NETFRAMEWORK
using System.Runtime.ConstrainedExecution;
using System.Security.Permissions;
#endif
namespace Microsoft.Data.ProviderBase
{
internal abstract class DbConnectionInternal
{
#region Fields
internal static readonly StateChangeEventArgs StateChangeClosed = new StateChangeEventArgs(
ConnectionState.Open,
ConnectionState.Closed);
internal static readonly StateChangeEventArgs StateChangeOpen = new StateChangeEventArgs(
ConnectionState.Closed,
ConnectionState.Open);
private static int _objectTypeCount;
private readonly int _objectId = Interlocked.Increment(ref _objectTypeCount);
/// <summary>
/// UTC time at which this internal connection was most recently handed to an owning
/// <see cref="DbConnection"/>. Cleared when it returns to the pool.
/// </summary>
private DateTime _checkoutTime;
/// <summary>
/// [usage must be thread safe] the owning object, when not in the pool. (both Pooled and Non-Pooled connections)
/// </summary>
private readonly WeakReference<DbConnection> _owningObject = new WeakReference<DbConnection>(null, false);
/// <summary>
/// True when the connection should no longer be pooled.
/// </summary>
private bool _cannotBePooled;
/// <summary>
/// [usage must be thread-safe] the transaction that we're enlisted in, either manually or automatically.
/// </summary>
private Transaction _enlistedTransaction;
/// <summary>
/// <see cref="_enlistedTransaction"/> is a clone, so that transaction information can be
/// queried even if the original transaction object is disposed. However, there are times
/// when we need to know if the original transaction object was disposed, so we keep a
/// reference to it here. This field should only be assigned a value at the same time
/// <see cref="_enlistedTransaction"/> is updated.
/// Also, this reference should not be disposed, since we aren't taking ownership of it.
/// </summary>
private Transaction _enlistedTransactionOriginal;
/// <summary>
/// usage must be thread safe] the number of times this object has been pushed into the
/// pool less the number of times it's been popped (0 != inPool)
/// </summary>
private int _pooledCount;
private TransactionCompletedEventHandler _transactionCompletedEventHandler = null;
#endregion
protected DbConnectionInternal() : this(ConnectionState.Open, true, false)
{
}
// Constructor for internal connections that report to a specific metrics sink, reusing
// the same defaults as the parameterless constructor above.
protected DbConnectionInternal(ISqlClientMetrics metrics) : this(ConnectionState.Open, true, false, metrics)
{
}
// Constructor for internal connections
internal DbConnectionInternal(ConnectionState state, bool hidePassword, bool allowSetConnectionString)
: this(state, hidePassword, allowSetConnectionString, metrics: null)
{
}
// Constructor for internal connections
internal DbConnectionInternal(ConnectionState state, bool hidePassword, bool allowSetConnectionString, ISqlClientMetrics metrics)
{
AllowSetConnectionString = allowSetConnectionString;
ShouldHidePassword = hidePassword;
State = state;
CreateTime = DateTime.UtcNow;
// Initialize the returned-to-pool stamp to creation time so that a freshly built connection is treated
// as "just used" by the pool's idle-expiry checks until the pool's return path stamps it again on first return.
// Without this initialization, ReturnedTime would default to DateTime.MinValue, which would cause
// IsLiveConnection to immediately evict every new connection whenever IdleTimeout is configured.
ReturnedTime = CreateTime;
Metrics = metrics ?? SqlClientDiagnostics.Metrics;
}
#region Properties
/// <summary>
/// When the connection was created.
/// </summary>
internal DateTime CreateTime { get; }
/// <summary>
/// UTC timestamp of when this connection was last returned to the pool.
/// Stamped by <see cref="SetReturnedTime()"/>. Initialized to <see cref="CreateTime"/> in the constructor
/// so a freshly built connection is treated as "just used" until its first return.
/// Internal setter exists to support deterministic unit tests without reflection.
/// The pool reads this value to decide whether the connection has sat idle longer than the configured idle timeout.
/// </summary>
internal DateTime ReturnedTime { get; set; }
/// <summary>
/// UTC timestamp of the current checkout, or <see cref="DateTime.MinValue"/> while the
/// connection is not owned by an application connection. The internal setter supports
/// deterministic timeout diagnostics tests.
/// </summary>
internal DateTime CheckoutTime
{
get => _checkoutTime;
set => _checkoutTime = value;
}
/// <summary>
/// The pool generation at the time this connection was created or added to the pool.
/// Used by <see cref="ChannelDbConnectionPool"/> to detect stale connections after a pool clear.
/// </summary>
/// <remarks>
/// Not safe, should only be set by the connection pool.
/// </remarks>
// TODO: Ideally this would be readonly and set in the constructor. Piping the value all the way through the connection factory is too complicated to be worth it.
// If we can expose the constructor to the connection pool in the future, it can be set in the constructor.
internal int ClearGeneration { get; set; }
internal bool AllowSetConnectionString { get; }
internal bool CanBePooled => !IsConnectionDoomed && !_cannotBePooled && !_owningObject.TryGetTarget(out _);
internal virtual bool IsAccessTokenExpired => false;
internal bool IsEmancipated
{
get
{
// NOTE: There are race conditions between PrePush, PostPop and this
// property getter -- only use this while this object is locked;
// (IDbConnectionPool.Clear and ReclaimEmancipatedObjects
// do this for us)
// The functionality is as follows:
//
// _pooledCount is incremented when the connection is pushed into the pool
// _pooledCount is decremented when the connection is popped from the pool
// _pooledCount is set to -1 when the connection is not pooled (just in case...)
//
// That means that:
//
// _pooledCount > 1 connection is in the pool multiple times (This should not happen)
// _pooledCount == 1 connection is in the pool
// _pooledCount == 0 connection is out of the pool
// _pooledCount == -1 connection is not a pooled connection; we shouldn't be here for non-pooled connections.
// _pooledCount < -1 connection out of the pool multiple times
//
// Now, our job is to return TRUE when the connection is out
// of the pool and it's owning object is no longer around to
// return it.
return !IsTxRootWaitingForTxEnd && (_pooledCount < 1) && !_owningObject.TryGetTarget(out _);
}
}
internal bool IsInPool
{
get
{
Debug.Assert(_pooledCount <= 1 && _pooledCount >= -1, "Pooled count for object is invalid");
return _pooledCount == 1;
}
}
/// <remarks>
/// If you want to have delegated transactions, you had better override this...
/// </remarks>
internal virtual bool IsTransactionRoot => false;
/// <summary>
/// Is this connection in stasis, waiting for transaction to end before returning to pool?
/// </summary>
internal bool IsTxRootWaitingForTxEnd { get; private set; }
internal int ObjectID => _objectId;
/// <summary>
/// The pooler that the connection came from (Pooled connections only)
/// </summary>
internal IDbConnectionPool Pool { get; private set; }
/// <summary>
/// The metrics sink this connection reports its activation state to. Supplied by the
/// <see cref="SqlConnectionFactory"/> that created this connection, from its own injected
/// instance, rather than derived from <see cref="Pool"/>: the metrics sink is not
/// inherently tied to a pool, and a connection is not necessarily pooled at all. Defaults
/// to the process-wide instance when no metrics sink is supplied to the constructor (e.g.
/// a test double constructed directly), so it still reports somewhere.
/// </summary>
internal ISqlClientMetrics Metrics { get; }
public abstract string ServerVersion { get; }
public virtual ConnectionCapabilities Capabilities => null;
// this should be abstract but until it is added to all the providers virtual will have to do RickFe
public virtual string ServerVersionNormalized
{
get => throw ADP.NotSupported();
}
public bool ShouldHidePassword { get; }
public ConnectionState State { get; }
protected internal Transaction EnlistedTransaction
{
get
{
return _enlistedTransaction;
}
set
{
Transaction currentEnlistedTransaction = _enlistedTransaction;
if ((currentEnlistedTransaction == null && value != null) ||
(currentEnlistedTransaction != null && !currentEnlistedTransaction.Equals(value)))
{
// Pay attention to the order here:
// 1) defect from any notifications
// 2) replace the transaction
// 3) re-enlist in notifications for the new transaction
// SQLBUDT #230558 we need to use a clone of the transaction
// when we store it, or we'll end up keeping it past the
// duration of the using block of the TransactionScope
Transaction valueClone = null;
Transaction previousTransactionClone = null;
try
{
if (value != null)
{
valueClone = value.Clone();
}
// NOTE: rather than take locks around several potential round-
// trips to the server, and/or virtual function calls, we simply
// presume that you aren't doing something illegal from multiple
// threads, and check once we get around to finalizing things
// inside a lock.
lock (this)
{
// NOTE: There is still a race condition here, when we are
// called from EnlistTransaction (which cannot re-enlist)
// instead of EnlistDistributedTransaction (which can),
// however this should have been handled by the outer
// connection which checks to ensure that it's OK. The
// only case where we have the race condition is multiple
// concurrent enlist requests to the same connection, which
// is a bit out of line with something we should have to
// support.
// enlisted transaction can be nullified in Dispose call without lock
previousTransactionClone = Interlocked.Exchange(ref _enlistedTransaction, valueClone);
_enlistedTransactionOriginal = value;
value = valueClone;
valueClone = null; // we've stored it, don't dispose it.
}
}
finally
{
// we really need to dispose our clones; they may have
// native resources and GC may not happen soon enough.
// VSDevDiv 479564: don't dispose if still holding reference in _enlistedTransaction
if (previousTransactionClone != null && !ReferenceEquals(previousTransactionClone, _enlistedTransaction))
{
previousTransactionClone.Dispose();
}
if (valueClone != null && !ReferenceEquals(valueClone, _enlistedTransaction))
{
valueClone.Dispose();
}
}
// I don't believe that we need to lock to protect the actual
// enlistment in the transaction; it would only protect us
// against multiple concurrent calls to enlist, which really
// isn't supported anyway.
if (value != null)
{
SqlClientEventSource.Log.TryPoolerTraceEvent("<prov.DbConnectionInternal.set_EnlistedTransaction|RES|CPOOL> {0}, Transaction {1}, Enlisting.", ObjectID, value.GetHashCode());
TransactionOutcomeEnlist(value);
}
}
}
}
/// <summary>
/// Get boolean value that indicates whether the enlisted transaction has been disposed.
/// </summary>
/// <value>
/// <see langword="true"/> if there is an enlisted transaction, and it has been disposed.
/// <see langword="false"/> if there is an enlisted transaction that has not been disposed,
/// or if the transaction reference is null.
/// </value>
/// <remarks>
/// This method must be called while holding a lock on the DbConnectionInternal instance.
/// </remarks>
protected bool EnlistedTransactionDisposed
{
get
{
// Until the Transaction.Disposed property is public it is necessary to access a member
// that throws if the object is disposed to determine if in fact the transaction is disposed.
try
{
bool disposed;
Transaction currentEnlistedTransactionOriginal = _enlistedTransactionOriginal;
if (currentEnlistedTransactionOriginal != null)
{
disposed = currentEnlistedTransactionOriginal.TransactionInformation == null;
}
else
{
// Don't expect to get here in the general case,
// Since this getter is called by CheckEnlistedTransactionBinding
// after checking for a non-null enlisted transaction (and it does so under lock).
disposed = false;
}
return disposed;
}
catch (ObjectDisposedException)
{
return true;
}
}
}
/// <summary>
/// <see langword="true" /> when the connection should no longer be used.
/// </summary>
protected internal bool IsConnectionDoomed { get; private set; }
/// <remarks>
/// We use a weak reference to the owning object so we can identify when it has been
/// garbage collected without throwing exceptions.
/// </remarks>
protected internal DbConnection Owner
{
get => _owningObject.TryGetTarget(out DbConnection connection) ? connection : null;
}
protected virtual bool ReadyToPrepareTransaction
{
get => true;
}
/// <summary>
/// Collection of objects that we need to notify in some way when we're being deactivated
/// </summary>
protected internal DbReferenceCollection ReferenceCollection { get; private set; }
/// <summary>
/// Get boolean that specifies whether an enlisted transaction can be unbound from
/// the connection when that transaction completes.
/// </summary>
/// <value>
/// <see langword="true" /> if the enlisted transaction can be unbound on transaction
/// completion; otherwise <see langword="false" />.
/// </value>
protected virtual bool UnbindOnTransactionCompletion
{
get => true;
}
#endregion
#region Public/Internal Methods
internal void ActivateConnection(Transaction transaction)
{
// Internal method called from the connection pooler so we don't expose
// the Activate method publicly.
SqlClientEventSource.Log.TryPoolerTraceEvent("<prov.DbConnectionInternal.ActivateConnection|RES|INFO|CPOOL> {0}, Activating", ObjectID);
// Counted before Activate, mirroring DeactivateConnection, which counts before
// Deactivate. If Activate throws, the pool returns the connection and deactivates it,
// so counting afterwards would leave that exit unpaired and drive the
// active-connections gauge negative.
Metrics.EnterActiveConnection();
Activate(transaction);
}
internal void AddWeakReference(object value, int tag)
{
if (ReferenceCollection is null)
{
ReferenceCollection = CreateReferenceCollection();
if (ReferenceCollection is null)
{
throw ADP.InternalError(ADP.InternalErrorCode.CreateReferenceCollectionReturnedNull);
}
}
ReferenceCollection.Add(value, tag);
}
public abstract DbTransaction BeginTransaction(System.Data.IsolationLevel il);
public virtual void ChangeDatabase(string value)
{
throw ADP.MethodNotImplemented();
}
// Handle transaction detach, pool cleanup and other post-transaction cleanup tasks associated with
internal void CleanupConnectionOnTransactionCompletion(Transaction transaction)
{
DetachTransaction(transaction, false);
IDbConnectionPool pool = Pool;
pool?.TransactionEnded(transaction, this);
}
internal virtual void CloseConnection(DbConnection owningObject, SqlConnectionFactory connectionFactory)
{
// The implementation here is the implementation required for the
// "open" internal connections, since our own private "closed"
// singleton internal connection objects override this method to
// prevent anything funny from happening (like disposing themselves
// or putting them into a connection pool)
//
// Derived class should override DbConnectionInternal.Deactivate and DbConnectionInternal.Dispose
// for cleaning up after DbConnection.Close
// protected override void Deactivate() { // override DbConnectionInternal.Close
// // do derived class connection deactivation for both pooled & non-pooled connections
// }
// public override void Dispose() { // override DbConnectionInternal.Close
// // do derived class cleanup
// base.Dispose();
// }
//
// overriding DbConnection.Close is also possible, but must provider for their own synchronization
// public override void Close() { // override DbConnection.Close
// base.Close();
// // do derived class outer connection for both pooled & non-pooled connections
// // user must do their own synchronization here
// }
//
// if the DbConnectionInternal derived class needs to close the connection it should
// delegate to the DbConnection if one exists or directly call dispose
// DbConnection owningObject = (DbConnection)Owner;
// if (owningObject != null) {
// owningObject.Close(); // force the closed state on the outer object.
// }
// else {
// Dispose();
// }
//
////////////////////////////////////////////////////////////////
// DON'T MESS WITH THIS CODE UNLESS YOU KNOW WHAT YOU'RE DOING!
////////////////////////////////////////////////////////////////
Debug.Assert(owningObject is not null, "null owningObject");
Debug.Assert(connectionFactory is not null, "null connectionFactory");
SqlClientEventSource.Log.TryPoolerTraceEvent("<prov.DbConnectionInternal.CloseConnection|RES|CPOOL> {0} Closing.", ObjectID);
// if an exception occurs after the state change but before the try block
// the connection will be stuck in OpenBusy state. The commented out try-catch
// block doesn't really help because a ThreadAbort during the finally block
// would just revert the connection to a bad state.
// Open->Closed: guarantee internal connection is returned to correct pool
if (connectionFactory.SetInnerConnectionFrom(owningObject, DbConnectionOpenBusy.SingletonInstance, this))
{
// Lock to prevent race condition with cancellation
lock (this)
{
bool lockToken = ObtainAdditionalLocksForClose();
try
{
PrepareForCloseConnection();
IDbConnectionPool connectionPool = Pool;
// Detach from enlisted transactions that are no longer active on close
DetachCurrentTransactionIfEnded();
// The singleton closed classes won't have owners and
// connection pools, and we won't want to put them back
// into the pool.
if (connectionPool is not null)
{
// ReturnInternalConnection calls Deactivate for us...
connectionPool.ReturnInternalConnection(this, owningObject);
// NOTE: Before we leave the ReturnInternalConnection call, another thread may have
// already popped the connection from the pool, so don't expect to be
// able to verify it.
}
else
{
// Ensure we de-activate non-pooled connections, or the data readers
// and transactions may not get cleaned up...
Deactivate();
Metrics.HardDisconnectRequest();
// To prevent an endless recursion, we need to clear the owning object
// before we call dispose so that we can't get here a second time...
// Ordinarily, I would call setting the owner to null a hack, but this
// is safe since we're about to dispose the object, and it won't have
// an owner after that for certain.
_owningObject.SetTarget(null);
if (IsTransactionRoot)
{
SetInStasis();
}
else
{
Metrics.ExitNonPooledConnection();
Dispose();
}
}
}
finally
{
ReleaseAdditionalLocksForClose(lockToken);
// If a ThreadAbort puts us here then its possible the outer connection
// will not reference this and this will be orphaned, not reclaimed by
// object pool until outer connection goes out of scope.
connectionFactory.SetInnerConnectionEvent(
owningObject,
DbConnectionClosedPreviouslyOpened.SingletonInstance);
}
}
}
}
internal void DeactivateConnection()
{
// Internal method called from the connection pooler so we don't expose
// the Deactivate method publicly.
SqlClientEventSource.Log.TryPoolerTraceEvent("<prov.DbConnectionInternal.DeactivateConnection|RES|INFO|CPOOL> {0}, Deactivating", ObjectID);
Metrics.ExitActiveConnection();
if (!IsConnectionDoomed && Pool.UseLoadBalancing)
{
// If we're not already doomed, check the connection's lifetime and
// doom it if it's lifetime has elapsed.
DateTime now = DateTime.UtcNow;
if (now.Ticks - CreateTime.Ticks > Pool.LoadBalanceTimeout.Ticks)
{
DoNotPoolThisConnection();
}
}
Deactivate();
}
internal virtual void DelegatedTransactionEnded()
{
// Called by System.Transactions when the delegated transaction has completed. We need
// to make closed connections that are in stasis available again, or disposed
// closed/leaked non-pooled connections.
// IMPORTANT NOTE: You must have taken a lock on the object before
// you call this method to prevent race conditions with Clear and
// ReclaimEmancipatedObjects.
SqlClientEventSource.Log.TryPoolerTraceEvent("<prov.DbConnectionInternal.DelegatedTransactionEnded|RES|CPOOL> {0}, Delegated Transaction Completed.", ObjectID);
if (_pooledCount == 1)
{
// When _pooledCount is 1, it indicates a closed, pooled, connection so it is ready
// to put back into the pool for general use.
TerminateStasis(true);
Deactivate(); // call it one more time just in case
IDbConnectionPool pool = Pool;
if (pool == null)
{
// pooled connection does not have a pool
throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectWithoutPool);
}
pool.PutObjectFromTransactedPool(this);
}
else if (_pooledCount == -1 && !_owningObject.TryGetTarget(out _))
{
// When _pooledCount is -1 and the owning object no longer exists,
// it indicates a closed (or leaked), non-pooled connection so
// it is safe to dispose.
TerminateStasis(false);
// Call it one more time just in case
Deactivate();
// it's a non-pooled connection, we need to dispose of it
// once and for all, or the server will have fits about us
// leaving connections open until the client-side GC kicks
// in.
Metrics.ExitNonPooledConnection();
Dispose();
}
// When _pooledCount is 0, the connection is a pooled connection
// that is either open (if the owning object is alive) or leaked (if
// the owning object is not alive) In either case, we can't muck
// with the connection here.
}
internal void DetachCurrentTransactionIfEnded()
{
Transaction enlistedTransaction = EnlistedTransaction;
if (enlistedTransaction != null)
{
bool transactionIsDead;
try
{
transactionIsDead = enlistedTransaction.TransactionInformation.Status != TransactionStatus.Active;
}
catch (TransactionException)
{
// If the transaction is being processed (i.e. is partially through a rollback\
// commit\etc then TransactionInformation.Status will throw an exception)
transactionIsDead = true;
}
if (transactionIsDead)
{
DetachTransaction(enlistedTransaction, true);
}
}
}
// Detach transaction from connection.
internal void DetachTransaction(Transaction transaction, bool isExplicitlyReleasing)
{
SqlClientEventSource.Log.TryPoolerTraceEvent("<prov.DbConnectionInternal.DetachTransaction|RES|CPOOL> {0}, Transaction Completed. (pooledCount={1})", ObjectID, _pooledCount);
// Potentially a multithreaded event, so lock the connection to make sure we don't
// enlist in a new transaction between compare and assignment. No need to short
// circuit outside of lock, since failed comparisons should be the exception, not the
// rule.
// Locking on anything other than the transaction object would lead to a thread
// deadlock with System.Transaction.TransactionCompleted event.
lock (transaction)
{
// Detach if detach-on-end behavior, or if outer connection was closed
DbConnection owner = Owner;
if (isExplicitlyReleasing || UnbindOnTransactionCompletion || owner is null)
{
Transaction currentEnlistedTransaction = _enlistedTransaction;
if (currentEnlistedTransaction != null && transaction.Equals(currentEnlistedTransaction))
{
// We need to remove the transaction completed event handler to cease
// listening for the transaction to end.
currentEnlistedTransaction.TransactionCompleted -= _transactionCompletedEventHandler;
EnlistedTransaction = null;
if (IsTxRootWaitingForTxEnd)
{
DelegatedTransactionEnded();
}
}
}
}
}
public virtual void Dispose()
{
Pool = null;
IsConnectionDoomed = true;
_enlistedTransactionOriginal = null; // should not be disposed
// Dispose of the _enlistedTransaction since it is a clone of the original reference.
// VSDD 780271 - _enlistedTransaction can be changed by another thread (TX end event)
Transaction enlistedTransaction = Interlocked.Exchange(ref _enlistedTransaction, null);
if (enlistedTransaction != null)
{
enlistedTransaction.Dispose();
}
}
public abstract void EnlistTransaction(Transaction transaction);
/// <summary>
/// When overridden in a derived class, will check if the underlying connection is still
/// actually alive.
/// </summary>
/// <param name="throwOnException">
/// If true an exception will be thrown if the connection is dead instead of returning
/// true\false (this allows the caller to have the real reason that the connection is not
/// alive (e.g. network error, etc.)).
/// </param>
/// <returns>
/// <see langword="true" /> if the connection is still alive, otherwise <see langword="false"/>.
/// (If not overridden, then always true)
/// </returns>
internal virtual bool IsConnectionAlive(bool throwOnException = false) => true;
/// <summary>
/// Used by DbConnectionFactory to indicate that this object IS NOT part of a connection pool.
/// </summary>
internal void MakeNonPooledObject(DbConnection owningObject)
{
Pool = null;
_owningObject.SetTarget(owningObject);
_pooledCount = -1;
}
/// <summary>
/// Used by DbConnectionFactory to indicate that this object IS part of a connection pool.
/// </summary>
/// <param name="connectionPool"></param>
internal void MakePooledConnection(IDbConnectionPool connectionPool)
{
Pool = connectionPool;
}
internal void PostPop(DbConnection newOwner, DateTime checkoutTime)
{
Debug.Assert(checkoutTime.Kind == DateTimeKind.Utc);
// Called by IDbConnectionPool right after it pulls this from its pool, we take this
// opportunity to ensure ownership and pool counts are legit.
Debug.Assert(!IsEmancipated, "pooled object not in pool");
// IMPORTANT NOTE: You must have taken a lock on the object before you call this method
// to prevent race conditions with Clear and ReclaimEmancipatedObjects.
if (_owningObject.TryGetTarget(out _))
{
// Pooled connection already has an owner!
throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectHasOwner);
}
_owningObject.SetTarget(newOwner);
_pooledCount--;
_checkoutTime = checkoutTime;
SqlClientEventSource.Log.TryPoolerTraceEvent("<prov.DbConnectionInternal.PostPop|RES|CPOOL> {0}, Preparing to pop from pool, owning connection {1}, pooledCount={2}", ObjectID, 0, _pooledCount);
//3 // The following tests are retail assertions of things we can't allow to happen.
if (Pool is not null)
{
if (_pooledCount != 0)
{
// Popping object off stack with multiple pooledCount
throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectInPoolMoreThanOnce);
}
}
else if (_pooledCount != -1)
{
// Popping object off stack with multiple pooledCount
throw ADP.InternalError(ADP.InternalErrorCode.NonPooledObjectUsedMoreThanOnce);
}
}
/// <summary>
/// Stamps <see cref="ReturnedTime"/> with the current UTC time. The pool calls this from its
/// return-to-pool path only when it intends the idle-timeout machinery to act on the value;
/// the connection owns the mechanism (recording the time) while the pool owns the policy
/// (deciding when a stamp is meaningful).
/// </summary>
internal void SetReturnedTime()
{
SetReturnedTime(DateTime.UtcNow);
}
/// <summary>
/// Stamps <see cref="ReturnedTime"/> with the supplied UTC time. Lets the pool source the
/// timestamp from its configured <see cref="System.TimeProvider"/> so the return stamp and the
/// idle-timeout expiry check read the same clock, which tests use to drive idle expiry
/// deterministically. Callers must pass a UTC value.
/// </summary>
internal void SetReturnedTime(DateTime utcNow)
{
ReturnedTime = utcNow;
}
internal void PrePush(DbConnection expectedOwner)
{
// Called by IDbConnectionPool when we're about to be put into it's pool, we take this
// opportunity to ensure ownership and pool counts are legit.
// IMPORTANT NOTE: You must have taken a lock on the object before you call this method
// to prevent race conditions with Clear and ReclaimEmancipatedObjects.
// The following tests are retail assertions of things we can't allow to happen.
bool isAlive = _owningObject.TryGetTarget(out DbConnection connection);
if (expectedOwner is null)
{
if (isAlive)
{
// New unpooled object has an owner
throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasOwner);
}
}
else if (isAlive && connection != expectedOwner)
{
// Unpooled object has incorrect owner
throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasWrongOwner);
}
if (_pooledCount != 0)
{
// Pushing object onto stack a second time
throw ADP.InternalError(ADP.InternalErrorCode.PushingObjectSecondTime);
}
SqlClientEventSource.Log.TryPoolerTraceEvent("<prov.DbConnectionInternal.PrePush|RES|CPOOL> {0}, Preparing to push into pool, owning connection {1}, pooledCount={2}", ObjectID, 0, _pooledCount);
_pooledCount++;
_checkoutTime = DateTime.MinValue;
// NOTE: doing this and checking for InternalError.PooledObjectHasOwner degrades the
// close by 2%
_owningObject.SetTarget(null);
}
/// <summary>
/// Classifies the connection for a timeout-only pool diagnostics snapshot.
/// The caller must hold this connection's monitor.
/// </summary>
/// <param name="utcNow">Current UTC time used to calculate checkout duration.</param>
/// <param name="checkoutDuration">How long the current or abandoned checkout has lasted.</param>
/// <returns>The connection's current pool usage state.</returns>
internal PoolConnectionUsageState GetPoolUsageState(
DateTime utcNow,
out TimeSpan checkoutDuration)
{
Debug.Assert(Monitor.IsEntered(this));
Debug.Assert(utcNow.Kind == DateTimeKind.Utc);
checkoutDuration = TimeSpan.Zero;
if (IsTxRootWaitingForTxEnd ||
(IsInPool && EnlistedTransaction is not null))
{
return PoolConnectionUsageState.TransactionHeld;
}
if (IsInPool)
{
return PoolConnectionUsageState.Idle;
}
if (_owningObject.TryGetTarget(out _))
{
checkoutDuration = GetCheckoutDuration(utcNow);
return PoolConnectionUsageState.CheckedOut;
}
if (_checkoutTime != DateTime.MinValue && IsEmancipated)
{
checkoutDuration = GetCheckoutDuration(utcNow);
return PoolConnectionUsageState.Abandoned;
}
return PoolConnectionUsageState.Unclassified;
}
private TimeSpan GetCheckoutDuration(DateTime utcNow) =>
utcNow > _checkoutTime
? utcNow - _checkoutTime
: TimeSpan.Zero;
internal void RemoveWeakReference(object value) =>
ReferenceCollection?.Remove(value);
/// <summary>
/// Idempotently resets the connection so that it may be recycled without leaking state.
/// May preserve transaction state if the connection is enlisted in a distributed transaction.
/// Should be called before the first action is taken on a recycled connection.
/// </summary>
internal abstract void ResetConnection();
internal void SetInStasis()
{
IsTxRootWaitingForTxEnd = true;
SqlClientEventSource.Log.TryPoolerTraceEvent("<prov.DbConnectionInternal.SetInStasis|RES|CPOOL> {0}, Non-Pooled Connection has Delegated Transaction, waiting to Dispose.", ObjectID);
Metrics.EnterStasisConnection();
}
/// <remarks>
/// The default implementation is for the open connection objects, and it simply throws.
/// Our private closed-state connection objects override this and do the correct thing.
/// User code should either override DbConnectionInternal.Activate when it comes out of the
/// pool or override DbConnectionFactory.CreateConnection when the connection is created
/// for non-pooled connections.
/// </remarks>
internal virtual bool TryOpenConnection(
DbConnection outerConnection,
SqlConnectionFactory connectionFactory,
TaskCompletionSource<DbConnectionInternal> retry,
TimeoutTimer timeout)
{
throw ADP.ConnectionAlreadyOpen(State);
}
internal virtual bool TryReplaceConnection(
DbConnection outerConnection,
SqlConnectionFactory connectionFactory,
TaskCompletionSource<DbConnectionInternal> retry,
TimeoutTimer timeout)
{
throw ADP.MethodNotImplemented();
}
#endregion
#region Protected Methods
/// <summary>
/// Activates the connection, preparing it for active use.
/// An activated connection has an owner and is checked out from the connection pool (if pooling is enabled).
/// </summary>
/// <param name="transaction">The transaction in which the connection should enlist.</param>
protected abstract void Activate(Transaction transaction);
/// <summary>
/// Cleanup connection's transaction-specific structures (currently used by Delegated transaction).
/// This is a separate method because cleanup can be triggered in multiple ways for a delegated
/// transaction.
/// </summary>
protected virtual void CleanupTransactionOnCompletion(Transaction transaction)
{
}
protected virtual DbReferenceCollection CreateReferenceCollection()
{
throw ADP.InternalError(ADP.InternalErrorCode.AttemptingToConstructReferenceCollectionOnStaticObject);
}
/// <summary>
/// Deactivates the connection, cleaning up any state as necessary.
/// A deactivated connection is one that is no longer in active use and does not have an owner.
/// A deactivated connection may be open (connected to a server) and is checked into the connection pool (if pooling is enabled).
/// </summary>
protected abstract void Deactivate();
protected internal void DoNotPoolThisConnection()
{
_cannotBePooled = true;
SqlClientEventSource.Log.TryPoolerTraceEvent("<prov.DbConnectionInternal.DoNotPoolThisConnection|RES|INFO|CPOOL> {0}, Marking pooled object as non-poolable so it will be disposed", ObjectID);
}
/// <summary>
/// Ensure that this connection cannot be put back into the pool.
/// </summary>
protected internal void DoomThisConnection()
{
IsConnectionDoomed = true;
SqlClientEventSource.Log.TryPoolerTraceEvent("<prov.DbConnectionInternal.DoomThisConnection|RES|INFO|CPOOL> {0}, Dooming", ObjectID);
}
protected internal virtual DataTable GetSchema(
SqlConnectionFactory factory,
DbConnectionPoolGroup poolGroup,
DbConnection outerConnection,
string collectionName,
string[] restrictions)
{
Debug.Assert(outerConnection is not null, "outerConnection may not be null.");
SqlMetaDataFactory metaDataFactory = factory.GetMetaDataFactory(poolGroup, this);
Debug.Assert(metaDataFactory is not null, "metaDataFactory may not be null.");
return metaDataFactory.GetSchema(outerConnection, collectionName, restrictions);
}