forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVolatileResourceManager.cs
More file actions
367 lines (327 loc) · 14.7 KB
/
VolatileResourceManager.cs
File metadata and controls
367 lines (327 loc) · 14.7 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
#region License
// The PostgreSQL License
//
// Copyright (C) 2017 The Npgsql Development Team
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph and the following two paragraphs appear in all copies.
//
// IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY
// FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
// INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
// DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
// THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
// ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
#endregion
#if !NETSTANDARD1_3
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Transactions;
using JetBrains.Annotations;
using Npgsql.Logging;
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>
class VolatileResourceManager : ISinglePhaseNotification
{
[CanBeNull] NpgsqlConnector _connector;
[CanBeNull] Transaction _transaction;
[CanBeNull] readonly string _txId;
[CanBeNull] NpgsqlTransaction _localTx;
[CanBeNull] string _preparedTxName;
bool IsPrepared => _preparedTxName != null;
bool _isDisposed;
static readonly NpgsqlLogger Log = NpgsqlLogManager.GetCurrentClassLogger();
const int MaximumRollbackAttempts = 20;
internal VolatileResourceManager(NpgsqlConnection connection, [NotNull] Transaction transaction)
{
_connector = connection.Connector;
_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;
_localTx = connection.BeginTransaction(ConvertIsolationLevel(_transaction.IsolationLevel));
}
public void SinglePhaseCommit(SinglePhaseEnlistment singlePhaseEnlistment)
{
CheckDisposed();
Debug.Assert(_transaction != null, "No transaction");
Debug.Assert(_localTx != null, "No local transaction");
Debug.Assert(_connector != null, "No connector");
Log.Debug($"Single Phase Commit (localid={_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();
Debug.Assert(_transaction != null, "No transaction");
Debug.Assert(_localTx != null, "No local transaction");
Debug.Assert(_connector != null, "No connector");
Log.Debug($"Two-phase transaction prepare (localid={_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);
}
}
public void Commit(Enlistment enlistment)
{
CheckDisposed();
Debug.Assert(_transaction != null, "No transaction");
Debug.Assert(_connector != null, "No connector");
Log.Debug($"Two-phase transaction commit (localid={_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.
using (var conn2 = (NpgsqlConnection)((ICloneable)_connector.Connection).Clone())
{
conn2.Open();
var connector = conn2.Connector;
Debug.Assert(connector != null);
using (connector.StartUserAction())
connector.ExecuteInternalCommand($"COMMIT PREPARED '{_preparedTxName}'");
}
}
}
catch (Exception e)
{
Log.Error("Exception during two-phase transaction commit (localid={TransactionId})", e, _connector.Id);
}
finally
{
Dispose();
enlistment.Done();
}
}
public void Rollback(Enlistment enlistment)
{
CheckDisposed();
Debug.Assert(_transaction != null, "No transaction");
Debug.Assert(_connector != null, "No connector");
try
{
if (IsPrepared)
RollbackTwoPhase();
else
RollbackLocal();
}
catch (Exception e)
{
Log.Error($"Exception during transaction rollback (localid={_txId})", e, _connector.Id);
}
finally
{
Dispose();
enlistment.Done();
}
}
public void InDoubt(Enlistment enlistment)
{
Debug.Assert(_transaction != null, "No transaction");
Debug.Assert(_connector != null, "No connector");
Log.Warn($"Two-phase transaction in doubt (localid={_txId})", _connector.Id);
// TODO: Is this the correct behavior?
try
{
RollbackTwoPhase();
}
catch (Exception e)
{
Log.Error($"Exception during transaction rollback (localid={_txId})", e, _connector.Id);
}
finally
{
Dispose();
enlistment.Done();
}
}
void RollbackLocal()
{
Debug.Assert(_connector != null, "No connector");
Debug.Assert(_localTx != null, "No local transaction");
Log.Debug($"Single-phase transaction rollback (localid={_txId})", _connector.Id);
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.");
Log.Warn($"Connection in use while trying to rollback, will cancel and retry (localid={_txId}", _connector.Id);
_connector.CancelRequest();
// Cancellations are asynchronous, give it some time
Thread.Sleep(500);
}
}
}
void RollbackTwoPhase()
{
// This only occurs if we've started a two-phase commit but one of the commits has failed.
Log.Debug($"Two-phase transaction rollback (localid={_txId})", _connector.Id);
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;
Debug.Assert(connector != null);
using (connector.StartUserAction())
connector.ExecuteInternalCommand($"ROLLBACK PREPARED '{_preparedTxName}'");
}
}
}
#region Dispose/Cleanup
void Dispose()
{
if (_isDisposed)
return;
Debug.Assert(_transaction != null, "No transaction");
Debug.Assert(_connector != null, "No connector");
Log.Trace($"Cleaning up resource manager (localid={_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.
if (_connector.Settings.Pooling)
{
ConnectorPool pool;
lock (PoolManager.Pools)
{
var found = PoolManager.Pools.TryGetValue(_connector.ConnectionString, out pool);
Debug.Assert(found);
}
pool.TryRemovePendingEnlistedConnector(_connector, _transaction);
pool.Release(_connector);
}
else
_connector.Close();
}
_connector = null;
_transaction = null;
_isDisposed = true;
}
void CheckDisposed()
{
if (_isDisposed)
throw new ObjectDisposedException(nameof(VolatileResourceManager));
}
#endregion
static System.Data.IsolationLevel ConvertIsolationLevel(IsolationLevel isolationLevel)
{
switch (isolationLevel)
{
case IsolationLevel.Chaos:
return System.Data.IsolationLevel.Chaos;
case IsolationLevel.ReadCommitted:
return System.Data.IsolationLevel.ReadCommitted;
case IsolationLevel.ReadUncommitted:
return System.Data.IsolationLevel.ReadUncommitted;
case IsolationLevel.RepeatableRead:
return System.Data.IsolationLevel.RepeatableRead;
case IsolationLevel.Serializable:
return System.Data.IsolationLevel.Serializable;
case IsolationLevel.Snapshot:
return System.Data.IsolationLevel.Snapshot;
case IsolationLevel.Unspecified:
default:
return System.Data.IsolationLevel.Unspecified;
}
}
}
}
#endif