-
Notifications
You must be signed in to change notification settings - Fork 874
Expand file tree
/
Copy pathVolatileResourceManager.cs
More file actions
311 lines (276 loc) · 12.1 KB
/
VolatileResourceManager.cs
File metadata and controls
311 lines (276 loc) · 12.1 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
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Transactions;
using Microsoft.Extensions.Logging;
using Npgsql.Internal;
namespace Npgsql;
/// <summary>
///
/// </summary>
/// <remarks>
/// Note that a connection may be closed before its TransactionScope completes. In this case we close the NpgsqlConnection
/// as usual but the connector in a special list in the pool; it will be closed only when the scope completes.
/// </remarks>
sealed class VolatileResourceManager : ISinglePhaseNotification
{
NpgsqlConnector _connector;
NpgsqlDataSource _dataSource;
Transaction _transaction;
readonly string _txId;
NpgsqlTransaction _localTx = null!;
string? _preparedTxName;
bool IsPrepared => _preparedTxName != null;
bool _isDisposed;
readonly ILogger _transactionLogger;
const int MaximumRollbackAttempts = 20;
internal VolatileResourceManager(NpgsqlConnection connection, Transaction transaction)
{
_connector = connection.Connector!;
_dataSource = connection.NpgsqlDataSource;
_transaction = transaction;
// _tx gets disposed by System.Transactions at some point, but we want to be able to log its local ID
_txId = transaction.TransactionInformation.LocalIdentifier;
_transactionLogger = _connector.LoggingConfiguration.TransactionLogger;
}
internal void Init()
=> _localTx = _connector.Connection!.BeginTransaction(ConvertIsolationLevel(_transaction.IsolationLevel));
public void SinglePhaseCommit(SinglePhaseEnlistment singlePhaseEnlistment)
{
CheckDisposed();
LogMessages.CommittingSinglePhaseTransaction(_transactionLogger, _txId, _connector.Id);
try
{
_localTx.Commit();
singlePhaseEnlistment.Committed();
}
catch (PostgresException e)
{
singlePhaseEnlistment.Aborted(e);
}
catch (Exception e)
{
singlePhaseEnlistment.InDoubt(e);
}
finally
{
Dispose();
}
}
public void Prepare(PreparingEnlistment preparingEnlistment)
{
CheckDisposed();
LogMessages.PreparingTwoPhaseTransaction(_transactionLogger, _txId, _connector.Id);
// The PostgreSQL prepared transaction name is the distributed GUID + our connection's process ID, for uniqueness
_preparedTxName = $"{_transaction.TransactionInformation.DistributedIdentifier}/{_connector.BackendProcessId}";
try
{
using (_connector.StartUserAction())
_connector.ExecuteInternalCommand($"PREPARE TRANSACTION '{_preparedTxName}'");
// The MSDTC, which manages escalated distributed transactions, performs the 2nd phase
// asynchronously - this means that TransactionScope.Dispose() will return before all
// resource managers have actually commit.
// If the same connection tries to enlist to a new TransactionScope immediately after
// disposing an old TransactionScope, its EnlistedTransaction must have been cleared
// (or we'll throw a double enlistment exception). This must be done here at the 1st phase
// (which is sync).
if (_connector.Connection != null)
_connector.Connection.EnlistedTransaction = null;
preparingEnlistment.Prepared();
}
catch (Exception e)
{
Dispose();
preparingEnlistment.ForceRollback(e);
}
}
[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Changing Enlist to be false does not affect potentially trimmed out functionality.")]
[UnconditionalSuppressMessage("Aot", "IL3050", Justification = "Changing Enlist to be false does not cause dynamic codegen.")]
public void Commit(Enlistment enlistment)
{
CheckDisposed();
LogMessages.CommittingTwoPhaseTransaction(_transactionLogger, _txId, _connector.Id);
try
{
if (_connector.Connection == null)
{
// The connection has been closed before the TransactionScope was disposed.
// The connector is unbound from its connection and is sitting in the pool's
// pending enlisted connector list. Since there's no risk of the connector being
// used by anyone we can executed the 2nd phase on it directly (see below).
using (_connector.StartUserAction())
_connector.ExecuteInternalCommand($"COMMIT PREPARED '{_preparedTxName}'");
}
else
{
// The connection is still open and potentially will be reused by by the user.
// The MSDTC, which manages escalated distributed transactions, performs the 2nd phase
// asynchronously - this means that TransactionScope.Dispose() will return before all
// resource managers have actually commit. This can cause a concurrent connection use scenario
// if the user continues to use their connection after disposing the scope, and the MSDTC
// requests a commit at that exact time.
// To avoid this, we open a new connection for performing the 2nd phase.
var settings = _connector.Connection.Settings.Clone();
// Set Enlist to false because we might be in TransactionScope and we can't prepare transaction while being in an open transaction
// see #5246
settings.Enlist = false;
using var conn2 = _connector.Connection.CloneWith(settings.ConnectionString);
conn2.Open();
var connector = conn2.Connector!;
using (connector.StartUserAction())
connector.ExecuteInternalCommand($"COMMIT PREPARED '{_preparedTxName}'");
}
}
catch (Exception e)
{
LogMessages.TwoPhaseTransactionCommitFailed(_transactionLogger, _txId, _connector.Id, e);
}
finally
{
Dispose();
enlistment.Done();
}
}
public void Rollback(Enlistment enlistment)
{
CheckDisposed();
try
{
if (IsPrepared)
RollbackTwoPhase();
else
RollbackLocal();
}
finally
{
Dispose();
enlistment.Done();
}
}
public void InDoubt(Enlistment enlistment)
{
LogMessages.TwoPhaseTransactionInDoubt(_transactionLogger, _txId, _connector.Id);
// TODO: Is this the correct behavior?
try
{
RollbackTwoPhase();
}
finally
{
Dispose();
enlistment.Done();
}
}
void RollbackLocal()
{
LogMessages.RollingBackSinglePhaseTransaction(_transactionLogger, _txId, _connector.Id);
try
{
var attempt = 0;
while (true)
{
try
{
_localTx.Rollback();
return;
}
catch (NpgsqlOperationInProgressException)
{
// Repeatedly attempts to rollback, to support timeout-triggered rollbacks that occur
// while the connection is busy.
// This really shouldn't be necessary, but just in case
if (attempt++ == MaximumRollbackAttempts)
throw new Exception(
$"Could not roll back after {MaximumRollbackAttempts} attempts, aborting. Transaction is in an unknown state.");
LogMessages.ConnectionInUseWhenRollingBack(_transactionLogger, _txId, _connector.Id);
_connector.PerformPostgresCancellation();
// Cancellations are asynchronous, give it some time
Thread.Sleep(500);
}
}
}
catch
{
LogMessages.SinglePhaseTransactionRollbackFailed(_transactionLogger, _txId, _connector.Id);
}
}
void RollbackTwoPhase()
{
// This only occurs if we've started a two-phase commit but one of the commits has failed.
LogMessages.RollingBackTwoPhaseTransaction(_transactionLogger, _txId, _connector.Id);
try
{
if (_connector.Connection == null)
{
// The connection has been closed before the TransactionScope was disposed.
// The connector is unbound from its connection and is sitting in the pool's
// pending enlisted connector list. Since there's no risk of the connector being
// used by anyone we can executed the 2nd phase on it directly (see below).
using (_connector.StartUserAction())
_connector.ExecuteInternalCommand($"ROLLBACK PREPARED '{_preparedTxName}'");
}
else
{
// The connection is still open and potentially will be reused by by the user.
// The MSDTC, which manages escalated distributed transactions, performs the 2nd phase
// asynchronously - this means that TransactionScope.Dispose() will return before all
// resource managers have actually commit. This can cause a concurrent connection use scenario
// if the user continues to use their connection after disposing the scope, and the MSDTC
// requests a commit at that exact time.
// To avoid this, we open a new connection for performing the 2nd phase.
using var conn2 = (NpgsqlConnection)((ICloneable)_connector.Connection).Clone();
conn2.Open();
var connector = conn2.Connector!;
using (connector.StartUserAction())
connector.ExecuteInternalCommand($"ROLLBACK PREPARED '{_preparedTxName}'");
}
}
catch (Exception e)
{
LogMessages.TwoPhaseTransactionRollbackFailed(_transactionLogger, _txId, _connector.Id, e);
}
}
#region Dispose/Cleanup
#pragma warning disable CS8625
void Dispose()
{
if (_isDisposed)
return;
LogMessages.CleaningUpResourceManager(_transactionLogger, _txId, _connector.Id);
if (_localTx != null)
{
_localTx.Dispose();
_localTx = null;
}
if (_connector.Connection != null)
_connector.Connection.EnlistedTransaction = null;
else
{
// We're here for connections which were closed before their TransactionScope completes.
// These need to be closed now.
// We should return the connector to the pool only if we've successfully removed it from the pending list.
// Note that we remove it from the NpgsqlDataSource bound to connection and not to connector
// because of NpgsqlMultiHostDataSource which has its own list to which connection adds connectors.
if (_dataSource.TryRemovePendingEnlistedConnector(_connector, _transaction))
_connector.Return();
}
_connector = null!;
_transaction = null!;
_isDisposed = true;
}
#pragma warning restore CS8625
void CheckDisposed()
=> ObjectDisposedException.ThrowIf(_isDisposed, this);
#endregion
static System.Data.IsolationLevel ConvertIsolationLevel(IsolationLevel isolationLevel)
=> isolationLevel switch
{
IsolationLevel.Chaos => System.Data.IsolationLevel.Chaos,
IsolationLevel.ReadCommitted => System.Data.IsolationLevel.ReadCommitted,
IsolationLevel.ReadUncommitted => System.Data.IsolationLevel.ReadUncommitted,
IsolationLevel.RepeatableRead => System.Data.IsolationLevel.RepeatableRead,
IsolationLevel.Serializable => System.Data.IsolationLevel.Serializable,
IsolationLevel.Snapshot => System.Data.IsolationLevel.Snapshot,
_ => System.Data.IsolationLevel.Unspecified
};
}