/
transaction_participant.cpp
3312 lines (2834 loc) · 153 KB
/
transaction_participant.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#define LOGV2_FOR_TRANSACTION(ID, DLEVEL, MESSAGE, ...) \
LOGV2_DEBUG_OPTIONS(ID, DLEVEL, {logv2::LogComponent::kTransaction}, MESSAGE, ##__VA_ARGS__)
#include "mongo/platform/basic.h"
#include "mongo/db/transaction_participant.h"
#include <fmt/format.h>
#include "mongo/db/catalog/database_holder.h"
#include "mongo/db/catalog/index_catalog.h"
#include "mongo/db/catalog/local_oplog_info.h"
#include "mongo/db/catalog/uncommitted_catalog_updates.h"
#include "mongo/db/catalog_raii.h"
#include "mongo/db/commands/test_commands_enabled.h"
#include "mongo/db/concurrency/d_concurrency.h"
#include "mongo/db/concurrency/exception_util.h"
#include "mongo/db/concurrency/lock_state.h"
#include "mongo/db/concurrency/locker.h"
#include "mongo/db/concurrency/replication_state_transition_lock_guard.h"
#include "mongo/db/curop_failpoint_helpers.h"
#include "mongo/db/dbdirectclient.h"
#include "mongo/db/dbhelpers.h"
#include "mongo/db/index/index_access_method.h"
#include "mongo/db/internal_transactions_feature_flag_gen.h"
#include "mongo/db/logical_session_id.h"
#include "mongo/db/op_observer.h"
#include "mongo/db/ops/update.h"
#include "mongo/db/ops/write_ops_retryability.h"
#include "mongo/db/query/get_executor.h"
#include "mongo/db/repl/apply_ops_command_info.h"
#include "mongo/db/repl/repl_client_info.h"
#include "mongo/db/repl/storage_interface.h"
#include "mongo/db/retryable_writes_stats.h"
#include "mongo/db/s/sharding_write_router.h"
#include "mongo/db/server_recovery.h"
#include "mongo/db/server_transactions_metrics.h"
#include "mongo/db/session_catalog_mongod.h"
#include "mongo/db/stats/fill_locker_info.h"
#include "mongo/db/storage/flow_control.h"
#include "mongo/db/transaction_history_iterator.h"
#include "mongo/db/transaction_participant_gen.h"
#include "mongo/db/txn_retry_counter_too_old_info.h"
#include "mongo/db/vector_clock_mutable.h"
#include "mongo/logv2/log.h"
#include "mongo/s/grid.h"
#include "mongo/s/would_change_owning_shard_exception.h"
#include "mongo/util/fail_point.h"
#include "mongo/util/log_with_sampling.h"
#include "mongo/util/net/socket_utils.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kStorage
namespace mongo {
using namespace fmt::literals;
namespace {
// Failpoint which will pause an operation just after allocating a point-in-time storage engine
// transaction.
MONGO_FAIL_POINT_DEFINE(hangAfterPreallocateSnapshot);
MONGO_FAIL_POINT_DEFINE(hangAfterReservingPrepareTimestamp);
MONGO_FAIL_POINT_DEFINE(hangAfterSettingPrepareStartTime);
MONGO_FAIL_POINT_DEFINE(hangBeforeReleasingTransactionOplogHole);
MONGO_FAIL_POINT_DEFINE(skipCommitTxnCheckPrepareMajorityCommitted);
MONGO_FAIL_POINT_DEFINE(restoreLocksFail);
MONGO_FAIL_POINT_DEFINE(failTransactionNoopWrite);
MONGO_FAIL_POINT_DEFINE(hangAfterCheckingInternalTransactionsFeatureFlag);
const auto getTransactionParticipant = Session::declareDecoration<TransactionParticipant>();
const auto retryableWriteTransactionParticipantCatalogDecoration =
Session::declareDecoration<RetryableWriteTransactionParticipantCatalog>();
/**
* Returns the RetryableWriteTransactionParticipantCatalog for the given session.
*/
RetryableWriteTransactionParticipantCatalog& getRetryableWriteTransactionParticipantCatalog(
Session* session) {
if (const auto parentSession = session->getParentSession()) {
return retryableWriteTransactionParticipantCatalogDecoration(parentSession);
}
return retryableWriteTransactionParticipantCatalogDecoration(session);
}
/**
* Returns the RetryableWriteTransactionParticipantCatalog for the session checked out by the
* given 'opCtx'.
*/
RetryableWriteTransactionParticipantCatalog& getRetryableWriteTransactionParticipantCatalog(
OperationContext* opCtx) {
auto session = OperationContextSession::get(opCtx);
return getRetryableWriteTransactionParticipantCatalog(session);
}
// The command names that are allowed in a prepared transaction.
const StringMap<int> preparedTxnCmdAllowlist = {
{"abortTransaction", 1}, {"commitTransaction", 1}, {"prepareTransaction", 1}};
void fassertOnRepeatedExecution(const LogicalSessionId& lsid,
TxnNumberAndRetryCounter txnNumberAndRetryCounter,
StmtId stmtId,
const repl::OpTime& firstOpTime,
const repl::OpTime& secondOpTime) {
LOGV2_FATAL(
40526,
"Statement id {stmtId} from transaction [ {lsid}:{txnNumberAndRetryCounter} ] was "
"committed once with opTime {firstCommitOpTime} and a second time with opTime { "
"secondCommitOpTime}. This indicates possible data corruption or server bug and the "
"process will be terminated.",
"Statement from transaction was committed twice. This indicates possible data corruption "
"or server bug and the process will be terminated",
"stmtId"_attr = stmtId,
"lsid"_attr = lsid.toBSON(),
"txnNumberAndRetryCounter"_attr = txnNumberAndRetryCounter,
"firstCommitOpTime"_attr = firstOpTime,
"secondCommitOpTime"_attr = secondOpTime);
}
void validateTransactionHistoryApplyOpsOplogEntry(const repl::OplogEntry& oplogEntry) {
uassert(5875601,
"Found an applyOps oplog entry for retryable writes that were executed without "
"using a retryable internal transaction",
isInternalSessionForRetryableWrite(*oplogEntry.getSessionId()));
uassert(5875602,
"Found an applyOps oplog entry for retryable internal transaction with top-level "
"'stmtId' field",
oplogEntry.getStatementIds().empty());
}
/**
* Runs the given 'callable' with a DBDirectClient with a no-timestamp read source, and restores
* the original timestamp read source after returning. Used for performing a read against the
* config.transactions collection during refresh below since snapshot reads and causal consistent
* majority reads against are not supported in that collection.
*/
template <typename Callable>
auto performReadWithNoTimestampDBDirectClient(OperationContext* opCtx, Callable&& callable) {
ReadSourceScope readSourceScope(opCtx, RecoveryUnit::ReadSource::kNoTimestamp);
DBDirectClient client(opCtx);
// If the 'opCtx' is marked as "in multi document transaction", the read done by 'callable'
// would acquire the global lock in the IX mode. That upconvert would require a flow control
// ticket to be obtained.
FlowControl::Bypass flowControlBypass(opCtx);
return callable(&client);
}
void rethrowPartialIndexQueryBadValueWithContext(const DBException& ex) {
if (ex.reason().find("hint provided does not correspond to an existing index") !=
std::string::npos) {
uassertStatusOKWithContext(
ex.toStatus(),
str::stream()
<< "Failed to find partial index for "
<< NamespaceString::kSessionTransactionsTableNamespace.ns()
<< ". Please create an index directly on this replica set with the specification: "
<< MongoDSessionCatalog::getConfigTxnPartialIndexSpec() << " or drop the "
<< NamespaceString::kSessionTransactionsTableNamespace.ns()
<< " collection and step up a new primary.");
}
}
struct ActiveTransactionHistory {
boost::optional<SessionTxnRecord> lastTxnRecord;
TransactionParticipant::CommittedStatementTimestampMap committedStatements;
bool hasIncompleteHistory{false};
};
ActiveTransactionHistory fetchActiveTransactionHistory(OperationContext* opCtx,
const LogicalSessionId& lsid,
bool fetchOplogEntries) {
// Storage engine operations require at least Global IS.
Lock::GlobalLock lk(opCtx, MODE_IS);
ActiveTransactionHistory result;
result.lastTxnRecord = [&]() -> auto {
return performReadWithNoTimestampDBDirectClient(
opCtx, [&](DBDirectClient* client) -> boost::optional<SessionTxnRecord> {
auto result =
client->findOne(NamespaceString::kSessionTransactionsTableNamespace,
BSON(SessionTxnRecord::kSessionIdFieldName << lsid.toBSON()));
if (result.isEmpty()) {
return boost::none;
}
return SessionTxnRecord::parse(
IDLParserErrorContext("parse latest txn record for session"), result);
});
}
();
if (!result.lastTxnRecord) {
return result;
}
if (auto state = result.lastTxnRecord->getState()) {
if (!isInternalSessionForRetryableWrite(lsid) || state != DurableTxnStateEnum::kCommitted) {
// When state is given, it must be a transaction, so we don't need to traverse the
// history if it is not a committed transaction for retryable writes.
return result;
}
}
if (!fetchOplogEntries) {
return result;
}
// Helper for registering statement ids of an oplog entry for a retryable write or a retryable
// internal transaction.
auto insertStmtIdsForOplogEntry = [&](const repl::OplogEntry& entry) {
for (auto stmtId : entry.getStatementIds()) {
uassert(5875604,
str::stream() << "Found an oplog entry with an invalid stmtId "
<< entry.toBSONForLogging(),
stmtId >= 0);
const auto insertRes = result.committedStatements.emplace(stmtId, entry.getOpTime());
if (!insertRes.second) {
const auto& existingOpTime = insertRes.first->second;
fassertOnRepeatedExecution(lsid,
result.lastTxnRecord->getTxnNum(),
stmtId,
existingOpTime,
entry.getOpTime());
}
}
};
// Restore the current timestamp read source after fetching transaction history, which may
// change our ReadSource.
ReadSourceScope readSourceScope(opCtx, RecoveryUnit::ReadSource::kNoTimestamp);
auto it = TransactionHistoryIterator(result.lastTxnRecord->getLastWriteOpTime());
while (it.hasNext()) {
try {
const auto entry = it.next(opCtx);
auto stmtIds = entry.getStatementIds();
if (isInternalSessionForRetryableWrite(lsid)) {
uassert(5875605,
"Found an oplog entry for retryable internal transaction with top-level "
"'stmtId' field",
stmtIds.empty());
if (entry.getCommandType() == repl::OplogEntry::CommandType::kCommitTransaction) {
continue;
} else if (entry.getCommandType() == repl::OplogEntry::CommandType::kApplyOps) {
validateTransactionHistoryApplyOpsOplogEntry(entry);
std::vector<repl::OplogEntry> innerEntries;
repl::ApplyOps::extractOperationsTo(
entry, entry.getEntry().toBSON(), &innerEntries);
for (const auto& innerEntry : innerEntries) {
insertStmtIdsForOplogEntry(innerEntry);
}
} else {
MONGO_UNREACHABLE;
}
} else {
// Oplog entries for retryable writes are expected to have a statement id.
invariant(!stmtIds.empty());
if (stmtIds.front() == kIncompleteHistoryStmtId) {
// Only the dead end sentinel can have this id for oplog write history
invariant(stmtIds.size() == 1);
invariant(entry.getObject2());
invariant(entry.getObject2()->woCompare(
TransactionParticipant::kDeadEndSentinel) == 0);
result.hasIncompleteHistory = true;
continue;
}
// TODO (SERVER-64172): Remove leftover upgrade/downgrade code from 4.2 in
// fetchActiveTransactionHistory.
if (entry.getCommandType() == repl::OplogEntry::CommandType::kApplyOps &&
!entry.shouldPrepare() && !entry.isPartialTransaction()) {
result.lastTxnRecord->setState(DurableTxnStateEnum::kCommitted);
return result;
}
insertStmtIdsForOplogEntry(entry);
}
} catch (const DBException& ex) {
if (ex.code() == ErrorCodes::IncompleteTransactionHistory) {
result.hasIncompleteHistory = true;
break;
}
throw;
}
}
return result;
}
/**
* Returns the highest txnNumber in the given session that has corresponding internal sessions as
* found in the session catalog and the config.transactions collection.
*/
TxnNumber fetchHighestTxnNumberWithInternalSessions(OperationContext* opCtx,
const LogicalSessionId& parentLsid) {
TxnNumber highestTxnNumber{kUninitializedTxnNumber};
const auto sessionCatalog = SessionCatalog::get(opCtx);
sessionCatalog->scanSession(parentLsid, [&](const ObservableSession& osession) {
highestTxnNumber = osession.getHighestTxnNumberWithChildSessions();
});
try {
performReadWithNoTimestampDBDirectClient(opCtx, [&](DBDirectClient* client) {
FindCommandRequest findRequest{NamespaceString::kSessionTransactionsTableNamespace};
findRequest.setFilter(BSON(SessionTxnRecord::kParentSessionIdFieldName
<< parentLsid.toBSON()
<< (SessionTxnRecord::kSessionIdFieldName + "." +
LogicalSessionId::kTxnNumberFieldName)
<< BSON("$gte" << highestTxnNumber)));
findRequest.setSort(BSON((SessionTxnRecord::kSessionIdFieldName + "." +
LogicalSessionId::kTxnNumberFieldName)
<< -1));
findRequest.setProjection(BSON(SessionTxnRecord::kSessionIdFieldName << 1));
findRequest.setLimit(1);
findRequest.setHint(BSON("$hint" << MongoDSessionCatalog::kConfigTxnsPartialIndexName));
auto cursor = client->find(findRequest);
while (cursor->more()) {
const auto doc = cursor->next();
const auto childLsid = LogicalSessionId::parse(
IDLParserErrorContext("LogicalSessionId"), doc.getObjectField("_id"));
highestTxnNumber = std::max(highestTxnNumber, *childLsid.getTxnNumber());
invariant(!cursor->more());
}
});
} catch (const ExceptionFor<ErrorCodes::BadValue>& ex) {
rethrowPartialIndexQueryBadValueWithContext(ex);
throw;
}
return highestTxnNumber;
}
void updateSessionEntry(OperationContext* opCtx,
const UpdateRequest& updateRequest,
const LogicalSessionId& sessionId,
TxnNumber txnNum) {
// Current code only supports replacement update.
dassert(updateRequest.getUpdateModification().type() ==
write_ops::UpdateModification::Type::kReplacement);
const auto updateMod = updateRequest.getUpdateModification().getUpdateReplacement();
// TODO SERVER-58243: evaluate whether this is safe or whether acquiring the lock can block.
AllowLockAcquisitionOnTimestampedUnitOfWork allowLockAcquisition(opCtx->lockState());
AutoGetCollection collection(
opCtx, NamespaceString::kSessionTransactionsTableNamespace, MODE_IX);
uassert(40527,
str::stream() << "Unable to persist transaction state because the session transaction "
"collection is missing. This indicates that the "
<< NamespaceString::kSessionTransactionsTableNamespace.ns()
<< " collection has been manually deleted.",
collection.getCollection());
WriteUnitOfWork wuow(opCtx);
auto idIndex = collection->getIndexCatalog()->findIdIndex(opCtx);
uassert(40672,
str::stream() << "Failed to fetch _id index for "
<< NamespaceString::kSessionTransactionsTableNamespace.ns(),
idIndex);
auto indexAccess =
collection->getIndexCatalog()->getEntry(idIndex)->accessMethod()->asSortedData();
// Since we are looking up a key inside the _id index, create a key object consisting of only
// the _id field.
auto idToFetch = updateRequest.getQuery().firstElement();
auto toUpdateIdDoc = idToFetch.wrap();
dassert(idToFetch.fieldNameStringData() == "_id"_sd);
auto recordId = indexAccess->findSingle(opCtx, *collection, toUpdateIdDoc);
auto startingSnapshotId = opCtx->recoveryUnit()->getSnapshotId();
if (recordId.isNull()) {
// Upsert case.
auto status = collection->insertDocument(opCtx, InsertStatement(updateMod), nullptr, false);
if (status == ErrorCodes::DuplicateKey) {
throwWriteConflictException(
str::stream() << "Updating session entry failed with duplicate key, session "_sd
<< sessionId << ", transaction "_sd << txnNum);
}
uassertStatusOK(status);
wuow.commit();
return;
}
auto originalRecordData = collection->getRecordStore()->dataFor(opCtx, recordId);
auto originalDoc = originalRecordData.toBson();
const auto parentLsidFieldName = SessionTxnRecord::kParentSessionIdFieldName;
uassert(5875700,
str::stream() << "Cannot modify the '" << parentLsidFieldName << "' field of "
<< NamespaceString::kSessionTransactionsTableNamespace << " entries",
updateMod.getObjectField(parentLsidFieldName)
.woCompare(originalDoc.getObjectField(parentLsidFieldName)) == 0);
invariant(collection->getDefaultCollator() == nullptr);
boost::intrusive_ptr<ExpressionContext> expCtx(
new ExpressionContext(opCtx, nullptr, updateRequest.getNamespaceString()));
auto matcher =
fassert(40673, MatchExpressionParser::parse(updateRequest.getQuery(), std::move(expCtx)));
if (!matcher->matchesBSON(originalDoc)) {
// Document no longer match what we expect so throw WCE to make the caller re-examine.
throwWriteConflictException(
str::stream() << "Updating session entry failed as document no longer matches, "_sd
<< "session "_sd << sessionId << ", transaction "_sd << txnNum);
}
CollectionUpdateArgs args;
args.update = updateMod;
args.criteria = toUpdateIdDoc;
// Specify indexesAffected = false because the sessions collection has two indexes: {_id: 1} and
// {parentLsid: 1, _id.txnNumber: 1, _id: 1}, and none of the fields are mutable.
collection->updateDocument(opCtx,
recordId,
Snapshotted<BSONObj>(startingSnapshotId, originalDoc),
updateMod,
false, /* indexesAffected */
nullptr,
&args);
wuow.commit();
}
// Failpoint which allows different failure actions to happen after each write. Supports the
// parameters below, which can be combined with each other (unless explicitly disallowed):
//
// closeConnection (bool, default = true): Closes the connection on which the write was executed.
// failBeforeCommitExceptionCode (int, default = not specified): If set, the specified exception
// code will be thrown, which will cause the write to not commit; if not specified, the write
// will be allowed to commit.
MONGO_FAIL_POINT_DEFINE(onPrimaryTransactionalWrite);
} // namespace
const BSONObj TransactionParticipant::kDeadEndSentinel(BSON("$incompleteOplogHistory" << 1));
TransactionParticipant::TransactionParticipant() = default;
TransactionParticipant::~TransactionParticipant() {
// invariant(!_o.txnState.isInProgress());
}
TransactionParticipant::Observer::Observer(const ObservableSession& osession)
: Observer(&getTransactionParticipant(osession.get())) {}
TransactionParticipant::Participant::Participant(OperationContext* opCtx)
: Observer([opCtx]() -> TransactionParticipant* {
if (auto session = OperationContextSession::get(opCtx)) {
return &getTransactionParticipant(session);
}
return nullptr;
}()) {}
TransactionParticipant::Participant::Participant(OperationContext* opCtx, Session* session)
: Observer([opCtx, session]() -> TransactionParticipant* {
invariant(session);
auto checkedOutSession = OperationContextSession::get(opCtx);
uassert(6202000,
str::stream() << "Cannot get the transaction participant for the session "
<< session->getSessionId()
<< " without having it or its parent checked out",
checkedOutSession &&
(castToParentSessionId(checkedOutSession->getSessionId()) ==
castToParentSessionId(session->getSessionId())));
return &getTransactionParticipant(session);
}()) {}
TransactionParticipant::Participant::Participant(const SessionToKill& session)
: Observer(&getTransactionParticipant(session.get())) {}
void TransactionParticipant::performNoopWrite(OperationContext* opCtx, StringData msg) {
const auto replCoord = repl::ReplicationCoordinator::get(opCtx);
// The locker must not have a max lock timeout when this noop write is performed, since if it
// threw LockTimeout, this would be treated as a TransientTransactionError, which would indicate
// it's safe to retry the entire transaction. We cannot know it is safe to attach
// TransientTransactionError until the noop write has been performed and the writeConcern has
// been satisfied.
invariant(!opCtx->lockState()->hasMaxLockTimeout());
// Simulate an operation timeout and fail the noop write if the fail point is enabled. This is
// to test that NoSuchTransaction error is not considered transient if the noop write cannot
// occur.
if (MONGO_unlikely(failTransactionNoopWrite.shouldFail())) {
uasserted(ErrorCodes::MaxTimeMSExpired, "failTransactionNoopWrite fail point enabled");
}
{
AutoGetOplog oplogWrite(opCtx, OplogAccessMode::kWrite);
uassert(ErrorCodes::NotWritablePrimary,
"Not primary when performing noop write for {}"_format(msg),
replCoord->canAcceptWritesForDatabase(opCtx, "admin"));
writeConflictRetry(
opCtx, "performNoopWrite", NamespaceString::kRsOplogNamespace.ns(), [&opCtx, &msg] {
WriteUnitOfWork wuow(opCtx);
opCtx->getClient()->getServiceContext()->getOpObserver()->onOpMessage(
opCtx, BSON("msg" << msg));
wuow.commit();
});
}
}
StorageEngine::OldestActiveTransactionTimestampResult
TransactionParticipant::getOldestActiveTimestamp(Timestamp stableTimestamp) {
// Read from config.transactions at the stable timestamp for the oldest active transaction
// timestamp. Use a short timeout: another thread might have the global lock e.g. to shut down
// the server, and it both blocks this thread from querying config.transactions and waits for
// this thread to terminate.
auto client = getGlobalServiceContext()->makeClient("OldestActiveTxnTimestamp");
AlternativeClientRegion acr(client);
try {
auto opCtx = cc().makeOperationContext();
auto nss = NamespaceString::kSessionTransactionsTableNamespace;
auto deadline = Date_t::now() + Milliseconds(100);
ShouldNotConflictWithSecondaryBatchApplicationBlock shouldNotConflictBlock(
opCtx->lockState());
Lock::DBLock dbLock(opCtx.get(), nss.db(), MODE_IS, deadline);
Lock::CollectionLock collLock(opCtx.get(), nss, MODE_IS, deadline);
auto databaseHolder = DatabaseHolder::get(opCtx.get());
auto db = databaseHolder->getDb(opCtx.get(), nss.dbName());
if (!db) {
// There is no config database, so there cannot be any active transactions.
return boost::none;
}
auto collection =
CollectionCatalog::get(opCtx.get())->lookupCollectionByNamespace(opCtx.get(), nss);
if (!collection) {
return boost::none;
}
if (!stableTimestamp.isNull()) {
opCtx->recoveryUnit()->setTimestampReadSource(RecoveryUnit::ReadSource::kProvided,
stableTimestamp);
}
// Scan. We guess that occasional scans are cheaper than the write overhead of an index.
boost::optional<Timestamp> oldestTxnTimestamp;
auto cursor = collection->getCursor(opCtx.get());
while (auto record = cursor->next()) {
auto doc = record.get().data.toBson();
auto txnRecord = SessionTxnRecord::parse(
IDLParserErrorContext("parse oldest active txn record"), doc);
if (txnRecord.getState() != DurableTxnStateEnum::kPrepared &&
txnRecord.getState() != DurableTxnStateEnum::kInProgress) {
continue;
}
// A prepared transaction must have a start timestamp.
invariant(txnRecord.getStartOpTime());
auto ts = txnRecord.getStartOpTime()->getTimestamp();
if (!oldestTxnTimestamp || ts < oldestTxnTimestamp.value()) {
oldestTxnTimestamp = ts;
}
}
return oldestTxnTimestamp;
} catch (const DBException&) {
return exceptionToStatus();
}
}
Session* TransactionParticipant::Observer::_session() const {
return getTransactionParticipant.owner(_tp);
}
const LogicalSessionId& TransactionParticipant::Observer::_sessionId() const {
return _session()->getSessionId();
}
bool TransactionParticipant::Observer::_isInternalSession() const {
return getParentSessionId(_sessionId()).has_value();
}
bool TransactionParticipant::Observer::_isInternalSessionForRetryableWrite() const {
return isInternalSessionForRetryableWrite(_sessionId());
}
bool TransactionParticipant::Observer::_isInternalSessionForNonRetryableWrite() const {
return isInternalSessionForNonRetryableWrite(_sessionId());
}
boost::optional<TxnNumber> TransactionParticipant::Observer::_activeRetryableWriteTxnNumber()
const {
if (_isInternalSessionForNonRetryableWrite()) {
return boost::none;
}
if (_isInternalSessionForRetryableWrite()) {
return *_sessionId().getTxnNumber();
}
invariant(!_isInternalSession());
if (o().txnState.isInRetryableWriteMode()) {
const auto txnNumber = o().activeTxnNumberAndRetryCounter.getTxnNumber();
return txnNumber != kUninitializedTxnNumber ? boost::make_optional(txnNumber) : boost::none;
}
return boost::none;
}
void TransactionParticipant::Participant::_uassertNoConflictingInternalTransactionForRetryableWrite(
OperationContext* opCtx, const TxnNumberAndRetryCounter& txnNumberAndRetryCounter) {
auto& retryableWriteTxnParticipantCatalog =
getRetryableWriteTransactionParticipantCatalog(opCtx);
invariant(retryableWriteTxnParticipantCatalog.isValid());
for (const auto& it : retryableWriteTxnParticipantCatalog.getParticipants()) {
const auto& txnParticipant = it.second;
if (txnParticipant._sessionId() == opCtx->getLogicalSessionId() ||
!txnParticipant._isInternalSessionForRetryableWrite()) {
continue;
}
uassert(ErrorCodes::RetryableTransactionInProgress,
str::stream() << "Cannot run retryable write with session id " << _sessionId()
<< " and transaction number "
<< txnNumberAndRetryCounter.getTxnNumber()
<< " because it is being executed in a retryable internal transaction"
<< " with session id " << txnParticipant._sessionId()
<< " and transaction number "
<< txnParticipant.getActiveTxnNumberAndRetryCounter().getTxnNumber()
<< " in state " << txnParticipant.o().txnState,
!txnParticipant.transactionIsOpen());
}
}
void TransactionParticipant::Participant::_uassertCanReuseActiveTxnNumberForTransaction(
OperationContext* opCtx) {
if (o().txnState.isInSet(TransactionState::kNone)) {
const auto& retryableWriteTxnParticipantCatalog =
getRetryableWriteTransactionParticipantCatalog(opCtx);
invariant(retryableWriteTxnParticipantCatalog.isValid());
for (const auto& it : retryableWriteTxnParticipantCatalog.getParticipants()) {
const auto& txnParticipant = it.second;
if (txnParticipant._sessionId() == _sessionId()) {
continue;
}
invariant(txnParticipant._isInternalSessionForRetryableWrite());
uassert(
6202002,
str::stream() << "Cannot start transaction with session id " << _sessionId()
<< " and transaction number "
<< o().activeTxnNumberAndRetryCounter.getTxnNumber()
<< " because a retryable write with the same transaction number"
<< " is being executed in a retryable internal transaction "
<< " with session id " << txnParticipant._sessionId()
<< " and transaction number "
<< txnParticipant.getActiveTxnNumberAndRetryCounter().getTxnNumber()
<< " in state " << txnParticipant.o().txnState,
txnParticipant.transactionIsAbortedWithoutPrepare());
}
} else {
uassert(
50911,
str::stream() << "Cannot start a transaction with session id " << _sessionId()
<< " and transaction number "
<< o().activeTxnNumberAndRetryCounter.toBSON()
<< " because a transaction with the same transaction number is in state "
<< o().txnState,
o().txnState.isInSet(TransactionState::kAbortedWithoutPrepare));
}
}
void TransactionParticipant::Participant::_beginOrContinueRetryableWrite(
OperationContext* opCtx, const TxnNumberAndRetryCounter& txnNumberAndRetryCounter) {
invariant(!txnNumberAndRetryCounter.getTxnRetryCounter());
_uassertNoConflictingInternalTransactionForRetryableWrite(opCtx, txnNumberAndRetryCounter);
if (txnNumberAndRetryCounter.getTxnNumber() >
o().activeTxnNumberAndRetryCounter.getTxnNumber()) {
// New retryable write.
_setNewTxnNumberAndRetryCounter(
opCtx, {txnNumberAndRetryCounter.getTxnNumber(), kUninitializedTxnRetryCounter});
p().autoCommit = boost::none;
auto& retryableWriteTxnParticipantCatalog =
getRetryableWriteTransactionParticipantCatalog(opCtx);
retryableWriteTxnParticipantCatalog.addParticipant(*this);
} else {
// Retrying a retryable write.
// If this retryable write's transaction id has been converted to a transaction, and that
// transaction is in prepare, wait for it to exit prepare before throwing
// IncompleteTransactionHistory so the error response's operationTime is inclusive of the
// transaction's 2PC decision, guaranteeing causally consistent sessions will always read
// the transaction's writes.
uassert(ErrorCodes::PreparedTransactionInProgress,
"Retryable write that has been converted to a transaction is in prepare",
!o().txnState.isInSet(TransactionState::kPrepared));
uassert(ErrorCodes::IncompleteTransactionHistory,
"Cannot retry a retryable write that has been converted into a transaction",
o().txnState.isInRetryableWriteMode());
invariant(p().autoCommit == boost::none);
}
}
void TransactionParticipant::Participant::_continueMultiDocumentTransaction(
OperationContext* opCtx, const TxnNumberAndRetryCounter& txnNumberAndRetryCounter) {
uassert(ErrorCodes::NoSuchTransaction,
str::stream()
<< "Given transaction number " << txnNumberAndRetryCounter.getTxnNumber()
<< " does not match any in-progress transactions. The active transaction number is "
<< o().activeTxnNumberAndRetryCounter.getTxnNumber(),
txnNumberAndRetryCounter.getTxnNumber() ==
o().activeTxnNumberAndRetryCounter.getTxnNumber() &&
!o().txnState.isInRetryableWriteMode());
uassert(TxnRetryCounterTooOldInfo(*o().activeTxnNumberAndRetryCounter.getTxnRetryCounter()),
str::stream() << "Cannot continue transaction "
<< txnNumberAndRetryCounter.getTxnNumber() << " on session "
<< _sessionId() << " using txnRetryCounter "
<< txnNumberAndRetryCounter.getTxnRetryCounter()
<< " because it has already been restarted using a higher"
<< " txnRetryCounter "
<< o().activeTxnNumberAndRetryCounter.getTxnRetryCounter(),
txnNumberAndRetryCounter.getTxnRetryCounter() >=
o().activeTxnNumberAndRetryCounter.getTxnRetryCounter());
uassert(ErrorCodes::IllegalOperation,
str::stream() << "Cannot continue transaction "
<< txnNumberAndRetryCounter.getTxnNumber() << " on session "
<< _sessionId() << " using txnNumberAndRetryCounter.getTxnRetryCounter() "
<< txnNumberAndRetryCounter.getTxnRetryCounter()
<< " because it is currently in state " << o().txnState
<< " with txnRetryCounter "
<< o().activeTxnNumberAndRetryCounter.getTxnRetryCounter(),
txnNumberAndRetryCounter.getTxnRetryCounter() ==
o().activeTxnNumberAndRetryCounter.getTxnRetryCounter());
if (o().txnState.isInProgress() && !o().txnResourceStash) {
// This indicates that the first command in the transaction failed but did not implicitly
// abort the transaction. It is not safe to continue the transaction, in particular because
// we have not saved the readConcern from the first statement of the transaction. Mark the
// transaction as active here, since _abortTransactionOnSession() will assume we are
// aborting an active transaction since there are no stashed resources.
{
stdx::lock_guard<Client> lk(*opCtx->getClient());
o(lk).transactionMetricsObserver.onUnstash(
ServerTransactionsMetrics::get(opCtx->getServiceContext()),
opCtx->getServiceContext()->getTickSource());
}
_abortTransactionOnSession(opCtx);
uasserted(
ErrorCodes::NoSuchTransaction,
str::stream()
<< "Transaction with " << txnNumberAndRetryCounter.toBSON()
<< " has been aborted because an earlier command in this transaction failed.");
}
}
void TransactionParticipant::Participant::_beginMultiDocumentTransaction(
OperationContext* opCtx, const TxnNumberAndRetryCounter& txnNumberAndRetryCounter) {
if (txnNumberAndRetryCounter.getTxnNumber() ==
o().activeTxnNumberAndRetryCounter.getTxnNumber()) {
if (txnNumberAndRetryCounter.getTxnRetryCounter() <
o().activeTxnNumberAndRetryCounter.getTxnRetryCounter()) {
uasserted(
TxnRetryCounterTooOldInfo(*o().activeTxnNumberAndRetryCounter.getTxnRetryCounter()),
str::stream() << "Cannot start a transaction at given transaction number "
<< txnNumberAndRetryCounter.getTxnNumber() << " on session "
<< _sessionId() << " using txnRetryCounter "
<< txnNumberAndRetryCounter.getTxnRetryCounter()
<< " because it has already been restarted using a "
<< "higher txnRetryCounter "
<< o().activeTxnNumberAndRetryCounter.getTxnRetryCounter());
} else if (txnNumberAndRetryCounter.getTxnRetryCounter() ==
o().activeTxnNumberAndRetryCounter.getTxnRetryCounter() ||
o().activeTxnNumberAndRetryCounter.getTxnRetryCounter() ==
kUninitializedTxnRetryCounter) {
// Servers in a sharded cluster can start a new transaction at the active transaction
// number to allow internal retries by routers on re-targeting errors, like
// StaleShard/DatabaseVersion or SnapshotTooOld.
uassert(ErrorCodes::ConflictingOperationInProgress,
"Only servers in a sharded cluster can start a new transaction at the active "
"transaction number",
serverGlobalParams.clusterRole != ClusterRole::None);
if (_isInternalSessionForRetryableWrite() &&
o().txnState.isInSet(TransactionState::kCommitted)) {
// This is a retry of a committed internal transaction for retryable writes so
// skip resetting the state and updating the metrics.
return;
}
_uassertCanReuseActiveTxnNumberForTransaction(opCtx);
} else {
const auto restartableStates = TransactionState::kNone | TransactionState::kInProgress |
TransactionState::kAbortedWithoutPrepare | TransactionState::kAbortedWithPrepare;
uassert(ErrorCodes::IllegalOperation,
str::stream() << "Cannot restart transaction "
<< txnNumberAndRetryCounter.getTxnNumber()
<< " using txnRetryCounter "
<< txnNumberAndRetryCounter.getTxnRetryCounter()
<< " because it is already in state " << o().txnState
<< " with txnRetryCounter "
<< o().activeTxnNumberAndRetryCounter.getTxnRetryCounter(),
o().txnState.isInSet(restartableStates));
}
} else {
invariant(txnNumberAndRetryCounter.getTxnNumber() >
o().activeTxnNumberAndRetryCounter.getTxnNumber());
}
// Aborts any in-progress txns.
_setNewTxnNumberAndRetryCounter(opCtx, txnNumberAndRetryCounter);
p().autoCommit = false;
auto& retryableWriteTxnParticipantCatalog =
getRetryableWriteTransactionParticipantCatalog(opCtx);
if (_isInternalSessionForRetryableWrite()) {
retryableWriteTxnParticipantCatalog.addParticipant(*this);
} else if (!_isInternalSessionForNonRetryableWrite()) {
// Don't reset the RetryableWriteTransactionParticipantCatalog upon starting an internal
// transaction for a non-retryable write since the transaction is unrelated to the
// retryable write or transaction in the original session that the write runs in. In
// addition, it is incorrect to clear the transaction history in the original session since
// the history should be kept until there is a retryable write or transaction with a higher
// txnNumber.
retryableWriteTxnParticipantCatalog.reset();
}
{
stdx::lock_guard<Client> lk(*opCtx->getClient());
o(lk).txnState.transitionTo(TransactionState::kInProgress);
// Start tracking various transactions metrics.
//
// We measure the start time in both microsecond and millisecond resolution. The TickSource
// provides microsecond resolution to record the duration of the transaction. The start
// "wall clock" time can be considered an approximation to the microsecond measurement.
auto now = opCtx->getServiceContext()->getPreciseClockSource()->now();
auto tickSource = opCtx->getServiceContext()->getTickSource();
o(lk).transactionExpireDate = now + Seconds(gTransactionLifetimeLimitSeconds.load());
o(lk).transactionMetricsObserver.onStart(
ServerTransactionsMetrics::get(opCtx->getServiceContext()),
*p().autoCommit,
tickSource,
now,
*o().transactionExpireDate);
invariant(p().transactionOperations.empty());
}
// TODO: (SERVER-62375): Remove upgrade/downgrade code for internal transactions
if (_isInternalSession() && opCtx->writesAreReplicated()) {
// Don't check the FCV and feature flag when starting an internal transaction on secondaries
// since they must apply transaction oplog entries replicated from the primary whether or
// not there have been changes to the FCV or feature flag.
uassert(ErrorCodes::InternalTransactionNotSupported,
"Internal transactions are not enabled",
feature_flags::gFeatureFlagInternalTransactions.isEnabled(
serverGlobalParams.featureCompatibility));
hangAfterCheckingInternalTransactionsFeatureFlag.pauseWhileSet(opCtx);
}
if (auto txnRetryCounter = txnNumberAndRetryCounter.getTxnRetryCounter();
txnRetryCounter && !isDefaultTxnRetryCounter(*txnRetryCounter)) {
uassert(ErrorCodes::TxnRetryCounterNotSupported,
"TxnRetryCounter support is not enabled",
feature_flags::gFeatureFlagInternalTransactions.isEnabled(
serverGlobalParams.featureCompatibility));
}
}
void TransactionParticipant::Participant::beginOrContinue(
OperationContext* opCtx,
TxnNumberAndRetryCounter txnNumberAndRetryCounter,
boost::optional<bool> autocommit,
boost::optional<bool> startTransaction) {
if (_isInternalSessionForRetryableWrite()) {
auto parentTxnParticipant =
TransactionParticipant::get(opCtx, _session()->getParentSession());
parentTxnParticipant.beginOrContinue(
opCtx, {*_sessionId().getTxnNumber(), boost::none}, boost::none, boost::none);
}
// Make sure we are still a primary. We need to hold on to the RSTL through the end of this
// method, as we otherwise risk stepping down in the interim and incorrectly updating the
// transaction number, which can abort active transactions.
repl::ReplicationStateTransitionLockGuard rstl(opCtx, MODE_IX);
if (opCtx->writesAreReplicated()) {
auto replCoord = repl::ReplicationCoordinator::get(opCtx);
uassert(ErrorCodes::NotWritablePrimary,
"Not primary so we cannot begin or continue a transaction",
replCoord->canAcceptWritesForDatabase(opCtx, "admin"));
// Disallow multi-statement transactions on shard servers that have
// writeConcernMajorityJournalDefault=false unless enableTestCommands=true. But allow
// retryable writes (autocommit == boost::none).
uassert(ErrorCodes::OperationNotSupportedInTransaction,
"Transactions are not allowed on shard servers when "
"writeConcernMajorityJournalDefault=false",
replCoord->getWriteConcernMajorityShouldJournal() ||
serverGlobalParams.clusterRole != ClusterRole::ShardServer || !autocommit ||
getTestCommandsEnabled());
}
if (txnNumberAndRetryCounter.getTxnNumber() <
o().activeTxnNumberAndRetryCounter.getTxnNumber()) {
const std::string currOperation =
o().txnState.isInRetryableWriteMode() ? "retryable write" : "transaction";
if (!autocommit) {
uasserted(ErrorCodes::TransactionTooOld,
str::stream()
<< "Retryable write with txnNumber "
<< txnNumberAndRetryCounter.getTxnNumber() << " is prohibited on session "
<< _sessionId() << " because a newer " << currOperation
<< " with txnNumber " << o().activeTxnNumberAndRetryCounter.getTxnNumber()
<< " has already started on this session.");
} else {
uasserted(ErrorCodes::TransactionTooOld,
str::stream()
<< "Cannot start transaction with " << txnNumberAndRetryCounter.toBSON()
<< " on session " << _sessionId() << " because a newer " << currOperation
<< " with txnNumberAndRetryCounter "
<< o().activeTxnNumberAndRetryCounter.toBSON()
<< " has already started on this session.");
}
}
// Requests without an autocommit field are interpreted as retryable writes. They cannot specify
// startTransaction, which is verified earlier when parsing the request.
if (!autocommit) {
invariant(!startTransaction);
invariant(!txnNumberAndRetryCounter.getTxnRetryCounter(),
"Cannot specify a txnRetryCounter for retryable write");
_beginOrContinueRetryableWrite(opCtx, txnNumberAndRetryCounter);
return;
}
// Attempt to continue a multi-statement transaction. In this case, it is required that
// autocommit be given as an argument on the request, and currently it can only be false, which
// is verified earlier when parsing the request.
invariant(*autocommit == false);
invariant(opCtx->inMultiDocumentTransaction());
if (txnNumberAndRetryCounter.getTxnRetryCounter()) {
uassert(ErrorCodes::InvalidOptions,
"txnRetryCounter is only supported in sharded clusters",
serverGlobalParams.clusterRole != ClusterRole::None);
invariant(*txnNumberAndRetryCounter.getTxnRetryCounter() >= 0,
"Cannot specify a negative txnRetryCounter");