/
tenant_migration_recipient_service.cpp
2491 lines (2205 loc) · 121 KB
/
tenant_migration_recipient_service.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) 2020-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_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kTenantMigration
#include "mongo/platform/basic.h"
#include "mongo/base/checked_cast.h"
#include "mongo/client/dbclient_connection.h"
#include "mongo/client/replica_set_monitor.h"
#include "mongo/client/replica_set_monitor_manager.h"
#include "mongo/config.h"
#include "mongo/db/client.h"
#include "mongo/db/commands/test_commands_enabled.h"
#include "mongo/db/concurrency/write_conflict_exception.h"
#include "mongo/db/db_raii.h"
#include "mongo/db/dbdirectclient.h"
#include "mongo/db/namespace_string.h"
#include "mongo/db/op_observer.h"
#include "mongo/db/pipeline/process_interface/mongo_process_interface.h"
#include "mongo/db/repl/cloner_utils.h"
#include "mongo/db/repl/data_replicator_external_state.h"
#include "mongo/db/repl/oplog_applier.h"
#include "mongo/db/repl/oplog_buffer_collection.h"
#include "mongo/db/repl/oplog_entry.h"
#include "mongo/db/repl/oplog_interface_local.h"
#include "mongo/db/repl/read_concern_args.h"
#include "mongo/db/repl/repl_client_info.h"
#include "mongo/db/repl/repl_server_parameters_gen.h"
#include "mongo/db/repl/replication_auth.h"
#include "mongo/db/repl/replication_coordinator.h"
#include "mongo/db/repl/tenant_migration_access_blocker_util.h"
#include "mongo/db/repl/tenant_migration_decoration.h"
#include "mongo/db/repl/tenant_migration_recipient_entry_helpers.h"
#include "mongo/db/repl/tenant_migration_recipient_service.h"
#include "mongo/db/repl/tenant_migration_state_machine_gen.h"
#include "mongo/db/repl/tenant_migration_statistics.h"
#include "mongo/db/repl/wait_for_majority_service.h"
#include "mongo/db/session_catalog_mongod.h"
#include "mongo/db/session_txn_record_gen.h"
#include "mongo/db/transaction_participant.h"
#include "mongo/db/vector_clock_mutable.h"
#include "mongo/db/write_concern_options.h"
#include "mongo/logv2/log.h"
#include "mongo/rpc/get_status_from_command_result.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/cancellation.h"
#include "mongo/util/future_util.h"
namespace mongo {
namespace repl {
namespace {
const std::string kTTLIndexName = "TenantMigrationRecipientTTLIndex";
const Backoff kExponentialBackoff(Seconds(1), Milliseconds::max());
constexpr StringData kOplogBufferPrefix = "repl.migration.oplog_"_sd;
NamespaceString getOplogBufferNs(const UUID& migrationUUID) {
return NamespaceString(NamespaceString::kConfigDb,
kOplogBufferPrefix + migrationUUID.toString());
}
boost::intrusive_ptr<ExpressionContext> makeExpressionContext(OperationContext* opCtx) {
StringMap<ExpressionContext::ResolvedNamespace> resolvedNamespaces;
// Add kTenantMigrationOplogView, kSessionTransactionsTableNamespace, and kRsOplogNamespace
// to resolvedNamespaces since they are all used during different pipeline stages.
resolvedNamespaces[NamespaceString::kTenantMigrationOplogView.coll()] = {
NamespaceString::kTenantMigrationOplogView, std::vector<BSONObj>()};
resolvedNamespaces[NamespaceString::kSessionTransactionsTableNamespace.coll()] = {
NamespaceString::kSessionTransactionsTableNamespace, std::vector<BSONObj>()};
resolvedNamespaces[NamespaceString::kRsOplogNamespace.coll()] = {
NamespaceString::kRsOplogNamespace, std::vector<BSONObj>()};
return make_intrusive<ExpressionContext>(opCtx,
boost::none, /* explain */
false, /* fromMongos */
false, /* needsMerge */
true, /* allowDiskUse */
true, /* bypassDocumentValidation */
false, /* isMapReduceCommand */
NamespaceString::kSessionTransactionsTableNamespace,
boost::none, /* runtimeConstants */
nullptr, /* collator */
MongoProcessInterface::create(opCtx),
std::move(resolvedNamespaces),
boost::none); /* collUUID */
}
// We allow retrying on the following oplog fetcher errors:
// 1) InvalidSyncSource - we cannot sync from the chosen sync source, potentially because the sync
// source is too stale or there was a network error when connecting to the sync source.
// 2) ShudownInProgress - the current sync source is shutting down
bool isRetriableOplogFetcherError(Status oplogFetcherStatus) {
return oplogFetcherStatus == ErrorCodes::InvalidSyncSource ||
oplogFetcherStatus == ErrorCodes::ShutdownInProgress;
}
} // namespace
// A convenient place to set test-specific parameters.
MONGO_FAIL_POINT_DEFINE(pauseBeforeRunTenantMigrationRecipientInstance);
MONGO_FAIL_POINT_DEFINE(pauseAfterRunTenantMigrationRecipientInstance);
MONGO_FAIL_POINT_DEFINE(skipTenantMigrationRecipientAuth);
MONGO_FAIL_POINT_DEFINE(skipComparingRecipientAndDonorFCV);
MONGO_FAIL_POINT_DEFINE(autoRecipientForgetMigration);
MONGO_FAIL_POINT_DEFINE(pauseAfterCreatingOplogBuffer);
MONGO_FAIL_POINT_DEFINE(skipFetchingCommittedTransactions);
MONGO_FAIL_POINT_DEFINE(skipFetchingRetryableWritesEntriesBeforeStartOpTime);
// Fails before waiting for the state doc to be majority replicated.
MONGO_FAIL_POINT_DEFINE(failWhilePersistingTenantMigrationRecipientInstanceStateDoc);
MONGO_FAIL_POINT_DEFINE(fpAfterPersistingTenantMigrationRecipientInstanceStateDoc);
MONGO_FAIL_POINT_DEFINE(fpBeforeFetchingDonorClusterTimeKeys);
MONGO_FAIL_POINT_DEFINE(fpAfterConnectingTenantMigrationRecipientInstance);
MONGO_FAIL_POINT_DEFINE(fpAfterRecordingRecipientPrimaryStartingFCV);
MONGO_FAIL_POINT_DEFINE(fpAfterComparingRecipientAndDonorFCV);
MONGO_FAIL_POINT_DEFINE(fpAfterRetrievingStartOpTimesMigrationRecipientInstance);
MONGO_FAIL_POINT_DEFINE(fpSetSmallAggregationBatchSize);
MONGO_FAIL_POINT_DEFINE(fpBeforeWaitingForRetryableWritePreFetchMajorityCommitted);
MONGO_FAIL_POINT_DEFINE(pauseAfterRetrievingRetryableWritesBatch);
MONGO_FAIL_POINT_DEFINE(fpAfterFetchingRetryableWritesEntriesBeforeStartOpTime);
MONGO_FAIL_POINT_DEFINE(fpAfterStartingOplogFetcherMigrationRecipientInstance);
MONGO_FAIL_POINT_DEFINE(setTenantMigrationRecipientInstanceHostTimeout);
MONGO_FAIL_POINT_DEFINE(pauseAfterRetrievingLastTxnMigrationRecipientInstance);
MONGO_FAIL_POINT_DEFINE(fpBeforeMarkingCollectionClonerDone);
MONGO_FAIL_POINT_DEFINE(fpAfterCollectionClonerDone);
MONGO_FAIL_POINT_DEFINE(fpAfterStartingOplogApplierMigrationRecipientInstance);
MONGO_FAIL_POINT_DEFINE(fpBeforeFulfillingDataConsistentPromise);
MONGO_FAIL_POINT_DEFINE(fpAfterDataConsistentMigrationRecipientInstance);
MONGO_FAIL_POINT_DEFINE(fpBeforePersistingRejectReadsBeforeTimestamp);
MONGO_FAIL_POINT_DEFINE(fpAfterWaitForRejectReadsBeforeTimestamp);
MONGO_FAIL_POINT_DEFINE(hangBeforeTaskCompletion);
MONGO_FAIL_POINT_DEFINE(fpAfterReceivingRecipientForgetMigration);
MONGO_FAIL_POINT_DEFINE(hangAfterCreatingRSM);
MONGO_FAIL_POINT_DEFINE(skipRetriesWhenConnectingToDonorHost);
MONGO_FAIL_POINT_DEFINE(fpBeforeDroppingOplogBufferCollection);
MONGO_FAIL_POINT_DEFINE(fpWaitUntilTimestampMajorityCommitted);
MONGO_FAIL_POINT_DEFINE(fpAfterFetchingCommittedTransactions);
MONGO_FAIL_POINT_DEFINE(hangAfterUpdatingTransactionEntry);
MONGO_FAIL_POINT_DEFINE(pauseAtStartOfTenantMigrationRecipientFutureChain);
MONGO_FAIL_POINT_DEFINE(pauseTenantMigrationAfterSettingWaitingForCloneStage);
MONGO_FAIL_POINT_DEFINE(pauseTenantMigrationRecipientBeforeForgetMigration);
MONGO_FAIL_POINT_DEFINE(pauseTenantMigrationRecipientBeforeLeavingFutureChain);
namespace {
// We never restart just the oplog fetcher. If a failure occurs, we restart the whole state machine
// and recover from there. So the restart decision is always "no".
class OplogFetcherRestartDecisionTenantMigration
: public OplogFetcher::OplogFetcherRestartDecision {
public:
~OplogFetcherRestartDecisionTenantMigration(){};
bool shouldContinue(OplogFetcher* fetcher, Status status) final {
return false;
}
void fetchSuccessful(OplogFetcher* fetcher) final {}
};
// The oplog fetcher requires some of the methods in DataReplicatorExternalState to operate.
class DataReplicatorExternalStateTenantMigration : public DataReplicatorExternalState {
public:
// The oplog fetcher is passed its executor directly and does not use the one from the
// DataReplicatorExternalState.
executor::TaskExecutor* getTaskExecutor() const final {
MONGO_UNREACHABLE;
}
std::shared_ptr<executor::TaskExecutor> getSharedTaskExecutor() const final {
MONGO_UNREACHABLE;
}
// The oplog fetcher uses the current term and opTime to inform the sync source of term changes.
// As the term on the donor and the term on the recipient have nothing to do with each other,
// we do not want to do that.
OpTimeWithTerm getCurrentTermAndLastCommittedOpTime() final {
return {OpTime::kUninitializedTerm, OpTime()};
}
// Tenant migration does not require the metadata from the oplog query.
void processMetadata(const rpc::ReplSetMetadata& replMetadata,
rpc::OplogQueryMetadata oqMetadata) final {}
// Tenant migration does not change sync source depending on metadata.
ChangeSyncSourceAction shouldStopFetching(const HostAndPort& source,
const rpc::ReplSetMetadata& replMetadata,
const rpc::OplogQueryMetadata& oqMetadata,
const OpTime& previousOpTimeFetched,
const OpTime& lastOpTimeFetched) final {
return ChangeSyncSourceAction::kContinueSyncing;
}
// The oplog fetcher should never call the rest of the methods.
std::unique_ptr<OplogBuffer> makeInitialSyncOplogBuffer(OperationContext* opCtx) const final {
MONGO_UNREACHABLE;
}
std::unique_ptr<OplogApplier> makeOplogApplier(
OplogBuffer* oplogBuffer,
OplogApplier::Observer* observer,
ReplicationConsistencyMarkers* consistencyMarkers,
StorageInterface* storageInterface,
const OplogApplier::Options& options,
ThreadPool* writerPool) final {
MONGO_UNREACHABLE;
};
virtual StatusWith<ReplSetConfig> getCurrentConfig() const final {
MONGO_UNREACHABLE;
}
};
} // namespace
TenantMigrationRecipientService::TenantMigrationRecipientService(
ServiceContext* const serviceContext)
: PrimaryOnlyService(serviceContext), _serviceContext(serviceContext) {}
StringData TenantMigrationRecipientService::getServiceName() const {
return kTenantMigrationRecipientServiceName;
}
NamespaceString TenantMigrationRecipientService::getStateDocumentsNS() const {
return NamespaceString::kTenantMigrationRecipientsNamespace;
}
ThreadPool::Limits TenantMigrationRecipientService::getThreadPoolLimits() const {
ThreadPool::Limits limits;
limits.maxThreads = maxTenantMigrationRecipientThreadPoolSize;
return limits;
}
void TenantMigrationRecipientService::abortAllMigrations(OperationContext* opCtx) {
LOGV2(5356303, "Aborting all tenant migrations on recipient");
auto instances = getAllInstances(opCtx);
for (auto& instance : instances) {
auto typedInstance =
checked_pointer_cast<TenantMigrationRecipientService::Instance>(instance);
typedInstance->cancelMigration();
}
}
ExecutorFuture<void> TenantMigrationRecipientService::_rebuildService(
std::shared_ptr<executor::ScopedTaskExecutor> executor, const CancellationToken& token) {
return AsyncTry([this] {
auto nss = getStateDocumentsNS();
AllowOpCtxWhenServiceRebuildingBlock allowOpCtxBlock(Client::getCurrent());
auto opCtxHolder = cc().makeOperationContext();
auto opCtx = opCtxHolder.get();
DBDirectClient client(opCtx);
BSONObj result;
client.runCommand(
nss.db().toString(),
BSON("createIndexes"
<< nss.coll().toString() << "indexes"
<< BSON_ARRAY(BSON("key" << BSON("expireAt" << 1) << "name" << kTTLIndexName
<< "expireAfterSeconds" << 0))),
result);
uassertStatusOK(getStatusFromCommandResult(result));
})
.until([token](Status status) { return status.isOK() || token.isCanceled(); })
.withBackoffBetweenIterations(kExponentialBackoff)
.on(**executor, CancellationToken::uncancelable());
}
std::shared_ptr<PrimaryOnlyService::Instance> TenantMigrationRecipientService::constructInstance(
BSONObj initialStateDoc) {
return std::make_shared<TenantMigrationRecipientService::Instance>(
_serviceContext, this, initialStateDoc);
}
TenantMigrationRecipientService::Instance::Instance(
ServiceContext* const serviceContext,
const TenantMigrationRecipientService* recipientService,
BSONObj stateDoc)
: PrimaryOnlyService::TypedInstance<Instance>(),
_serviceContext(serviceContext),
_recipientService(recipientService),
_stateDoc(TenantMigrationRecipientDocument::parse(IDLParserErrorContext("recipientStateDoc"),
stateDoc)),
_tenantId(_stateDoc.getTenantId().toString()),
_migrationUuid(_stateDoc.getId()),
_donorConnectionString(_stateDoc.getDonorConnectionString().toString()),
_donorUri(uassertStatusOK(MongoURI::parse(_stateDoc.getDonorConnectionString().toString()))),
_readPreference(_stateDoc.getReadPreference()),
_recipientCertificateForDonor(_stateDoc.getRecipientCertificateForDonor()),
_transientSSLParams([&]() -> boost::optional<TransientSSLParams> {
if (auto recipientCertificate = _stateDoc.getRecipientCertificateForDonor()) {
invariant(!repl::tenantMigrationDisableX509Auth);
#ifdef MONGO_CONFIG_SSL
uassert(ErrorCodes::IllegalOperation,
"Cannot run tenant migration with x509 authentication as SSL is not enabled",
getSSLGlobalParams().sslMode.load() != SSLParams::SSLMode_disabled);
auto recipientSSLClusterPEMPayload =
recipientCertificate->getCertificate().toString() + "\n" +
recipientCertificate->getPrivateKey().toString();
return TransientSSLParams{_donorUri.connectionString(),
std::move(recipientSSLClusterPEMPayload)};
#else
// If SSL is not supported, the recipientSyncData command should have failed
// certificate field validation.
MONGO_UNREACHABLE;
#endif
} else {
invariant(repl::tenantMigrationDisableX509Auth);
return boost::none;
}
}()) {
}
boost::optional<BSONObj> TenantMigrationRecipientService::Instance::reportForCurrentOp(
MongoProcessInterface::CurrentOpConnectionsMode connMode,
MongoProcessInterface::CurrentOpSessionsMode sessionMode) noexcept {
BSONObjBuilder bob;
stdx::lock_guard lk(_mutex);
bob.append("desc", "tenant recipient migration");
_migrationUuid.appendToBuilder(&bob, "instanceID"_sd);
bob.append("tenantId", _stateDoc.getTenantId());
bob.append("donorConnectionString", _stateDoc.getDonorConnectionString());
bob.append("readPreference", _stateDoc.getReadPreference().toInnerBSON());
bob.append("state", _stateDoc.getState());
bob.append("dataSyncCompleted", _dataSyncCompletionPromise.getFuture().isReady());
bob.append("migrationCompleted", _taskCompletionPromise.getFuture().isReady());
bob.append("numRestartsDueToDonorConnectionFailure",
_stateDoc.getNumRestartsDueToDonorConnectionFailure());
bob.append("numRestartsDueToRecipientFailure", _stateDoc.getNumRestartsDueToRecipientFailure());
if (_tenantAllDatabaseCloner) {
auto stats = _tenantAllDatabaseCloner->getStats();
bob.append("approxTotalDataSize", stats.approxTotalDataSize);
bob.append("approxTotalBytesCopied", stats.approxTotalBytesCopied);
long long elapsedMillis = duration_cast<Milliseconds>(Date_t::now() - stats.start).count();
bob.append("totalReceiveElapsedMillis", elapsedMillis);
// Perform the multiplication first to avoid rounding errors, and add one to avoid division
// by 0.
long long timeRemainingMillis =
((stats.approxTotalDataSize - stats.approxTotalBytesCopied) * elapsedMillis) /
(stats.approxTotalBytesCopied + 1);
bob.append("remainingReceiveEstimatedMillis", timeRemainingMillis);
BSONObjBuilder dbsBuilder(bob.subobjStart("databases"));
_tenantAllDatabaseCloner->getStats().append(&dbsBuilder);
dbsBuilder.doneFast();
}
if (_stateDoc.getStartFetchingDonorOpTime())
_stateDoc.getStartFetchingDonorOpTime()->append(&bob, "startFetchingDonorOpTime");
if (_stateDoc.getStartApplyingDonorOpTime())
_stateDoc.getStartApplyingDonorOpTime()->append(&bob, "startApplyingDonorOpTime");
if (_stateDoc.getDataConsistentStopDonorOpTime())
_stateDoc.getDataConsistentStopDonorOpTime()->append(&bob, "dataConsistentStopDonorOpTime");
if (_stateDoc.getCloneFinishedRecipientOpTime())
_stateDoc.getCloneFinishedRecipientOpTime()->append(&bob, "cloneFinishedRecipientOpTime");
if (_stateDoc.getExpireAt())
bob.append("expireAt", *_stateDoc.getExpireAt());
if (_client) {
bob.append("donorSyncSource", _client->getServerAddress());
}
if (_stateDoc.getStartAt()) {
bob.append("receiveStart", *_stateDoc.getStartAt());
}
if (_tenantOplogApplier) {
bob.appendNumber("numOpsApplied",
static_cast<long long>(_tenantOplogApplier->getNumOpsApplied()));
}
bob.append("recipientStage", _describeStage(_recipientStage.load()));
return bob.obj();
}
Status TenantMigrationRecipientService::Instance::checkIfOptionsConflict(
const TenantMigrationRecipientDocument& stateDoc) const {
stdx::lock_guard<Latch> lg(_mutex);
invariant(stateDoc.getId() == _migrationUuid);
if (stateDoc.getTenantId() == _tenantId &&
stateDoc.getDonorConnectionString() == _donorConnectionString &&
stateDoc.getReadPreference().equals(_readPreference) &&
stateDoc.getRecipientCertificateForDonor() == _recipientCertificateForDonor) {
return Status::OK();
}
return Status(ErrorCodes::ConflictingOperationInProgress,
str::stream() << "Found active migration for migrationId \""
<< _migrationUuid.toBSON() << "\" with different options "
<< tenant_migration_util::redactStateDoc(_stateDoc.toBSON()));
}
OpTime TenantMigrationRecipientService::Instance::waitUntilMigrationReachesConsistentState(
OperationContext* opCtx) const {
return _dataConsistentPromise.getFuture().get(opCtx);
}
Timestamp selectRejectReadsBeforeTimestamp(OperationContext* opCtx,
const Timestamp& returnAfterReachingTimestamp,
const OpTime& oplogApplierOpTime) {
// Don't allow reading before the opTime timestamp of the final write on the recipient
// associated with cloning the donor's data so the client can't see an inconsistent state. The
// oplog applier timestamp may be null if no oplog entries were copied, but data may still have
// been cloned, so use the last applied opTime in that case.
//
// Note the cloning writes happen on a separate thread, but the last applied opTime in the
// replication coordinator is guaranteed to be inclusive of those writes because this function
// is called after waiting for the _dataConsistentPromise to resolve, which happens after the
// last write for cloning completes (and all of its WUOW onCommit() handlers).
auto finalRecipientWriteTimestamp = oplogApplierOpTime.getTimestamp().isNull()
? ReplicationCoordinator::get(opCtx)->getMyLastAppliedOpTime().getTimestamp()
: oplogApplierOpTime.getTimestamp();
// Also don't allow reading before the returnAfterReachingTimestamp (aka the blockTimestamp) to
// prevent readers from possibly seeing data in a point in time snapshot on the recipient that
// would not have been seen at the same point in time on the donor if the donor's cluster time
// is ahead of the recipient's.
return std::max(finalRecipientWriteTimestamp, returnAfterReachingTimestamp);
}
OpTime
TenantMigrationRecipientService::Instance::waitUntilMigrationReachesReturnAfterReachingTimestamp(
OperationContext* opCtx, const Timestamp& returnAfterReachingTimestamp) {
// This gives assurance that _tenantOplogApplier pointer won't be empty, and that it has been
// started. Additionally, we must have finished processing the recipientSyncData command that
// waits on _dataConsistentPromise.
_dataConsistentPromise.getFuture().get(opCtx);
auto getWaitOpTimeFuture = [&]() {
stdx::unique_lock lk(_mutex);
// In the event of a donor failover, it is possible that a new donor has stepped up and
// initiated this 'recipientSyncData' cmd. Make sure the recipient is not in the middle of
// restarting the oplog applier to retry the future chain.
opCtx->waitForConditionOrInterrupt(
_restartOplogApplierCondVar, lk, [&] { return !_isRestartingOplogApplier; });
if (_dataSyncCompletionPromise.getFuture().isReady()) {
// When the data sync is done, we reset _tenantOplogApplier, so just throw the data sync
// completion future result.
_dataSyncCompletionPromise.getFuture().get();
MONGO_UNREACHABLE;
}
// Sanity checks.
invariant(_tenantOplogApplier);
auto state = _stateDoc.getState();
uassert(ErrorCodes::IllegalOperation,
str::stream()
<< "Failed to wait for the donor timestamp to be majority committed due to"
"conflicting tenant migration state, migration uuid: "
<< getMigrationUUID() << " , current state: "
<< TenantMigrationRecipientState_serializer(state) << " , expected state: "
<< TenantMigrationRecipientState_serializer(
TenantMigrationRecipientStateEnum::kConsistent)
<< ".",
state == TenantMigrationRecipientStateEnum::kConsistent);
return _tenantOplogApplier->getNotificationForOpTime(
OpTime(returnAfterReachingTimestamp, OpTime::kUninitializedTerm));
};
auto waitOpTimeFuture = getWaitOpTimeFuture();
fpWaitUntilTimestampMajorityCommitted.pauseWhileSet();
auto swDonorRecipientOpTimePair = waitOpTimeFuture.getNoThrow();
auto status = swDonorRecipientOpTimePair.getStatus();
// A cancellation error may occur due to an interrupt. If that is the case, replace the error
// code with the interrupt code, the true reason for interruption.
if (ErrorCodes::isCancellationError(status)) {
stdx::lock_guard lk(_mutex);
if (!_taskState.getInterruptStatus().isOK()) {
status = _taskState.getInterruptStatus();
}
}
uassertStatusOK(status);
auto& donorRecipientOpTimePair = swDonorRecipientOpTimePair.getValue();
// Make sure that the recipient logical clock has advanced to at least the donor timestamp
// before returning success for recipientSyncData.
// Note: tickClusterTimeTo() will not tick the recipient clock backwards in time.
VectorClockMutable::get(opCtx)->tickClusterTimeTo(LogicalTime(returnAfterReachingTimestamp));
{
stdx::lock_guard lk(_mutex);
_stateDoc.setRejectReadsBeforeTimestamp(selectRejectReadsBeforeTimestamp(
opCtx, returnAfterReachingTimestamp, donorRecipientOpTimePair.recipientOpTime));
}
_stopOrHangOnFailPoint(&fpBeforePersistingRejectReadsBeforeTimestamp, opCtx);
uassertStatusOK(tenantMigrationRecipientEntryHelpers::updateStateDoc(opCtx, _stateDoc));
auto writeOpTime = repl::ReplClientInfo::forClient(opCtx->getClient()).getLastOp();
auto replCoord = repl::ReplicationCoordinator::get(_serviceContext);
WriteConcernOptions writeConcern(repl::ReplSetConfig::kConfigAllWriteConcernName,
WriteConcernOptions::SyncMode::NONE,
opCtx->getWriteConcern().wTimeout);
uassertStatusOK(replCoord->awaitReplication(opCtx, writeOpTime, writeConcern).status);
_stopOrHangOnFailPoint(&fpAfterWaitForRejectReadsBeforeTimestamp, opCtx);
return donorRecipientOpTimePair.donorOpTime;
}
std::unique_ptr<DBClientConnection> TenantMigrationRecipientService::Instance::_connectAndAuth(
const HostAndPort& serverAddress, StringData applicationName) {
auto swClientBase = ConnectionString(serverAddress)
.connect(applicationName,
0 /* socketTimeout */,
nullptr /* uri */,
nullptr /* apiParameters */,
_transientSSLParams ? &_transientSSLParams.get() : nullptr);
if (!swClientBase.isOK()) {
LOGV2_ERROR(4880400,
"Failed to connect to migration donor",
"tenantId"_attr = getTenantId(),
"migrationId"_attr = getMigrationUUID(),
"serverAddress"_attr = serverAddress,
"applicationName"_attr = applicationName,
"error"_attr = swClientBase.getStatus());
uassertStatusOK(swClientBase.getStatus());
}
auto clientBase = swClientBase.getValue().release();
// ConnectionString::connect() always returns a DBClientConnection in a unique_ptr of
// DBClientBase type.
std::unique_ptr<DBClientConnection> client(checked_cast<DBClientConnection*>(clientBase));
// Authenticate connection to the donor.
if (!_transientSSLParams) {
uassertStatusOK(
replAuthenticate(clientBase)
.withContext(str::stream()
<< "TenantMigrationRecipientService failed to authenticate to "
<< serverAddress));
} else if (MONGO_likely(!skipTenantMigrationRecipientAuth.shouldFail())) {
client->auth(auth::createInternalX509AuthDocument());
}
return client;
}
OpTime TenantMigrationRecipientService::Instance::_getDonorMajorityOpTime(
std::unique_ptr<mongo::DBClientConnection>& client) {
auto oplogOpTimeFields =
BSON(OplogEntry::kTimestampFieldName << 1 << OplogEntry::kTermFieldName << 1);
auto majorityOpTimeBson =
client->findOne(NamespaceString::kRsOplogNamespace.ns(),
BSONObj{},
Query().sort("$natural", -1),
&oplogOpTimeFields,
QueryOption_SecondaryOk,
ReadConcernArgs(ReadConcernLevel::kMajorityReadConcern).toBSONInner());
uassert(5272003, "Found no entries in the remote oplog", !majorityOpTimeBson.isEmpty());
auto majorityOpTime = uassertStatusOK(OpTime::parseFromOplogEntry(majorityOpTimeBson));
return majorityOpTime;
}
SemiFuture<TenantMigrationRecipientService::Instance::ConnectionPair>
TenantMigrationRecipientService::Instance::_createAndConnectClients() {
LOGV2_DEBUG(4880401,
1,
"Recipient migration service connecting clients",
"tenantId"_attr = getTenantId(),
"migrationId"_attr = getMigrationUUID(),
"connectionString"_attr = _donorConnectionString,
"readPreference"_attr = _readPreference);
const auto& servers = _donorUri.getServers();
stdx::lock_guard lk(_mutex);
_donorReplicaSetMonitor = ReplicaSetMonitor::createIfNeeded(
_donorUri.getSetName(), std::set<HostAndPort>(servers.begin(), servers.end()));
// Only ever used to cancel when the setTenantMigrationRecipientInstanceHostTimeout failpoint is
// set.
CancellationSource getHostCancelSource;
setTenantMigrationRecipientInstanceHostTimeout.execute([&](const BSONObj& data) {
auto exec = **_scopedExecutor;
const auto deadline =
exec->now() + Milliseconds(data["findHostTimeoutMillis"].safeNumberLong());
// Cancel the find host request after a timeout. Ignore callback handle.
exec->sleepUntil(deadline, CancellationToken::uncancelable())
.getAsync([getHostCancelSource](auto) mutable { getHostCancelSource.cancel(); });
});
if (MONGO_unlikely(hangAfterCreatingRSM.shouldFail())) {
LOGV2(5272004, "hangAfterCreatingRSM failpoint enabled");
hangAfterCreatingRSM.pauseWhileSet();
}
const auto kDelayedMajorityOpTimeErrorCode = 5272000;
return AsyncTry([this,
self = shared_from_this(),
getHostCancelSource,
kDelayedMajorityOpTimeErrorCode] {
stdx::lock_guard lk(_mutex);
// Get all donor hosts that we have excluded.
const auto& excludedHosts = _getExcludedDonorHosts(lk);
return _donorReplicaSetMonitor
->getHostOrRefresh(_readPreference, excludedHosts, getHostCancelSource.token())
.thenRunOn(**_scopedExecutor)
.then([this, self = shared_from_this(), kDelayedMajorityOpTimeErrorCode](
const HostAndPort& serverAddress) {
LOGV2(5272002,
"Attempting to connect to donor host",
"donorHost"_attr = serverAddress,
"tenantId"_attr = getTenantId(),
"migrationId"_attr = getMigrationUUID());
// Application name is constructed such that it doesn't exceeds
// kMaxApplicationNameByteLength (128 bytes).
// "TenantMigration_" (16 bytes) + <tenantId> (61 bytes) + "_" (1 byte) +
// <migrationUuid> (36 bytes) = 114 bytes length.
// Note: Since the total length of tenant database name (<tenantId>_<user
// provided db name>) can't exceed 63 bytes and the user provided db name
// should be at least one character long, the maximum length of tenantId can
// only be 61 bytes.
auto applicationName =
"TenantMigration_" + getTenantId() + "_" + getMigrationUUID().toString();
auto client = _connectAndAuth(serverAddress, applicationName);
boost::optional<repl::OpTime> startApplyingOpTime;
Timestamp startMigrationDonorTimestamp;
{
stdx::lock_guard lk(_mutex);
startApplyingOpTime = _stateDoc.getStartApplyingDonorOpTime();
startMigrationDonorTimestamp =
_stateDoc.getStartMigrationDonorTimestamp();
}
auto majoritySnapshotOpTime = _getDonorMajorityOpTime(client);
if (majoritySnapshotOpTime.getTimestamp() < startMigrationDonorTimestamp) {
stdx::lock_guard lk(_mutex);
const auto now = getGlobalServiceContext()->getFastClockSource()->now();
_excludeDonorHost(
lk,
serverAddress,
now + Milliseconds(tenantMigrationExcludeDonorHostTimeoutMS));
uasserted(
kDelayedMajorityOpTimeErrorCode,
str::stream()
<< "majoritySnapshotOpTime on donor host must not be behind "
"startMigrationDonorTimestamp, majoritySnapshotOpTime: "
<< majoritySnapshotOpTime.toString()
<< "; startMigrationDonorTimestamp: "
<< startMigrationDonorTimestamp.toString());
}
if (startApplyingOpTime && majoritySnapshotOpTime < *startApplyingOpTime) {
stdx::lock_guard lk(_mutex);
const auto now = getGlobalServiceContext()->getFastClockSource()->now();
_excludeDonorHost(
lk,
serverAddress,
now + Milliseconds(tenantMigrationExcludeDonorHostTimeoutMS));
uasserted(
kDelayedMajorityOpTimeErrorCode,
str::stream()
<< "majoritySnapshotOpTime on donor host must not be behind "
"startApplyingDonorOpTime, majoritySnapshotOpTime: "
<< majoritySnapshotOpTime.toString()
<< "; startApplyingDonorOpTime: "
<< (*startApplyingOpTime).toString());
}
// Application name is constructed such that it doesn't exceed
// kMaxApplicationNameByteLength (128 bytes).
// "TenantMigration_" (16 bytes) + <tenantId> (61 bytes) + "_" (1 byte) +
// <migrationUuid> (36 bytes) + _oplogFetcher" (13 bytes) = 127 bytes
// length.
applicationName += "_oplogFetcher";
auto oplogFetcherClient = _connectAndAuth(serverAddress, applicationName);
return ConnectionPair(std::move(client), std::move(oplogFetcherClient));
});
})
.until([this, self = shared_from_this(), kDelayedMajorityOpTimeErrorCode](
const StatusWith<ConnectionPair>& statusWith) {
auto status = statusWith.getStatus();
if (status.isOK()) {
return true;
}
LOGV2_ERROR(4880404,
"Connecting to donor failed",
"tenantId"_attr = getTenantId(),
"migrationId"_attr = getMigrationUUID(),
"error"_attr = status);
// Make sure we don't end up with a partially initialized set of connections.
stdx::lock_guard lk(_mutex);
_client = nullptr;
_oplogFetcherClient = nullptr;
// If the future chain has been interrupted, stop retrying.
if (_taskState.isInterrupted()) {
return true;
}
if (MONGO_unlikely(skipRetriesWhenConnectingToDonorHost.shouldFail())) {
LOGV2(5425600,
"skipRetriesWhenConnectingToDonorHost failpoint enabled, migration "
"proceeding with error from connecting to sync source");
return true;
}
/*
* Retry sync source selection if we encountered any of the following errors:
* 1) The RSM couldn't find a suitable donor host
* 2) The majority snapshot OpTime on the donor host was not ahead of our stored
* 'startApplyingDonorOpTime'
* 3) Some other retriable error
*/
if (status == ErrorCodes::FailedToSatisfyReadPreference ||
status == ErrorCodes::Error(kDelayedMajorityOpTimeErrorCode) ||
ErrorCodes::isRetriableError(status)) {
return false;
}
return true;
})
.on(**_scopedExecutor, CancellationToken::uncancelable())
.semi();
}
void TenantMigrationRecipientService::Instance::_excludeDonorHost(WithLock,
const HostAndPort& host,
Date_t until) {
LOGV2_DEBUG(5271800,
2,
"Excluding donor host",
"donorHost"_attr = host,
"until"_attr = until.toString());
_excludedDonorHosts.emplace_back(std::make_pair(host, until));
}
std::vector<HostAndPort> TenantMigrationRecipientService::Instance::_getExcludedDonorHosts(
WithLock lk) {
const auto now = getGlobalServiceContext()->getFastClockSource()->now();
// Clean up any hosts that have had their exclusion duration expired.
auto itr = std::remove_if(
_excludedDonorHosts.begin(),
_excludedDonorHosts.end(),
[now](const std::pair<HostAndPort, Date_t>& pair) { return pair.second < now; });
_excludedDonorHosts.erase(itr, _excludedDonorHosts.end());
// Return the list of currently excluded donor hosts.
std::vector<HostAndPort> excludedHosts;
std::transform(_excludedDonorHosts.begin(),
_excludedDonorHosts.end(),
std::back_inserter(excludedHosts),
[](const std::pair<HostAndPort, Date_t>& pair) { return pair.first; });
return excludedHosts;
}
SemiFuture<void> TenantMigrationRecipientService::Instance::_initializeStateDoc(WithLock) {
// If the instance state has a startAt field, then the instance is restarted by step up. So,
// skip persisting the state doc. And, PrimaryOnlyService::onStepUp() waits for majority commit
// of the primary no-op oplog entry written by the node in the newer term before scheduling the
// Instance::run(). So, it's also safe to assume that instance's state document written in an
// older term on disk won't get rolled back for step up case.
if (_stateDoc.getStartAt()) {
return SemiFuture<void>::makeReady();
}
LOGV2_DEBUG(5081400,
2,
"Recipient migration service initializing state document",
"tenantId"_attr = getTenantId(),
"migrationId"_attr = getMigrationUUID(),
"connectionString"_attr = _donorConnectionString,
"readPreference"_attr = _readPreference);
if (_stateDoc.getState() != TenantMigrationRecipientStateEnum::kDone) {
_stateDoc.setState(TenantMigrationRecipientStateEnum::kStarted);
} else {
// If we don't have a startAt field, we shouldn't have an expireAt either.
// If the state is 'kDone' without the expireAt field, it means a recipientForgetMigration
// command is received before a recipientSyncData command or after the state doc is garbage
// collected. We want to re-initialize the state doc but immediately mark it garbage
// collectable to account for delayed recipientSyncData commands.
invariant(!_stateDoc.getExpireAt());
}
// Persist the state doc before starting the data sync.
_stateDoc.setStartAt(getGlobalServiceContext()->getFastClockSource()->now());
return ExecutorFuture(**_scopedExecutor)
.then([this, self = shared_from_this(), stateDoc = _stateDoc] {
auto opCtx = cc().makeOperationContext();
{
Lock::ExclusiveLock stateDocInsertLock(
opCtx.get(), opCtx->lockState(), _recipientService->_stateDocInsertMutex);
uassertStatusOK(
tenantMigrationRecipientEntryHelpers::insertStateDoc(opCtx.get(), stateDoc));
}
if (MONGO_unlikely(
failWhilePersistingTenantMigrationRecipientInstanceStateDoc.shouldFail())) {
LOGV2(4878500, "Persisting state doc failed due to fail point enabled.");
uasserted(
ErrorCodes::NotWritablePrimary,
"Persisting state doc failed - "
"'failWhilePersistingTenantMigrationRecipientInstanceStateDoc' fail point "
"active");
}
// Wait for the state doc to be majority replicated to make sure that the state doc
// doesn't rollback.
auto writeOpTime = repl::ReplClientInfo::forClient(opCtx->getClient()).getLastOp();
return WaitForMajorityService::get(opCtx->getServiceContext())
.waitUntilMajority(writeOpTime, CancellationToken::uncancelable());
})
.semi();
}
void TenantMigrationRecipientService::Instance::_getStartOpTimesFromDonor(WithLock lk) {
if (_sharedData->isResuming()) {
// We are resuming a migration.
return;
}
// We only expect to already have start optimes populated if we are resuming a migration.
invariant(!_stateDoc.getStartApplyingDonorOpTime().has_value());
invariant(!_stateDoc.getStartFetchingDonorOpTime().has_value());
// Get the last oplog entry at the read concern majority optime in the remote oplog. It
// does not matter which tenant it is for.
auto lastOplogEntry1OpTime = _getDonorMajorityOpTime(_client);
LOGV2_DEBUG(4880600,
2,
"Found last oplog entry at read concern majority optime on remote node",
"migrationId"_attr = getMigrationUUID(),
"tenantId"_attr = _stateDoc.getTenantId(),
"lastOplogEntry"_attr = lastOplogEntry1OpTime.toBSON());
// Get the optime of the earliest transaction that was open at the read concern majority optime
// As with the last oplog entry, it does not matter that this may be for a different tenant; an
// optime that is too early does not result in incorrect behavior.
const auto preparedState = DurableTxnState_serializer(DurableTxnStateEnum::kPrepared);
const auto inProgressState = DurableTxnState_serializer(DurableTxnStateEnum::kInProgress);
auto transactionTableOpTimeFields = BSON(SessionTxnRecord::kStartOpTimeFieldName << 1);
auto earliestOpenTransactionBson = _client->findOne(
NamespaceString::kSessionTransactionsTableNamespace.ns(),
BSON("state" << BSON("$in" << BSON_ARRAY(preparedState << inProgressState))),
Query().sort(SessionTxnRecord::kStartOpTimeFieldName.toString(), 1),
&transactionTableOpTimeFields,
QueryOption_SecondaryOk,
ReadConcernArgs(ReadConcernLevel::kMajorityReadConcern).toBSONInner());
LOGV2_DEBUG(4880602,
2,
"Transaction table entry for earliest transaction that was open at the read "
"concern majority optime on remote node (may be empty)",
"migrationId"_attr = getMigrationUUID(),
"tenantId"_attr = _stateDoc.getTenantId(),
"earliestOpenTransaction"_attr = earliestOpenTransactionBson);
pauseAfterRetrievingLastTxnMigrationRecipientInstance.pauseWhileSet();
// We need to fetch the last oplog entry both before and after getting the transaction
// table entry, as otherwise there is a potential race where we may try to apply
// a commit for which we have not fetched a previous transaction oplog entry.
auto lastOplogEntry2OpTime = _getDonorMajorityOpTime(_client);
LOGV2_DEBUG(4880604,
2,
"Found last oplog entry at the read concern majority optime (after reading txn "
"table) on remote node",
"migrationId"_attr = getMigrationUUID(),
"tenantId"_attr = _stateDoc.getTenantId(),
"lastOplogEntry"_attr = lastOplogEntry2OpTime.toBSON());
_stateDoc.setStartApplyingDonorOpTime(lastOplogEntry2OpTime);
OpTime startFetchingDonorOpTime = lastOplogEntry1OpTime;
if (!earliestOpenTransactionBson.isEmpty()) {
auto startOpTimeField =
earliestOpenTransactionBson[SessionTxnRecord::kStartOpTimeFieldName];
if (startOpTimeField.isABSONObj()) {
startFetchingDonorOpTime = OpTime::parse(startOpTimeField.Obj());
}
}
_stateDoc.setStartFetchingDonorOpTime(startFetchingDonorOpTime);
}
AggregateCommandRequest
TenantMigrationRecipientService::Instance::_makeCommittedTransactionsAggregation() const {
auto opCtx = cc().makeOperationContext();
auto expCtx = makeExpressionContext(opCtx.get());
Timestamp startFetchingTimestamp;
{
stdx::lock_guard lk(_mutex);
invariant(_stateDoc.getStartFetchingDonorOpTime());
startFetchingTimestamp = _stateDoc.getStartFetchingDonorOpTime().get().getTimestamp();
}
auto serializedPipeline =
tenant_migration_util::createCommittedTransactionsPipelineForTenantMigrations(
expCtx, startFetchingTimestamp, getTenantId())
->serializeToBson();
AggregateCommandRequest aggRequest(NamespaceString::kSessionTransactionsTableNamespace,
std::move(serializedPipeline));
auto readConcern = repl::ReadConcernArgs(
boost::optional<repl::ReadConcernLevel>(repl::ReadConcernLevel::kMajorityReadConcern));
aggRequest.setReadConcern(readConcern.toBSONInner());
aggRequest.setHint(BSON(SessionTxnRecord::kSessionIdFieldName << 1));
aggRequest.setCursor(SimpleCursorOptions());
// We must set a writeConcern on internal commands.
aggRequest.setWriteConcern(WriteConcernOptions());
return aggRequest;
}
void TenantMigrationRecipientService::Instance::_processCommittedTransactionEntry(
const BSONObj& entry) {
auto sessionTxnRecord =
SessionTxnRecord::parse(IDLParserErrorContext("SessionTxnRecord"), entry);
auto sessionId = sessionTxnRecord.getSessionId();
auto txnNumber = sessionTxnRecord.getTxnNum();
auto optTxnRetryCounter = sessionTxnRecord.getTxnRetryCounter();
uassert(ErrorCodes::InvalidOptions,
"txnRetryCounter is only supported in sharded clusters",
!optTxnRetryCounter.has_value() || *optTxnRetryCounter == 0);
auto uniqueOpCtx = cc().makeOperationContext();
auto opCtx = uniqueOpCtx.get();
// If the tenantMigrationRecipientInfo is set on the opCtx, we will set the
// 'fromTenantMigration' field when writing oplog entries. That field is used to help recipient
// secondaries determine if a no-op entry is related to a transaction entry.
tenantMigrationRecipientInfo(opCtx) =
boost::make_optional<TenantMigrationRecipientInfo>(getMigrationUUID());
opCtx->setLogicalSessionId(sessionId);
opCtx->setTxnNumber(txnNumber);
if (optTxnRetryCounter) {
opCtx->setTxnRetryCounter(*optTxnRetryCounter);
}
opCtx->setInMultiDocumentTransaction();
MongoDOperationContextSession ocs(opCtx);
LOGV2_DEBUG(5351301,
1,
"Migration attempting to commit transaction",
"sessionId"_attr = sessionId,
"txnNumber"_attr = txnNumber,
"tenantId"_attr = getTenantId(),
"migrationId"_attr = getMigrationUUID(),
"entry"_attr = entry);
auto txnParticipant = TransactionParticipant::get(opCtx);
uassert(5351300,
str::stream() << "Migration failed to get transaction participant for transaction "
<< txnNumber << " on session " << sessionId,
txnParticipant);
// The in-memory transaction state may have been updated past the on-disk transaction state. For
// instance, this might happen in an unprepared read-only transaction, which updates in-memory
// but not on-disk. To prevent potential errors, we use the on-disk state for the following
// transaction number checks.
txnParticipant.invalidate(opCtx);
txnParticipant.refreshFromStorageIfNeeded(opCtx);
// If the entry's transaction number is stale/older than the current active transaction number
// on the participant, fail the migration.
uassert(ErrorCodes::TransactionTooOld,
str::stream() << "Migration cannot apply transaction " << txnNumber << " on session "