/
transaction_participant.cpp
2110 lines (1796 loc) · 94.6 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 MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kStorage
#define LOG_FOR_TRANSACTION(level) \
MONGO_LOG_COMPONENT(level, ::mongo::logger::LogComponent::kTransaction)
#include "mongo/platform/basic.h"
#include "mongo/db/transaction_participant.h"
#include "mongo/db/catalog/database_holder.h"
#include "mongo/db/catalog/index_catalog.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/lock_state.h"
#include "mongo/db/concurrency/locker.h"
#include "mongo/db/concurrency/replication_state_transition_lock_guard.h"
#include "mongo/db/concurrency/write_conflict_exception.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/op_observer.h"
#include "mongo/db/ops/update.h"
#include "mongo/db/query/get_executor.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/server_recovery.h"
#include "mongo/db/server_transactions_metrics.h"
#include "mongo/db/session.h"
#include "mongo/db/session_catalog.h"
#include "mongo/db/stats/fill_locker_info.h"
#include "mongo/db/transaction_history_iterator.h"
#include "mongo/db/transaction_participant_gen.h"
#include "mongo/util/fail_point_service.h"
#include "mongo/util/log.h"
#include "mongo/util/net/socket_utils.h"
namespace mongo {
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);
const auto getTransactionParticipant = Session::declareDecoration<TransactionParticipant>();
// The command names that are allowed in a prepared transaction.
const StringMap<int> preparedTxnCmdWhitelist = {
{"abortTransaction", 1}, {"commitTransaction", 1}, {"prepareTransaction", 1}};
void fassertOnRepeatedExecution(const LogicalSessionId& lsid,
TxnNumber txnNumber,
StmtId stmtId,
const repl::OpTime& firstOpTime,
const repl::OpTime& secondOpTime) {
severe() << "Statement id " << stmtId << " from transaction [ " << lsid.toBSON() << ":"
<< txnNumber << " ] was committed once with opTime " << firstOpTime
<< " and a second time with opTime " << secondOpTime
<< ". This indicates possible data corruption or server bug and the process will be "
"terminated.";
fassertFailed(40526);
}
struct ActiveTransactionHistory {
boost::optional<SessionTxnRecord> lastTxnRecord;
TransactionParticipant::CommittedStatementTimestampMap committedStatements;
enum TxnRecordState { kNone, kCommitted, kAbortedWithPrepare, kPrepared };
TxnRecordState state = TxnRecordState::kNone;
bool hasIncompleteHistory{false};
};
ActiveTransactionHistory fetchActiveTransactionHistory(OperationContext* opCtx,
const LogicalSessionId& lsid) {
// Restore the current timestamp read source after fetching transaction history.
ReadSourceScope readSourceScope(opCtx);
ActiveTransactionHistory result;
result.lastTxnRecord = [&]() -> boost::optional<SessionTxnRecord> {
DBDirectClient client(opCtx);
auto result =
client.findOne(NamespaceString::kSessionTransactionsTableNamespace.ns(),
{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;
}
// State is a new field in FCV 4.2 that indicates if a transaction committed, so check it in FCV
// 4.2 and upgrading to 4.2. Check when downgrading as well so sessions refreshed at the start
// of downgrade enter the correct state.
if ((serverGlobalParams.featureCompatibility.getVersion() >=
ServerGlobalParams::FeatureCompatibility::Version::kDowngradingTo40)) {
// The state being kCommitted marks the commit of a transaction.
if (result.lastTxnRecord->getState() == DurableTxnStateEnum::kCommitted) {
result.state = result.TxnRecordState::kCommitted;
}
// The state being kAborted marks the abort of a prepared transaction since we do not write
// down abortTransaction oplog entries in 4.0.
if (result.lastTxnRecord->getState() == DurableTxnStateEnum::kAborted) {
result.state = result.TxnRecordState::kAbortedWithPrepare;
}
// The state being kPrepared marks a prepared transaction. We should never be refreshing
// a prepared transaction from storage since it should already be in a valid state after
// replication recovery.
invariant(result.lastTxnRecord->getState() != DurableTxnStateEnum::kPrepared);
}
auto it = TransactionHistoryIterator(result.lastTxnRecord->getLastWriteOpTime());
while (it.hasNext()) {
try {
const auto entry = it.next(opCtx);
invariant(entry.getStatementId());
if (*entry.getStatementId() == kIncompleteHistoryStmtId) {
// Only the dead end sentinel can have this id for oplog write history
invariant(entry.getObject2());
invariant(entry.getObject2()->woCompare(TransactionParticipant::kDeadEndSentinel) ==
0);
result.hasIncompleteHistory = true;
continue;
}
const auto insertRes =
result.committedStatements.emplace(*entry.getStatementId(), entry.getOpTime());
if (!insertRes.second) {
const auto& existingOpTime = insertRes.first->second;
fassertOnRepeatedExecution(lsid,
result.lastTxnRecord->getTxnNum(),
*entry.getStatementId(),
existingOpTime,
entry.getOpTime());
}
// State is a new field in FCV 4.2, so look for an applyOps oplog entry without a
// prepare flag to mark a committed transaction in FCV 4.0 or downgrading to 4.0. Check
// when upgrading as well so sessions refreshed at the beginning of upgrade enter the
// correct state.
if ((serverGlobalParams.featureCompatibility.getVersion() <=
ServerGlobalParams::FeatureCompatibility::Version::kUpgradingTo42) &&
(entry.getCommandType() == repl::OplogEntry::CommandType::kApplyOps &&
!entry.shouldPrepare())) {
result.state = result.TxnRecordState::kCommitted;
}
} catch (const DBException& ex) {
if (ex.code() == ErrorCodes::IncompleteTransactionHistory) {
result.hasIncompleteHistory = true;
break;
}
throw;
}
}
return result;
}
void updateSessionEntry(OperationContext* opCtx, const UpdateRequest& updateRequest) {
// Current code only supports replacement update.
dassert(UpdateDriver::isDocReplacement(updateRequest.getUpdates()));
AutoGetCollection autoColl(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.",
autoColl.getCollection());
WriteUnitOfWork wuow(opCtx);
auto collection = autoColl.getCollection();
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();
// 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, toUpdateIdDoc);
auto startingSnapshotId = opCtx->recoveryUnit()->getSnapshotId();
if (recordId.isNull()) {
// Upsert case.
auto status = collection->insertDocument(
opCtx, InsertStatement(updateRequest.getUpdates()), nullptr, false);
if (status == ErrorCodes::DuplicateKey) {
throw WriteConflictException();
}
uassertStatusOK(status);
wuow.commit();
return;
}
auto originalRecordData = collection->getRecordStore()->dataFor(opCtx, recordId);
auto originalDoc = originalRecordData.toBson();
invariant(collection->getDefaultCollator() == nullptr);
boost::intrusive_ptr<ExpressionContext> expCtx(new ExpressionContext(opCtx, nullptr));
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.
throw WriteConflictException();
}
CollectionUpdateArgs args;
args.update = updateRequest.getUpdates();
args.criteria = toUpdateIdDoc;
args.fromMigrate = false;
collection->updateDocument(opCtx,
recordId,
Snapshotted<BSONObj>(startingSnapshotId, originalDoc),
updateRequest.getUpdates(),
false, // indexesAffected = false because _id is the only index
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::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(const SessionToKill& session)
: Observer(&getTransactionParticipant(session.get())) {}
void TransactionParticipant::performNoopWrite(OperationContext* opCtx, StringData msg) {
repl::ReplicationCoordinator* replCoord =
repl::ReplicationCoordinator::get(opCtx->getClient()->getServiceContext());
// 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 resafe 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());
{
Lock::DBLock dbLock(opCtx, "local", MODE_IX);
Lock::CollectionLock collectionLock(opCtx->lockState(), "local.oplog.rs", MODE_IX);
uassert(ErrorCodes::NotMaster,
"Not primary when performing noop write for NoSuchTransaction error",
replCoord->canAcceptWritesForDatabase(opCtx, "admin"));
writeConflictRetry(opCtx, "performNoopWrite", "local.rs.oplog", [&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);
Lock::DBLock dbLock(opCtx.get(), nss.db(), MODE_IS, deadline);
Lock::CollectionLock collLock(opCtx.get()->lockState(), nss.toString(), MODE_IS, deadline);
auto databaseHolder = DatabaseHolder::get(opCtx.get());
auto db = databaseHolder->getDb(opCtx.get(), nss.db());
if (!db) {
// There is no config database, so there cannot be any active transactions.
return boost::none;
}
auto collection = db->getCollection(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) {
continue;
}
// A prepared transaction must have a start timestamp.
// TODO(SERVER-40013): Handle entries with state "prepared" and no "startTimestamp".
invariant(txnRecord.getStartOpTime());
auto ts = txnRecord.getStartOpTime()->getTimestamp();
if (!oldestTxnTimestamp || ts < oldestTxnTimestamp.value()) {
oldestTxnTimestamp = ts;
}
}
return oldestTxnTimestamp;
} catch (const DBException&) {
return exceptionToStatus();
}
}
const LogicalSessionId& TransactionParticipant::Observer::_sessionId() const {
const auto* owningSession = getTransactionParticipant.owner(_tp);
return owningSession->getSessionId();
}
void TransactionParticipant::Participant::_beginOrContinueRetryableWrite(OperationContext* opCtx,
TxnNumber txnNumber) {
if (txnNumber > o().activeTxnNumber) {
// New retryable write.
_setNewTxnNumber(opCtx, txnNumber);
p().autoCommit = boost::none;
} else {
// Retrying a retryable write.
uassert(ErrorCodes::InvalidOptions,
"Must specify autocommit=false on all operations of a multi-statement transaction.",
o().txnState.isNone());
invariant(p().autoCommit == boost::none);
}
}
void TransactionParticipant::Participant::_continueMultiDocumentTransaction(OperationContext* opCtx,
TxnNumber txnNumber) {
uassert(ErrorCodes::NoSuchTransaction,
str::stream()
<< "Given transaction number "
<< txnNumber
<< " does not match any in-progress transactions. The active transaction number is "
<< o().activeTxnNumber,
txnNumber == o().activeTxnNumber && !o().txnState.isNone());
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 "
<< txnNumber
<< " has been aborted because an earlier command in this transaction failed.");
}
return;
}
void TransactionParticipant::Participant::_beginMultiDocumentTransaction(OperationContext* opCtx,
TxnNumber txnNumber) {
// Aborts any in-progress txns.
_setNewTxnNumber(opCtx, txnNumber);
p().autoCommit = false;
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());
}
void TransactionParticipant::Participant::beginOrContinue(OperationContext* opCtx,
TxnNumber txnNumber,
boost::optional<bool> autocommit,
boost::optional<bool> startTransaction) {
// 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::NotMaster,
"Not primary so we cannot begin or continue a transaction",
replCoord->canAcceptWritesForDatabase(opCtx, "admin"));
}
uassert(ErrorCodes::TransactionTooOld,
str::stream() << "Cannot start transaction " << txnNumber << " on session "
<< _sessionId()
<< " because a newer transaction "
<< o().activeTxnNumber
<< " has already started.",
txnNumber >= o().activeTxnNumber);
// 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);
_beginOrContinueRetryableWrite(opCtx, txnNumber);
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);
if (!startTransaction) {
_continueMultiDocumentTransaction(opCtx, txnNumber);
return;
}
// Attempt to start a multi-statement transaction, which requires startTransaction be given as
// an argument on the request. The 'startTransaction' argument currently can only be specified
// as true, which is verified earlier, when parsing the request.
invariant(*startTransaction);
if (txnNumber == o().activeTxnNumber) {
// 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);
// The active transaction number can only be reused if the transaction is aborted and has
// not been involved in a two phase commit. Assuming routers target primaries in increasing
// order of term and in the absence of byzantine messages, this check should never fail.
const auto restartableStates = TransactionState::kAbortedWithoutPrepare;
uassert(50911,
str::stream() << "Cannot start a transaction at given transaction number "
<< txnNumber
<< " a transaction with the same number is in state "
<< o().txnState.toString(),
o().txnState.isInSet(restartableStates));
}
_beginMultiDocumentTransaction(opCtx, txnNumber);
}
void TransactionParticipant::Participant::beginOrContinueTransactionUnconditionally(
OperationContext* opCtx, TxnNumber txnNumber) {
// We don't check or fetch any on-disk state, so treat the transaction as 'valid' for the
// purposes of this method and continue the transaction unconditionally
p().isValid = true;
if (o().activeTxnNumber != txnNumber) {
_beginMultiDocumentTransaction(opCtx, txnNumber);
}
}
void TransactionParticipant::Participant::_setSpeculativeTransactionOpTime(
OperationContext* opCtx, SpeculativeTransactionOpTime opTimeChoice) {
repl::ReplicationCoordinator* replCoord =
repl::ReplicationCoordinator::get(opCtx->getServiceContext());
boost::optional<Timestamp> readTimestamp;
if (opTimeChoice == SpeculativeTransactionOpTime::kAllCommitted) {
opCtx->recoveryUnit()->setTimestampReadSource(
RecoveryUnit::ReadSource::kAllCommittedSnapshot);
readTimestamp = repl::StorageInterface::get(opCtx)->getPointInTimeReadTimestamp(opCtx);
// Transactions do not survive term changes, so combining "getTerm" here with the
// recovery unit timestamp does not cause races.
p().speculativeTransactionReadOpTime = {*readTimestamp, replCoord->getTerm()};
stdx::lock_guard<Client> lk(*opCtx->getClient());
o(lk).transactionMetricsObserver.onChooseReadTimestamp(*readTimestamp);
} else {
opCtx->recoveryUnit()->setTimestampReadSource(RecoveryUnit::ReadSource::kNoTimestamp);
}
opCtx->recoveryUnit()->preallocateSnapshot();
}
void TransactionParticipant::Participant::_setSpeculativeTransactionReadTimestamp(
OperationContext* opCtx, Timestamp timestamp) {
// Read concern code should have already set the timestamp on the recovery unit.
invariant(timestamp == opCtx->recoveryUnit()->getPointInTimeReadTimestamp());
repl::ReplicationCoordinator* replCoord =
repl::ReplicationCoordinator::get(opCtx->getClient()->getServiceContext());
opCtx->recoveryUnit()->preallocateSnapshot();
p().speculativeTransactionReadOpTime = {timestamp, replCoord->getTerm()};
stdx::lock_guard<Client> lk(*opCtx->getClient());
o(lk).transactionMetricsObserver.onChooseReadTimestamp(timestamp);
}
TransactionParticipant::OplogSlotReserver::OplogSlotReserver(OperationContext* opCtx,
int numSlotsToReserve)
: _opCtx(opCtx) {
// Stash the transaction on the OperationContext on the stack. At the end of this function it
// will be unstashed onto the OperationContext.
TransactionParticipant::SideTransactionBlock sideTxn(opCtx);
// Begin a new WUOW and reserve a slot in the oplog.
WriteUnitOfWork wuow(opCtx);
_oplogSlots = repl::getNextOpTimes(opCtx, numSlotsToReserve);
// Release the WUOW state since this WUOW is no longer in use.
wuow.release();
// We must lock the Client to change the Locker on the OperationContext.
stdx::lock_guard<Client> lk(*opCtx->getClient());
// The new transaction should have an empty locker, and thus we do not need to save it.
invariant(opCtx->lockState()->getClientState() == Locker::ClientState::kInactive);
_locker = opCtx->swapLockState(stdx::make_unique<LockerImpl>());
// Inherit the locking setting from the original one.
opCtx->lockState()->setShouldConflictWithSecondaryBatchApplication(
_locker->shouldConflictWithSecondaryBatchApplication());
_locker->unsetThreadId();
if (opCtx->getLogicalSessionId()) {
_locker->setDebugInfo("lsid: " + opCtx->getLogicalSessionId()->toBSON().toString());
}
// OplogSlotReserver is only used by primary, so always set max transaction lock timeout.
invariant(opCtx->writesAreReplicated());
// This thread must still respect the transaction lock timeout, since it can prevent the
// transaction from making progress.
auto maxTransactionLockMillis = gMaxTransactionLockRequestTimeoutMillis.load();
if (maxTransactionLockMillis >= 0) {
opCtx->lockState()->setMaxLockTimeout(Milliseconds(maxTransactionLockMillis));
}
// Save the RecoveryUnit from the new transaction and replace it with an empty one.
_recoveryUnit = opCtx->releaseRecoveryUnit();
opCtx->setRecoveryUnit(std::unique_ptr<RecoveryUnit>(
opCtx->getServiceContext()->getStorageEngine()->newRecoveryUnit()),
WriteUnitOfWork::RecoveryUnitState::kNotInUnitOfWork);
}
TransactionParticipant::OplogSlotReserver::~OplogSlotReserver() {
if (MONGO_FAIL_POINT(hangBeforeReleasingTransactionOplogHole)) {
log()
<< "transaction - hangBeforeReleasingTransactionOplogHole fail point enabled. Blocking "
"until fail point is disabled.";
MONGO_FAIL_POINT_PAUSE_WHILE_SET(hangBeforeReleasingTransactionOplogHole);
}
// If the constructor did not complete, we do not attempt to abort the units of work.
if (_recoveryUnit) {
// We should be at WUOW nesting level 1, only the top level WUOW for the oplog reservation
// side transaction.
_recoveryUnit->abortUnitOfWork();
_locker->endWriteUnitOfWork();
invariant(!_locker->inAWriteUnitOfWork());
}
// After releasing the oplog hole, the "all committed timestamp" can advance past
// this oplog hole, if there are no other open holes. Check if we can advance the stable
// timestamp any further since a majority write may be waiting on the stable timestamp to
// advance beyond this oplog hole to acknowledge the write to the user.
auto replCoord = repl::ReplicationCoordinator::get(_opCtx);
replCoord->attemptToAdvanceStableTimestamp();
}
TransactionParticipant::TxnResources::TxnResources(WithLock wl,
OperationContext* opCtx,
StashStyle stashStyle) noexcept {
// We must hold the Client lock to change the Locker on the OperationContext. Hence the
// WithLock.
_ruState = opCtx->getWriteUnitOfWork()->release();
opCtx->setWriteUnitOfWork(nullptr);
_locker = opCtx->swapLockState(stdx::make_unique<LockerImpl>());
// Inherit the locking setting from the original one.
opCtx->lockState()->setShouldConflictWithSecondaryBatchApplication(
_locker->shouldConflictWithSecondaryBatchApplication());
if (stashStyle != StashStyle::kSideTransaction) {
_locker->releaseTicket();
}
_locker->unsetThreadId();
if (opCtx->getLogicalSessionId()) {
_locker->setDebugInfo("lsid: " + opCtx->getLogicalSessionId()->toBSON().toString());
}
// On secondaries, we yield the locks for transactions.
if (stashStyle == StashStyle::kSecondary) {
_lockSnapshot = std::make_unique<Locker::LockSnapshot>();
_locker->releaseWriteUnitOfWork(_lockSnapshot.get());
}
// This thread must still respect the transaction lock timeout, since it can prevent the
// transaction from making progress.
auto maxTransactionLockMillis = gMaxTransactionLockRequestTimeoutMillis.load();
if (stashStyle != StashStyle::kSecondary && maxTransactionLockMillis >= 0) {
opCtx->lockState()->setMaxLockTimeout(Milliseconds(maxTransactionLockMillis));
}
// On secondaries, max lock timeout must not be set.
invariant(stashStyle != StashStyle::kSecondary || !opCtx->lockState()->hasMaxLockTimeout());
_recoveryUnit = opCtx->releaseRecoveryUnit();
opCtx->setRecoveryUnit(std::unique_ptr<RecoveryUnit>(
opCtx->getServiceContext()->getStorageEngine()->newRecoveryUnit()),
WriteUnitOfWork::RecoveryUnitState::kNotInUnitOfWork);
_readConcernArgs = repl::ReadConcernArgs::get(opCtx);
}
TransactionParticipant::TxnResources::~TxnResources() {
if (!_released && _recoveryUnit) {
// This should only be reached when aborting a transaction that isn't active, i.e.
// when starting a new transaction before completing an old one. So we should
// be at WUOW nesting level 1 (only the top level WriteUnitOfWork).
_recoveryUnit->abortUnitOfWork();
// If locks are not yielded, release them.
if (!_lockSnapshot) {
_locker->endWriteUnitOfWork();
}
invariant(!_locker->inAWriteUnitOfWork());
}
}
void TransactionParticipant::TxnResources::release(OperationContext* opCtx) {
// Perform operations that can fail the release before marking the TxnResources as released.
// Restore locks if they are yielded.
if (_lockSnapshot) {
invariant(!_locker->isLocked());
// opCtx is passed in to enable the restoration to be interrupted.
_locker->restoreWriteUnitOfWork(opCtx, *_lockSnapshot);
_lockSnapshot.reset(nullptr);
}
_locker->reacquireTicket(opCtx);
invariant(!_released);
_released = true;
// It is necessary to lock the client to change the Locker on the OperationContext.
stdx::lock_guard<Client> lk(*opCtx->getClient());
invariant(opCtx->lockState()->getClientState() == Locker::ClientState::kInactive);
// We intentionally do not capture the return value of swapLockState(), which is just an empty
// locker. At the end of the operation, if the transaction is not complete, we will stash the
// operation context's locker and replace it with a new empty locker.
opCtx->swapLockState(std::move(_locker));
opCtx->lockState()->updateThreadIdToCurrentThread();
auto oldState = opCtx->setRecoveryUnit(std::move(_recoveryUnit),
WriteUnitOfWork::RecoveryUnitState::kNotInUnitOfWork);
invariant(oldState == WriteUnitOfWork::RecoveryUnitState::kNotInUnitOfWork,
str::stream() << "RecoveryUnit state was " << oldState);
opCtx->setWriteUnitOfWork(WriteUnitOfWork::createForSnapshotResume(opCtx, _ruState));
auto& readConcernArgs = repl::ReadConcernArgs::get(opCtx);
readConcernArgs = _readConcernArgs;
}
TransactionParticipant::SideTransactionBlock::SideTransactionBlock(OperationContext* opCtx)
: _opCtx(opCtx) {
if (_opCtx->getWriteUnitOfWork()) {
stdx::lock_guard<Client> lk(*_opCtx->getClient());
_txnResources = TransactionParticipant::TxnResources(
lk, _opCtx, TxnResources::StashStyle::kSideTransaction);
}
}
TransactionParticipant::SideTransactionBlock::~SideTransactionBlock() {
if (_txnResources) {
_txnResources->release(_opCtx);
}
}
void TransactionParticipant::Participant::_stashActiveTransaction(OperationContext* opCtx) {
if (p().inShutdown) {
return;
}
invariant(o().activeTxnNumber == opCtx->getTxnNumber());
stdx::lock_guard<Client> lk(*opCtx->getClient());
{
auto tickSource = opCtx->getServiceContext()->getTickSource();
o(lk).transactionMetricsObserver.onStash(ServerTransactionsMetrics::get(opCtx), tickSource);
o(lk).transactionMetricsObserver.onTransactionOperation(
opCtx, CurOp::get(opCtx)->debug().additiveMetrics, o().txnState.isPrepared());
}
invariant(!o().txnResourceStash);
auto stashStyle = opCtx->writesAreReplicated() ? TxnResources::StashStyle::kPrimary
: TxnResources::StashStyle::kSecondary;
o(lk).txnResourceStash = TxnResources(lk, opCtx, stashStyle);
}
void TransactionParticipant::Participant::stashTransactionResources(OperationContext* opCtx) {
if (opCtx->getClient()->isInDirectClient()) {
return;
}
invariant(opCtx->getTxnNumber());
if (o().txnState.inMultiDocumentTransaction()) {
_stashActiveTransaction(opCtx);
}
}
void TransactionParticipant::Participant::_releaseTransactionResourcesToOpCtx(
OperationContext* opCtx) {
// Transaction resources already exist for this transaction. Transfer them from the
// stash to the operation context.
//
// Because TxnResources::release must acquire the Client lock midway through, and because we
// must hold the Client clock to mutate txnResourceStash, we jump through some hoops here to
// move the TxnResources in txnResourceStash into a local variable that can be manipulated
// without holding the Client lock.
[&]() noexcept {
using std::swap;
boost::optional<TxnResources> trs;
stdx::lock_guard<Client> lk(*opCtx->getClient());
swap(trs, o(lk).txnResourceStash);
return std::move(*trs);
}
().release(opCtx);
}
void TransactionParticipant::Participant::unstashTransactionResources(OperationContext* opCtx,
const std::string& cmdName) {
invariant(!opCtx->getClient()->isInDirectClient());
invariant(opCtx->getTxnNumber());
// If this is not a multi-document transaction, there is nothing to unstash.
if (o().txnState.isNone()) {
invariant(!o().txnResourceStash);
return;
}
_checkIsCommandValidWithTxnState(*opCtx->getTxnNumber(), cmdName);
if (o().txnResourceStash) {
_releaseTransactionResourcesToOpCtx(opCtx);
stdx::lock_guard<Client> lg(*opCtx->getClient());
o(lg).transactionMetricsObserver.onUnstash(ServerTransactionsMetrics::get(opCtx),
opCtx->getServiceContext()->getTickSource());
return;
}
// If we have no transaction resources then we cannot be prepared. If we're not in progress,
// we don't do anything else.
invariant(!o().txnState.isPrepared());
if (!o().txnState.isInProgress()) {
// At this point we're either committed and this is a 'commitTransaction' command, or we
// are in the process of committing.
return;
}
// All locks of transactions must be acquired inside the global WUOW so that we can
// yield and restore all locks on state transition. Otherwise, we'd have to remember
// which locks are managed by WUOW.
invariant(!opCtx->lockState()->isLocked());
// Stashed transaction resources do not exist for this in-progress multi-document
// transaction. Set up the transaction resources on the opCtx.
opCtx->setWriteUnitOfWork(std::make_unique<WriteUnitOfWork>(opCtx));
// If maxTransactionLockRequestTimeoutMillis is set, then we will ensure no
// future lock request waits longer than maxTransactionLockRequestTimeoutMillis
// to acquire a lock. This is to avoid deadlocks and minimize non-transaction
// operation performance degradations.
auto maxTransactionLockMillis = gMaxTransactionLockRequestTimeoutMillis.load();
if (opCtx->writesAreReplicated() && maxTransactionLockMillis >= 0) {
opCtx->lockState()->setMaxLockTimeout(Milliseconds(maxTransactionLockMillis));
}
// On secondaries, max lock timeout must not be set.
invariant(opCtx->writesAreReplicated() || !opCtx->lockState()->hasMaxLockTimeout());
// Storage engine transactions may be started in a lazy manner. By explicitly
// starting here we ensure that a point-in-time snapshot is established during the
// first operation of a transaction.
//
// Active transactions are protected by the locking subsystem, so we must always hold at least a
// Global intent lock before starting a transaction. We pessimistically acquire an intent
// exclusive lock here because we might be doing writes in this transaction, and it is currently
// not deadlock-safe to upgrade IS to IX.
Lock::GlobalLock(opCtx, MODE_IX);
// Set speculative execution. This must be done after the global lock is acquired, because
// we need to check that we are primary.
const auto& readConcernArgs = repl::ReadConcernArgs::get(opCtx);
// TODO(SERVER-38203): We cannot wait for write concern on secondaries, so we do not set the
// speculative optime on secondaries either. This means that reads done in transactions on
// secondaries will not wait for the read snapshot to become majority-committed.
repl::ReplicationCoordinator* replCoord =
repl::ReplicationCoordinator::get(opCtx->getServiceContext());
if (replCoord->canAcceptWritesForDatabase(
opCtx, NamespaceString::kSessionTransactionsTableNamespace.db())) {
if (readConcernArgs.getArgsAtClusterTime()) {
_setSpeculativeTransactionReadTimestamp(
opCtx, readConcernArgs.getArgsAtClusterTime()->asTimestamp());
} else {
_setSpeculativeTransactionOpTime(opCtx,
readConcernArgs.getOriginalLevel() ==
repl::ReadConcernLevel::kSnapshotReadConcern
? SpeculativeTransactionOpTime::kAllCommitted
: SpeculativeTransactionOpTime::kNoTimestamp);
}
} else {
opCtx->recoveryUnit()->preallocateSnapshot();
}
// The Client lock must not be held when executing this failpoint as it will block currentOp
// execution.
if (MONGO_FAIL_POINT(hangAfterPreallocateSnapshot)) {
CurOpFailpointHelpers::waitWhileFailPointEnabled(
&hangAfterPreallocateSnapshot, opCtx, "hangAfterPreallocateSnapshot");
}
{
stdx::lock_guard<Client> lg(*opCtx->getClient());
o(lg).transactionMetricsObserver.onUnstash(ServerTransactionsMetrics::get(opCtx),
opCtx->getServiceContext()->getTickSource());
}
}
void TransactionParticipant::Participant::refreshLocksForPreparedTransaction(
OperationContext* opCtx, bool yieldLocks) {
// The opCtx will be used to swap locks, so it cannot hold any lock.
invariant(!opCtx->lockState()->isRSTLLocked());
invariant(!opCtx->lockState()->isLocked());
// The node must have txn resource.
invariant(o().txnResourceStash);
invariant(o().txnState.isPrepared());
_releaseTransactionResourcesToOpCtx(opCtx);
// Snapshot transactions don't conflict with PBWM lock on both primary and secondary.
invariant(!opCtx->lockState()->shouldConflictWithSecondaryBatchApplication());
// Transfer the txn resource back from the operation context to the stash.
auto stashStyle =
yieldLocks ? TxnResources::StashStyle::kSecondary : TxnResources::StashStyle::kPrimary;
stdx::lock_guard<Client> lk(*opCtx->getClient());
o(lk).txnResourceStash = TxnResources(lk, opCtx, stashStyle);
}
Timestamp TransactionParticipant::Participant::prepareTransaction(
OperationContext* opCtx, boost::optional<repl::OpTime> prepareOptime) {
auto abortGuard = makeGuard([&] {
// Prepare transaction on secondaries should always succeed.
invariant(!prepareOptime);
try {
// This shouldn't cause deadlocks with other prepared txns, because the acquisition
// of RSTL lock inside abortActiveTransaction will be no-op since we already have it.
// This abortGuard gets dismissed before we release the RSTL while transitioning to
// prepared.
UninterruptibleLockGuard noInterrupt(opCtx->lockState());
abortActiveTransaction(opCtx);
} catch (...) {
// It is illegal for aborting a prepared transaction to fail for any reason, so we crash
// instead.
severe() << "Caught exception during abort of prepared transaction "
<< opCtx->getTxnNumber() << " on " << _sessionId().toBSON() << ": "
<< exceptionToStatus();
std::terminate();
}
});
boost::optional<OplogSlotReserver> oplogSlotReserver;
OplogSlot prepareOplogSlot;
{
stdx::lock_guard<Client> lk(*opCtx->getClient());
// This check is necessary in order to avoid a race where a session with an active (but not
// prepared) transaction is killed, but it still ends up in the prepared state
opCtx->checkForInterrupt();
o(lk).txnState.transitionTo(TransactionState::kPrepared);
}
std::vector<OplogSlot> reservedSlots;
if (prepareOptime) {
// On secondary, we just prepare the transaction and discard the buffered ops.
prepareOplogSlot = OplogSlot(*prepareOptime, 0);
stdx::lock_guard<Client> lk(*opCtx->getClient());
o(lk).prepareOpTime = *prepareOptime;
reservedSlots.push_back(prepareOplogSlot);
} else {
// On primary, we reserve an optime, prepare the transaction and write the oplog entry.
//
// Reserve an optime for the 'prepareTimestamp'. This will create a hole in the oplog and
// cause 'snapshot' and 'afterClusterTime' readers to block until this transaction is done
// being prepared. When the OplogSlotReserver goes out of scope and is destroyed, the
// storage-transaction it uses to keep the hole open will abort and the slot (and
// corresponding oplog hole) will vanish.
if (!gUseMultipleOplogEntryFormatForTransactions) {
oplogSlotReserver.emplace(opCtx);
} else {
const auto numSlotsToReserve = retrieveCompletedTransactionOperations(opCtx).size();
// Reserve an extra slot here for the prepare oplog entry.
oplogSlotReserver.emplace(opCtx, numSlotsToReserve + 1);
invariant(oplogSlotReserver->getSlots().size() >= 1);