/
op_observer_impl.cpp
2221 lines (1934 loc) · 102 KB
/
op_observer_impl.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.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/op_observer/op_observer_impl.h"
#include <algorithm>
#include <limits>
#include "mongo/bson/bsonobjbuilder.h"
#include "mongo/db/catalog/collection_options.h"
#include "mongo/db/catalog/database.h"
#include "mongo/db/catalog/database_holder.h"
#include "mongo/db/catalog/document_validation.h"
#include "mongo/db/catalog/import_collection_oplog_entry_gen.h"
#include "mongo/db/catalog_raii.h"
#include "mongo/db/change_stream_pre_images_collection_manager.h"
#include "mongo/db/commands/txn_cmds_gen.h"
#include "mongo/db/concurrency/d_concurrency.h"
#include "mongo/db/concurrency/exception_util.h"
#include "mongo/db/dbhelpers.h"
#include "mongo/db/exec/write_stage_common.h"
#include "mongo/db/index/index_descriptor.h"
#include "mongo/db/keys_collection_document_gen.h"
#include "mongo/db/logical_time_validator.h"
#include "mongo/db/multitenancy_gen.h"
#include "mongo/db/namespace_string.h"
#include "mongo/db/op_observer/batched_write_context.h"
#include "mongo/db/op_observer/op_observer_util.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/pipeline/change_stream_preimage_gen.h"
#include "mongo/db/read_write_concern_defaults.h"
#include "mongo/db/repl/image_collection_entry_gen.h"
#include "mongo/db/repl/oplog_entry_gen.h"
#include "mongo/db/repl/repl_server_parameters_gen.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/s/operation_sharding_state.h"
#include "mongo/db/s/sharding_write_router.h"
#include "mongo/db/server_feature_flags_gen.h"
#include "mongo/db/server_options.h"
#include "mongo/db/session/session_catalog_mongod.h"
#include "mongo/db/storage/storage_parameters_gen.h"
#include "mongo/db/timeseries/bucket_catalog.h"
#include "mongo/db/timeseries/bucket_catalog_helpers.h"
#include "mongo/db/timeseries/timeseries_extended_range.h"
#include "mongo/db/transaction/transaction_participant.h"
#include "mongo/db/transaction/transaction_participant_gen.h"
#include "mongo/db/views/util.h"
#include "mongo/db/views/view_catalog_helpers.h"
#include "mongo/logv2/log.h"
#include "mongo/s/client/shard_registry.h"
#include "mongo/s/grid.h"
#include "mongo/scripting/engine.h"
#include "mongo/stdx/mutex.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/fail_point.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kReplication
namespace mongo {
using repl::DurableOplogEntry;
using repl::MutableOplogEntry;
using ChangeStreamPreImageRecordingMode = repl::ReplOperation::ChangeStreamPreImageRecordingMode;
const OperationContext::Decoration<boost::optional<ShardId>> destinedRecipientDecoration =
OperationContext::declareDecoration<boost::optional<ShardId>>();
namespace {
MONGO_FAIL_POINT_DEFINE(failCollectionUpdates);
MONGO_FAIL_POINT_DEFINE(hangAndFailUnpreparedCommitAfterReservingOplogSlot);
MONGO_FAIL_POINT_DEFINE(hangAfterLoggingApplyOpsForTransaction);
constexpr auto kNumRecordsFieldName = "numRecords"_sd;
constexpr auto kMsgFieldName = "msg"_sd;
constexpr long long kInvalidNumRecords = -1LL;
Date_t getWallClockTimeForOpLog(OperationContext* opCtx) {
auto const clockSource = opCtx->getServiceContext()->getFastClockSource();
return clockSource->now();
}
repl::OpTime logOperation(OperationContext* opCtx,
MutableOplogEntry* oplogEntry,
bool assignWallClockTime,
OplogWriter* oplogWriter) {
if (assignWallClockTime) {
oplogEntry->setWallClockTime(getWallClockTimeForOpLog(opCtx));
}
auto& times = OpObserver::Times::get(opCtx).reservedOpTimes;
auto opTime = oplogWriter->logOp(opCtx, oplogEntry);
times.push_back(opTime);
return opTime;
}
/**
* Updates the session state with the last write timestamp and transaction for that session.
*
* In the case of writes with transaction/statement id, this method will be recursively entered a
* second time for the actual write to the transactions table. Since this write does not generate an
* oplog entry, the recursion will stop at this point.
*/
void onWriteOpCompleted(OperationContext* opCtx,
std::vector<StmtId> stmtIdsWritten,
SessionTxnRecord sessionTxnRecord) {
if (sessionTxnRecord.getLastWriteOpTime().isNull())
return;
auto txnParticipant = TransactionParticipant::get(opCtx);
if (!txnParticipant ||
(!stmtIdsWritten.empty() && stmtIdsWritten.front() == kUninitializedStmtId))
// If the first statement written in uninitialized, then all the statements are assumed to
// be uninitialized.
return;
// We add these here since they may not exist if we return early.
const auto lsid = *opCtx->getLogicalSessionId();
sessionTxnRecord.setSessionId(lsid);
if (isInternalSessionForRetryableWrite(lsid)) {
sessionTxnRecord.setParentSessionId(*getParentSessionId(lsid));
}
sessionTxnRecord.setTxnNum(*opCtx->getTxnNumber());
txnParticipant.onWriteOpCompletedOnPrimary(opCtx, std::move(stmtIdsWritten), sessionTxnRecord);
}
/**
* Given the collection count from Collection::numRecords(), create and return the object for the
* 'o2' field of a drop or rename oplog entry. If the collection count exceeds the upper limit of a
* BSON NumberLong (long long), we will add a count of -1 and append a message with the original
* collection count.
*
* Replication rollback uses this field to correct correction counts on drop-pending collections.
*/
BSONObj makeObject2ForDropOrRename(uint64_t numRecords) {
BSONObjBuilder obj2Builder;
if (numRecords > static_cast<uint64_t>(std::numeric_limits<long long>::max())) {
obj2Builder.appendNumber(kNumRecordsFieldName, kInvalidNumRecords);
std::string msg = str::stream() << "Collection count " << numRecords
<< " is larger than the "
"maximum int64_t value. Setting numRecords to -1.";
obj2Builder.append(kMsgFieldName, msg);
} else {
obj2Builder.appendNumber(kNumRecordsFieldName, static_cast<long long>(numRecords));
}
auto obj = obj2Builder.obj();
return obj;
}
struct OpTimeBundle {
repl::OpTime writeOpTime;
repl::OpTime prePostImageOpTime;
Date_t wallClockTime;
};
/**
* Write oplog entry(ies) for the update operation.
*/
OpTimeBundle replLogUpdate(OperationContext* opCtx,
const OplogUpdateEntryArgs& args,
MutableOplogEntry* oplogEntry,
OplogWriter* oplogWriter) {
oplogEntry->setTid(args.coll->ns().tenantId());
oplogEntry->setNss(args.coll->ns());
oplogEntry->setUuid(args.coll->uuid());
repl::OplogLink oplogLink;
oplogWriter->appendOplogEntryChainInfo(opCtx, oplogEntry, &oplogLink, args.updateArgs->stmtIds);
OpTimeBundle opTimes;
oplogEntry->setOpType(repl::OpTypeEnum::kUpdate);
oplogEntry->setObject(args.updateArgs->update);
oplogEntry->setObject2(args.updateArgs->criteria);
oplogEntry->setFromMigrateIfTrue(args.updateArgs->source == OperationSource::kFromMigrate);
if (!args.updateArgs->oplogSlots.empty()) {
oplogEntry->setOpTime(args.updateArgs->oplogSlots.back());
}
opTimes.writeOpTime =
logOperation(opCtx, oplogEntry, true /*assignWallClockTime*/, oplogWriter);
opTimes.wallClockTime = oplogEntry->getWallClockTime();
return opTimes;
}
/**
* Write oplog entry(ies) for the delete operation.
*/
OpTimeBundle replLogDelete(OperationContext* opCtx,
const NamespaceString& nss,
MutableOplogEntry* oplogEntry,
const boost::optional<UUID>& uuid,
StmtId stmtId,
bool fromMigrate,
OplogWriter* oplogWriter) {
oplogEntry->setTid(nss.tenantId());
oplogEntry->setNss(nss);
oplogEntry->setUuid(uuid);
oplogEntry->setDestinedRecipient(destinedRecipientDecoration(opCtx));
repl::OplogLink oplogLink;
oplogWriter->appendOplogEntryChainInfo(opCtx, oplogEntry, &oplogLink, {stmtId});
OpTimeBundle opTimes;
oplogEntry->setOpType(repl::OpTypeEnum::kDelete);
oplogEntry->setObject(repl::documentKeyDecoration(opCtx).value().getShardKeyAndId());
oplogEntry->setFromMigrateIfTrue(fromMigrate);
opTimes.writeOpTime =
logOperation(opCtx, oplogEntry, true /*assignWallClockTime*/, oplogWriter);
opTimes.wallClockTime = oplogEntry->getWallClockTime();
return opTimes;
}
void writeToImageCollection(OperationContext* opCtx,
const LogicalSessionId& sessionId,
const repl::ReplOperation::ImageBundle& imageToWrite) {
repl::ImageEntry imageEntry;
imageEntry.set_id(sessionId);
imageEntry.setTxnNumber(opCtx->getTxnNumber().value());
imageEntry.setTs(imageToWrite.timestamp);
imageEntry.setImageKind(imageToWrite.imageKind);
imageEntry.setImage(imageToWrite.imageDoc);
DisableDocumentValidation documentValidationDisabler(
opCtx, DocumentValidationSettings::kDisableInternalValidation);
// In practice, this lock acquisition on kConfigImagesNamespace cannot block. The only time a
// stronger lock acquisition is taken on this namespace is during step up to create the
// collection.
AllowLockAcquisitionOnTimestampedUnitOfWork allowLockAcquisition(opCtx->lockState());
AutoGetCollection imageCollectionRaii(
opCtx, NamespaceString::kConfigImagesNamespace, LockMode::MODE_IX);
auto curOp = CurOp::get(opCtx);
const auto existingNs = curOp->getNSS();
UpdateResult res =
Helpers::upsert(opCtx, NamespaceString::kConfigImagesNamespace, imageEntry.toBSON());
{
stdx::lock_guard<Client> clientLock(*opCtx->getClient());
curOp->setNS_inlock(existingNs);
}
invariant(res.numDocsModified == 1 || !res.upsertedId.isEmpty());
}
bool shouldTimestampIndexBuildSinglePhase(OperationContext* opCtx, const NamespaceString& nss) {
// This function returns whether a timestamp for a catalog write when beginning an index build,
// or aborting an index build is necessary. There are four scenarios:
// 1. A timestamp is already set -- replication application sets a timestamp ahead of time.
// This could include the phase of initial sync where it applies oplog entries. Also,
// primaries performing an index build via `applyOps` may have a wrapping commit timestamp.
if (!opCtx->recoveryUnit()->getCommitTimestamp().isNull())
return false;
// 2. If the node is initial syncing, we do not set a timestamp.
auto replCoord = repl::ReplicationCoordinator::get(opCtx);
if (replCoord->isReplEnabled() && replCoord->getMemberState().startup2())
return false;
// 3. If the index build is on the local database, do not timestamp.
if (nss.isLocal())
return false;
// 4. All other cases, we generate a timestamp by writing a no-op oplog entry. This is
// better than using a ghost timestamp. Writing an oplog entry ensures this node is
// primary.
return true;
}
void logGlobalIndexDDLOperation(OperationContext* opCtx,
const NamespaceString& globalIndexNss,
const UUID& globalIndexUUID,
const StringData commandString,
boost::optional<long long> numKeys,
OplogWriter* oplogWriter) {
invariant(!opCtx->inMultiDocumentTransaction());
BSONObjBuilder builder;
// The rollback implementation requires the collection name to list affected namespaces.
builder.append(commandString, globalIndexNss.coll());
MutableOplogEntry oplogEntry;
oplogEntry.setOpType(repl::OpTypeEnum::kCommand);
oplogEntry.setObject(builder.done());
// On global index drops, persist the number of records into the 'o2' field similar to a
// collection drop. This allows for efficiently restoring the index keys count after rollback
// without forcing a collection scan.
invariant((numKeys && commandString == "dropGlobalIndex") ||
(!numKeys && commandString == "createGlobalIndex"));
if (numKeys) {
oplogEntry.setObject2(makeObject2ForDropOrRename(*numKeys));
}
// The 'ns' field is technically redundant as it can be derived from the uuid, however it's a
// required oplog entry field.
oplogEntry.setNss(globalIndexNss.getCommandNS());
oplogEntry.setUuid(globalIndexUUID);
constexpr StmtId stmtId = 0;
if (TransactionParticipant::get(opCtx)) {
// This is a retryable write: populate the lsid, txnNumber and stmtId fields.
// The oplog link to previous statement is empty and the stmtId is zero because this is a
// single-statement command replicating as a single createGlobalIndex/dropGlobalIndex oplog
// entry.
repl::OplogLink oplogLink;
oplogWriter->appendOplogEntryChainInfo(opCtx, &oplogEntry, &oplogLink, {stmtId});
}
auto writeOpTime = logOperation(opCtx, &oplogEntry, true /*assignWallClockTime*/, oplogWriter);
// Register the retryable write to in-memory transactions table.
SessionTxnRecord sessionTxnRecord;
sessionTxnRecord.setLastWriteOpTime(writeOpTime);
sessionTxnRecord.setLastWriteDate(oplogEntry.getWallClockTime());
onWriteOpCompleted(opCtx, {stmtId}, sessionTxnRecord);
}
} // namespace
OpObserverImpl::OpObserverImpl(std::unique_ptr<OplogWriter> oplogWriter)
: _oplogWriter(std::move(oplogWriter)) {}
void OpObserverImpl::onCreateGlobalIndex(OperationContext* opCtx,
const NamespaceString& globalIndexNss,
const UUID& globalIndexUUID) {
constexpr StringData commandString = "createGlobalIndex"_sd;
logGlobalIndexDDLOperation(opCtx,
globalIndexNss,
globalIndexUUID,
commandString,
boost::none /* numKeys */,
_oplogWriter.get());
}
void OpObserverImpl::onDropGlobalIndex(OperationContext* opCtx,
const NamespaceString& globalIndexNss,
const UUID& globalIndexUUID,
long long numKeys) {
constexpr StringData commandString = "dropGlobalIndex"_sd;
logGlobalIndexDDLOperation(
opCtx, globalIndexNss, globalIndexUUID, commandString, numKeys, _oplogWriter.get());
}
void OpObserverImpl::onCreateIndex(OperationContext* opCtx,
const NamespaceString& nss,
const UUID& uuid,
BSONObj indexDoc,
bool fromMigrate) {
auto txnParticipant = TransactionParticipant::get(opCtx);
const bool inMultiDocumentTransaction =
txnParticipant && opCtx->writesAreReplicated() && txnParticipant.transactionIsOpen();
if (inMultiDocumentTransaction) {
auto operation = MutableOplogEntry::makeCreateIndexesCommand(nss, uuid, indexDoc);
txnParticipant.addTransactionOperation(opCtx, operation);
} else {
BSONObjBuilder builder;
builder.append("createIndexes", nss.coll());
builder.appendElements(indexDoc);
MutableOplogEntry oplogEntry;
oplogEntry.setOpType(repl::OpTypeEnum::kCommand);
oplogEntry.setTid(nss.tenantId());
oplogEntry.setNss(nss.getCommandNS());
oplogEntry.setUuid(uuid);
oplogEntry.setObject(builder.done());
oplogEntry.setFromMigrateIfTrue(fromMigrate);
logOperation(opCtx, &oplogEntry, true /*assignWallClockTime*/, _oplogWriter.get());
}
}
void OpObserverImpl::onStartIndexBuild(OperationContext* opCtx,
const NamespaceString& nss,
const UUID& collUUID,
const UUID& indexBuildUUID,
const std::vector<BSONObj>& indexes,
bool fromMigrate) {
BSONObjBuilder oplogEntryBuilder;
oplogEntryBuilder.append("startIndexBuild", nss.coll());
indexBuildUUID.appendToBuilder(&oplogEntryBuilder, "indexBuildUUID");
BSONArrayBuilder indexesArr(oplogEntryBuilder.subarrayStart("indexes"));
for (const auto& indexDoc : indexes) {
indexesArr.append(indexDoc);
}
indexesArr.done();
MutableOplogEntry oplogEntry;
oplogEntry.setOpType(repl::OpTypeEnum::kCommand);
oplogEntry.setTid(nss.tenantId());
oplogEntry.setNss(nss.getCommandNS());
oplogEntry.setUuid(collUUID);
oplogEntry.setObject(oplogEntryBuilder.done());
oplogEntry.setFromMigrateIfTrue(fromMigrate);
logOperation(opCtx, &oplogEntry, true /*assignWallClockTime*/, _oplogWriter.get());
}
void OpObserverImpl::onStartIndexBuildSinglePhase(OperationContext* opCtx,
const NamespaceString& nss) {
if (!shouldTimestampIndexBuildSinglePhase(opCtx, nss)) {
return;
}
onInternalOpMessage(
opCtx,
{},
boost::none,
BSON("msg" << std::string(str::stream() << "Creating indexes. Coll: " << nss)),
boost::none,
boost::none,
boost::none,
boost::none,
boost::none);
}
void OpObserverImpl::onAbortIndexBuildSinglePhase(OperationContext* opCtx,
const NamespaceString& nss) {
if (!shouldTimestampIndexBuildSinglePhase(opCtx, nss)) {
return;
}
onInternalOpMessage(
opCtx,
{},
boost::none,
BSON("msg" << std::string(str::stream() << "Aborting indexes. Coll: " << nss)),
boost::none,
boost::none,
boost::none,
boost::none,
boost::none);
}
void OpObserverImpl::onCommitIndexBuild(OperationContext* opCtx,
const NamespaceString& nss,
const UUID& collUUID,
const UUID& indexBuildUUID,
const std::vector<BSONObj>& indexes,
bool fromMigrate) {
BSONObjBuilder oplogEntryBuilder;
oplogEntryBuilder.append("commitIndexBuild", nss.coll());
indexBuildUUID.appendToBuilder(&oplogEntryBuilder, "indexBuildUUID");
BSONArrayBuilder indexesArr(oplogEntryBuilder.subarrayStart("indexes"));
for (const auto& indexDoc : indexes) {
indexesArr.append(indexDoc);
}
indexesArr.done();
MutableOplogEntry oplogEntry;
oplogEntry.setOpType(repl::OpTypeEnum::kCommand);
oplogEntry.setTid(nss.tenantId());
oplogEntry.setNss(nss.getCommandNS());
oplogEntry.setUuid(collUUID);
oplogEntry.setObject(oplogEntryBuilder.done());
oplogEntry.setFromMigrateIfTrue(fromMigrate);
logOperation(opCtx, &oplogEntry, true /*assignWallClockTime*/, _oplogWriter.get());
}
void OpObserverImpl::onAbortIndexBuild(OperationContext* opCtx,
const NamespaceString& nss,
const UUID& collUUID,
const UUID& indexBuildUUID,
const std::vector<BSONObj>& indexes,
const Status& cause,
bool fromMigrate) {
BSONObjBuilder oplogEntryBuilder;
oplogEntryBuilder.append("abortIndexBuild", nss.coll());
indexBuildUUID.appendToBuilder(&oplogEntryBuilder, "indexBuildUUID");
BSONArrayBuilder indexesArr(oplogEntryBuilder.subarrayStart("indexes"));
for (const auto& indexDoc : indexes) {
indexesArr.append(indexDoc);
}
indexesArr.done();
BSONObjBuilder causeBuilder(oplogEntryBuilder.subobjStart("cause"));
// Some functions that extract a Status from a BSONObj, such as getStatusFromCommandResult(),
// expect the 'ok' field.
causeBuilder.appendBool("ok", 0);
cause.serializeErrorToBSON(&causeBuilder);
causeBuilder.done();
MutableOplogEntry oplogEntry;
oplogEntry.setOpType(repl::OpTypeEnum::kCommand);
oplogEntry.setTid(nss.tenantId());
oplogEntry.setNss(nss.getCommandNS());
oplogEntry.setUuid(collUUID);
oplogEntry.setObject(oplogEntryBuilder.done());
oplogEntry.setFromMigrateIfTrue(fromMigrate);
logOperation(opCtx, &oplogEntry, true /*assignWallClockTime*/, _oplogWriter.get());
}
void OpObserverImpl::onInserts(OperationContext* opCtx,
const CollectionPtr& coll,
std::vector<InsertStatement>::const_iterator first,
std::vector<InsertStatement>::const_iterator last,
bool fromMigrate) {
auto txnParticipant = TransactionParticipant::get(opCtx);
const bool inMultiDocumentTransaction =
txnParticipant && opCtx->writesAreReplicated() && txnParticipant.transactionIsOpen();
const auto& nss = coll->ns();
const auto& uuid = coll->uuid();
std::vector<repl::OpTime> opTimeList;
repl::OpTime lastOpTime;
ShardingWriteRouter shardingWriteRouter(opCtx, nss, Grid::get(opCtx)->catalogCache());
auto& batchedWriteContext = BatchedWriteContext::get(opCtx);
const bool inBatchedWrite = batchedWriteContext.writesAreBatched();
if (inBatchedWrite) {
invariant(!fromMigrate);
write_stage_common::PreWriteFilter preWriteFilter(opCtx, nss);
for (auto iter = first; iter != last; iter++) {
const auto docKey = repl::getDocumentKey(opCtx, coll, iter->doc).getShardKeyAndId();
auto operation = MutableOplogEntry::makeInsertOperation(nss, uuid, iter->doc, docKey);
operation.setDestinedRecipient(
shardingWriteRouter.getReshardingDestinedRecipient(iter->doc));
if (!OperationShardingState::isComingFromRouter(opCtx) &&
preWriteFilter.computeAction(Document(iter->doc)) ==
write_stage_common::PreWriteFilter::Action::kWriteAsFromMigrate) {
LOGV2_DEBUG(6585800,
3,
"Marking insert operation of orphan document with the 'fromMigrate' "
"flag to prevent a wrong change stream event",
"namespace"_attr = nss,
"document"_attr = iter->doc);
operation.setFromMigrate(true);
}
batchedWriteContext.addBatchedOperation(opCtx, operation);
}
} else if (inMultiDocumentTransaction) {
invariant(!fromMigrate);
// Do not add writes to the profile collection to the list of transaction operations, since
// these are done outside the transaction. There is no top-level WriteUnitOfWork when we are
// in a SideTransactionBlock.
if (!opCtx->getWriteUnitOfWork()) {
invariant(nss.isSystemDotProfile());
return;
}
const bool inRetryableInternalTransaction =
isInternalSessionForRetryableWrite(*opCtx->getLogicalSessionId());
write_stage_common::PreWriteFilter preWriteFilter(opCtx, nss);
for (auto iter = first; iter != last; iter++) {
const auto docKey = repl::getDocumentKey(opCtx, coll, iter->doc).getShardKeyAndId();
auto operation = MutableOplogEntry::makeInsertOperation(nss, uuid, iter->doc, docKey);
if (inRetryableInternalTransaction) {
operation.setInitializedStatementIds(iter->stmtIds);
}
operation.setDestinedRecipient(
shardingWriteRouter.getReshardingDestinedRecipient(iter->doc));
if (!OperationShardingState::isComingFromRouter(opCtx) &&
preWriteFilter.computeAction(Document(iter->doc)) ==
write_stage_common::PreWriteFilter::Action::kWriteAsFromMigrate) {
LOGV2_DEBUG(6585801,
3,
"Marking insert operation of orphan document with the 'fromMigrate' "
"flag to prevent a wrong change stream event",
"namespace"_attr = nss,
"document"_attr = iter->doc);
operation.setFromMigrate(true);
}
txnParticipant.addTransactionOperation(opCtx, operation);
}
} else {
std::function<boost::optional<ShardId>(const BSONObj& doc)> getDestinedRecipientFn =
[&shardingWriteRouter](const BSONObj& doc) {
return shardingWriteRouter.getReshardingDestinedRecipient(doc);
};
MutableOplogEntry oplogEntryTemplate;
oplogEntryTemplate.setTid(nss.tenantId());
oplogEntryTemplate.setNss(nss);
oplogEntryTemplate.setUuid(uuid);
oplogEntryTemplate.setFromMigrateIfTrue(fromMigrate);
Date_t lastWriteDate = getWallClockTimeForOpLog(opCtx);
oplogEntryTemplate.setWallClockTime(lastWriteDate);
opTimeList = _oplogWriter->logInsertOps(
opCtx, &oplogEntryTemplate, first, last, getDestinedRecipientFn, coll);
if (!opTimeList.empty())
lastOpTime = opTimeList.back();
auto& times = OpObserver::Times::get(opCtx).reservedOpTimes;
using std::begin;
using std::end;
times.insert(end(times), begin(opTimeList), end(opTimeList));
std::vector<StmtId> stmtIdsWritten;
std::for_each(first, last, [&](const InsertStatement& stmt) {
stmtIdsWritten.insert(stmtIdsWritten.end(), stmt.stmtIds.begin(), stmt.stmtIds.end());
});
SessionTxnRecord sessionTxnRecord;
sessionTxnRecord.setLastWriteOpTime(lastOpTime);
sessionTxnRecord.setLastWriteDate(lastWriteDate);
onWriteOpCompleted(opCtx, stmtIdsWritten, sessionTxnRecord);
}
size_t index = 0;
for (auto it = first; it != last; it++, index++) {
auto opTime = opTimeList.empty() ? repl::OpTime() : opTimeList[index];
shardObserveInsertOp(opCtx,
nss,
it->doc,
opTime,
shardingWriteRouter,
fromMigrate,
inMultiDocumentTransaction);
}
if (nss.coll() == "system.js") {
Scope::storedFuncMod(opCtx);
} else if (nss.isSystemDotViews()) {
try {
for (auto it = first; it != last; it++) {
view_util::validateViewDefinitionBSON(opCtx, it->doc, nss.dbName());
uassertStatusOK(CollectionCatalog::get(opCtx)->createView(
opCtx,
NamespaceStringUtil::deserialize(nss.dbName().tenantId(),
it->doc.getStringField("_id")),
{nss.dbName(), it->doc.getStringField("viewOn")},
BSONArray{it->doc.getObjectField("pipeline")},
view_catalog_helpers::validatePipeline,
it->doc.getObjectField("collation"),
ViewsForDatabase::Durability::kAlreadyDurable));
}
} catch (const DBException&) {
// If a previous operation left the view catalog in an invalid state, our inserts can
// fail even if all the definitions are valid. Reloading may help us reset the state.
CollectionCatalog::get(opCtx)->reloadViews(opCtx, nss.dbName()).ignore();
}
} else if (nss == NamespaceString::kSessionTransactionsTableNamespace && !lastOpTime.isNull()) {
for (auto it = first; it != last; it++) {
auto mongoDSessionCatalog = MongoDSessionCatalog::get(opCtx);
mongoDSessionCatalog->observeDirectWriteToConfigTransactions(opCtx, it->doc);
}
} else if (nss == NamespaceString::kConfigSettingsNamespace) {
for (auto it = first; it != last; it++) {
ReadWriteConcernDefaults::get(opCtx).observeDirectWriteToConfigSettings(
opCtx, it->doc["_id"], it->doc);
}
} else if (nss == NamespaceString::kExternalKeysCollectionNamespace) {
for (auto it = first; it != last; it++) {
auto externalKey =
ExternalKeysCollectionDocument::parse(IDLParserContext("externalKey"), it->doc);
opCtx->recoveryUnit()->onCommit(
[this, opCtx, externalKey = std::move(externalKey)](
boost::optional<Timestamp> unusedCommitTime) mutable {
auto validator = LogicalTimeValidator::get(opCtx);
if (validator) {
validator->cacheExternalKey(externalKey);
}
});
}
} else if (nss.isTimeseriesBucketsCollection()) {
// Check if the bucket _id is sourced from a date outside the standard range. If our writes
// end up erroring out or getting rolled back, then this flag will stay set. This is okay
// though, as it only disables some query optimizations and won't result in any correctness
// issues if the flag is set when it doesn't need to be (as opposed to NOT being set when it
// DOES need to be -- that will cause correctness issues). Additionally, if the user tried
// to insert measurements with dates outside the standard range, chances are they will do so
// again, and we will have only set the flag a little early.
invariant(opCtx->lockState()->isCollectionLockedForMode(nss, MODE_IX));
auto bucketsColl =
CollectionCatalog::get(opCtx)->lookupCollectionByNamespaceForRead(opCtx, nss);
tassert(6905201, "Could not find collection for write", bucketsColl);
auto timeSeriesOptions = bucketsColl->getTimeseriesOptions();
if (timeSeriesOptions.has_value()) {
if (auto currentSetting = bucketsColl->getRequiresTimeseriesExtendedRangeSupport();
!currentSetting &&
timeseries::bucketsHaveDateOutsideStandardRange(
timeSeriesOptions.value(), first, last)) {
bucketsColl->setRequiresTimeseriesExtendedRangeSupport(opCtx);
}
}
}
}
void OpObserverImpl::onInsertGlobalIndexKey(OperationContext* opCtx,
const NamespaceString& globalIndexNss,
const UUID& globalIndexUuid,
const BSONObj& key,
const BSONObj& docKey) {
if (!opCtx->writesAreReplicated()) {
return;
}
// _shardsvrInsertGlobalIndexKey must run inside a multi-doc transaction.
auto txnParticipant = TransactionParticipant::get(opCtx);
invariant(txnParticipant && txnParticipant.transactionIsOpen());
invariant(!opCtx->isRetryableWrite());
const auto op = MutableOplogEntry::makeInsertGlobalIndexKeyOperation(
globalIndexNss, globalIndexUuid, key, docKey);
txnParticipant.addTransactionOperation(opCtx, op);
}
void OpObserverImpl::onDeleteGlobalIndexKey(OperationContext* opCtx,
const NamespaceString& globalIndexNss,
const UUID& globalIndexUuid,
const BSONObj& key,
const BSONObj& docKey) {
if (!opCtx->writesAreReplicated()) {
return;
}
// _shardsvrDeleteGlobalIndexKey must run inside a multi-doc transaction.
auto txnParticipant = TransactionParticipant::get(opCtx);
invariant(txnParticipant && txnParticipant.transactionIsOpen());
invariant(!opCtx->isRetryableWrite());
const auto op = MutableOplogEntry::makeDeleteGlobalIndexKeyOperation(
globalIndexNss, globalIndexUuid, key, docKey);
txnParticipant.addTransactionOperation(opCtx, op);
}
void OpObserverImpl::onUpdate(OperationContext* opCtx, const OplogUpdateEntryArgs& args) {
failCollectionUpdates.executeIf(
[&](const BSONObj&) {
uasserted(40654,
str::stream()
<< "failCollectionUpdates failpoint enabled, namespace: "
<< args.coll->ns().ns() << ", update: " << args.updateArgs->update
<< " on document with " << args.updateArgs->criteria);
},
[&](const BSONObj& data) {
// If the failpoint specifies no collection or matches the existing one, fail.
auto collElem = data["collectionNS"];
return !collElem || args.coll->ns().ns() == collElem.String();
});
// Do not log a no-op operation; see SERVER-21738
if (args.updateArgs->update.isEmpty()) {
return;
}
auto txnParticipant = TransactionParticipant::get(opCtx);
const bool inMultiDocumentTransaction =
txnParticipant && opCtx->writesAreReplicated() && txnParticipant.transactionIsOpen();
ShardingWriteRouter shardingWriteRouter(
opCtx, args.coll->ns(), Grid::get(opCtx)->catalogCache());
OpTimeBundle opTime;
auto& batchedWriteContext = BatchedWriteContext::get(opCtx);
const bool inBatchedWrite = batchedWriteContext.writesAreBatched();
if (inBatchedWrite) {
auto operation = MutableOplogEntry::makeUpdateOperation(
args.coll->ns(), args.coll->uuid(), args.updateArgs->update, args.updateArgs->criteria);
operation.setDestinedRecipient(
shardingWriteRouter.getReshardingDestinedRecipient(args.updateArgs->updatedDoc));
operation.setFromMigrateIfTrue(args.updateArgs->source == OperationSource::kFromMigrate);
batchedWriteContext.addBatchedOperation(opCtx, operation);
} else if (inMultiDocumentTransaction) {
const bool inRetryableInternalTransaction =
isInternalSessionForRetryableWrite(*opCtx->getLogicalSessionId());
auto operation = MutableOplogEntry::makeUpdateOperation(
args.coll->ns(), args.coll->uuid(), args.updateArgs->update, args.updateArgs->criteria);
if (inRetryableInternalTransaction) {
operation.setInitializedStatementIds(args.updateArgs->stmtIds);
if (args.updateArgs->storeDocOption == CollectionUpdateArgs::StoreDocOption::PreImage) {
invariant(!args.updateArgs->preImageDoc.isEmpty());
operation.setPreImage(args.updateArgs->preImageDoc.getOwned());
operation.setPreImageRecordedForRetryableInternalTransaction();
if (args.retryableFindAndModifyLocation ==
RetryableFindAndModifyLocation::kSideCollection) {
operation.setNeedsRetryImage(repl::RetryImageEnum::kPreImage);
}
}
if (args.updateArgs->storeDocOption ==
CollectionUpdateArgs::StoreDocOption::PostImage) {
invariant(!args.updateArgs->updatedDoc.isEmpty());
operation.setPostImage(args.updateArgs->updatedDoc.getOwned());
if (args.retryableFindAndModifyLocation ==
RetryableFindAndModifyLocation::kSideCollection) {
operation.setNeedsRetryImage(repl::RetryImageEnum::kPostImage);
}
}
}
if (args.updateArgs->changeStreamPreAndPostImagesEnabledForCollection) {
invariant(!args.updateArgs->preImageDoc.isEmpty());
operation.setPreImage(args.updateArgs->preImageDoc.getOwned());
operation.setChangeStreamPreImageRecordingMode(
ChangeStreamPreImageRecordingMode::kPreImagesCollection);
}
auto scopedCss =
CollectionShardingState::assertCollectionLockedAndAcquire(opCtx, args.coll->ns());
auto scopedCollectionDescription = scopedCss->getCollectionDescription(opCtx);
if (scopedCollectionDescription.isSharded()) {
operation.setPostImageDocumentKey(
scopedCollectionDescription.extractDocumentKey(args.updateArgs->updatedDoc)
.getOwned());
}
operation.setDestinedRecipient(
shardingWriteRouter.getReshardingDestinedRecipient(args.updateArgs->updatedDoc));
operation.setFromMigrateIfTrue(args.updateArgs->source == OperationSource::kFromMigrate);
txnParticipant.addTransactionOperation(opCtx, operation);
} else {
MutableOplogEntry oplogEntry;
oplogEntry.setDestinedRecipient(
shardingWriteRouter.getReshardingDestinedRecipient(args.updateArgs->updatedDoc));
if (args.retryableFindAndModifyLocation ==
RetryableFindAndModifyLocation::kSideCollection) {
// If we've stored a preImage:
if (args.updateArgs->storeDocOption == CollectionUpdateArgs::StoreDocOption::PreImage) {
oplogEntry.setNeedsRetryImage({repl::RetryImageEnum::kPreImage});
} else if (args.updateArgs->storeDocOption ==
CollectionUpdateArgs::StoreDocOption::PostImage) {
// Or if we're storing a postImage.
oplogEntry.setNeedsRetryImage({repl::RetryImageEnum::kPostImage});
}
}
opTime = replLogUpdate(opCtx, args, &oplogEntry, _oplogWriter.get());
if (oplogEntry.getNeedsRetryImage()) {
// If the oplog entry has `needsRetryImage`, copy the image into image collection.
const BSONObj& dataImage = [&]() {
if (oplogEntry.getNeedsRetryImage().value() == repl::RetryImageEnum::kPreImage) {
return args.updateArgs->preImageDoc;
} else {
return args.updateArgs->updatedDoc;
}
}();
auto imageToWrite =
repl::ReplOperation::ImageBundle{oplogEntry.getNeedsRetryImage().value(),
dataImage,
opTime.writeOpTime.getTimestamp()};
writeToImageCollection(opCtx, *opCtx->getLogicalSessionId(), imageToWrite);
}
// Write a pre-image to the change streams pre-images collection when following conditions
// are met:
// 1. The collection has 'changeStreamPreAndPostImages' enabled.
// 2. The node wrote the oplog entry for the corresponding operation.
// 3. The request to write the pre-image does not come from chunk-migrate event, i.e. source
// of the request is not 'fromMigrate'. The 'fromMigrate' events are filtered out by
// change streams and storing them in pre-image collection is redundant.
// 4. a request to update is not on a temporary resharding collection. This update request
// does not result in change streams events. Recording pre-images from temporary
// resharing collection could result in incorrect pre-image getting recorded due to the
// temporary resharding collection not being consistent until writes are blocked (initial
// sync mode application).
if (args.updateArgs->changeStreamPreAndPostImagesEnabledForCollection &&
!opTime.writeOpTime.isNull() &&
args.updateArgs->source != OperationSource::kFromMigrate &&
!args.coll->ns().isTemporaryReshardingCollection()) {
const auto& preImageDoc = args.updateArgs->preImageDoc;
tassert(5868600, "PreImage must be set", !preImageDoc.isEmpty());
ChangeStreamPreImageId id(args.coll->uuid(), opTime.writeOpTime.getTimestamp(), 0);
ChangeStreamPreImage preImage(id, opTime.wallClockTime, preImageDoc);
ChangeStreamPreImagesCollectionManager::insertPreImage(
opCtx, args.coll->ns().tenantId(), preImage);
}
SessionTxnRecord sessionTxnRecord;
sessionTxnRecord.setLastWriteOpTime(opTime.writeOpTime);
sessionTxnRecord.setLastWriteDate(opTime.wallClockTime);
onWriteOpCompleted(opCtx, args.updateArgs->stmtIds, sessionTxnRecord);
}
if (args.coll->ns() != NamespaceString::kSessionTransactionsTableNamespace) {
if (args.updateArgs->source != OperationSource::kFromMigrate) {
shardObserveUpdateOp(opCtx,
args.coll->ns(),
args.updateArgs->preImageDoc,
args.updateArgs->updatedDoc,
opTime.writeOpTime,
shardingWriteRouter,
opTime.prePostImageOpTime,
inMultiDocumentTransaction);
}
}
if (args.coll->ns().coll() == "system.js") {
Scope::storedFuncMod(opCtx);
} else if (args.coll->ns().isSystemDotViews()) {
CollectionCatalog::get(opCtx)->reloadViews(opCtx, args.coll->ns().dbName()).ignore();
} else if (args.coll->ns() == NamespaceString::kSessionTransactionsTableNamespace &&
!opTime.writeOpTime.isNull()) {
auto mongoDSessionCatalog = MongoDSessionCatalog::get(opCtx);
mongoDSessionCatalog->observeDirectWriteToConfigTransactions(opCtx,
args.updateArgs->updatedDoc);
} else if (args.coll->ns() == NamespaceString::kConfigSettingsNamespace) {
ReadWriteConcernDefaults::get(opCtx).observeDirectWriteToConfigSettings(
opCtx, args.updateArgs->updatedDoc["_id"], args.updateArgs->updatedDoc);
} else if (args.coll->ns().isTimeseriesBucketsCollection()) {
if (args.updateArgs->source != OperationSource::kTimeseriesInsert) {
OID bucketId = args.updateArgs->updatedDoc["_id"].OID();
timeseries::handleDirectWrite(opCtx, bucketId);
}
}
}
void OpObserverImpl::aboutToDelete(OperationContext* opCtx,
const CollectionPtr& coll,
BSONObj const& doc) {
repl::documentKeyDecoration(opCtx).emplace(repl::getDocumentKey(opCtx, coll, doc));
ShardingWriteRouter shardingWriteRouter(opCtx, coll->ns(), Grid::get(opCtx)->catalogCache());
repl::DurableReplOperation op;
op.setDestinedRecipient(shardingWriteRouter.getReshardingDestinedRecipient(doc));
destinedRecipientDecoration(opCtx) = op.getDestinedRecipient();
shardObserveAboutToDelete(opCtx, coll->ns(), doc);
if (coll->ns().isTimeseriesBucketsCollection()) {
OID bucketId = doc["_id"].OID();
timeseries::handleDirectWrite(opCtx, bucketId);
}
}
void OpObserverImpl::onDelete(OperationContext* opCtx,
const CollectionPtr& coll,
StmtId stmtId,
const OplogDeleteEntryArgs& args) {
const auto& nss = coll->ns();
const auto uuid = coll->uuid();
auto optDocKey = repl::documentKeyDecoration(opCtx);
invariant(optDocKey, nss.ns());
auto& documentKey = optDocKey.value();
auto txnParticipant = TransactionParticipant::get(opCtx);
const bool inMultiDocumentTransaction =
txnParticipant && opCtx->writesAreReplicated() && txnParticipant.transactionIsOpen();
auto& batchedWriteContext = BatchedWriteContext::get(opCtx);
const bool inBatchedWrite = batchedWriteContext.writesAreBatched();
OpTimeBundle opTime;
if (inBatchedWrite) {
if (nss == NamespaceString::kSessionTransactionsTableNamespace) {
auto mongoDSessionCatalog = MongoDSessionCatalog::get(opCtx);
mongoDSessionCatalog->observeDirectWriteToConfigTransactions(opCtx,
documentKey.getId());
}
auto operation =