/
rs_rollback.cpp
2181 lines (1924 loc) · 104 KB
/
rs_rollback.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_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kReplicationRollback
#include "mongo/platform/basic.h"
#include "mongo/db/repl/rs_rollback.h"
#include <algorithm>
#include <memory>
#include "mongo/bson/bsonelement_comparator.h"
#include "mongo/bson/util/bson_extract.h"
#include "mongo/db/auth/authorization_manager.h"
#include "mongo/db/catalog/collection_catalog.h"
#include "mongo/db/catalog/database_holder.h"
#include "mongo/db/catalog/document_validation.h"
#include "mongo/db/catalog/index_build_oplog_entry.h"
#include "mongo/db/catalog/index_catalog.h"
#include "mongo/db/catalog/rename_collection.h"
#include "mongo/db/catalog_raii.h"
#include "mongo/db/client.h"
#include "mongo/db/commands.h"
#include "mongo/db/commands/txn_cmds_gen.h"
#include "mongo/db/concurrency/replication_state_transition_lock_guard.h"
#include "mongo/db/concurrency/write_conflict_exception.h"
#include "mongo/db/db_raii.h"
#include "mongo/db/dbhelpers.h"
#include "mongo/db/exec/working_set_common.h"
#include "mongo/db/index_builds_coordinator.h"
#include "mongo/db/logical_session_id.h"
#include "mongo/db/logical_time_validator.h"
#include "mongo/db/ops/delete.h"
#include "mongo/db/ops/update.h"
#include "mongo/db/ops/update_request.h"
#include "mongo/db/query/internal_plans.h"
#include "mongo/db/read_write_concern_defaults.h"
#include "mongo/db/repl/bgsync.h"
#include "mongo/db/repl/drop_pending_collection_reaper.h"
#include "mongo/db/repl/oplog.h"
#include "mongo/db/repl/oplog_interface.h"
#include "mongo/db/repl/replication_coordinator.h"
#include "mongo/db/repl/replication_coordinator_impl.h"
#include "mongo/db/repl/replication_process.h"
#include "mongo/db/repl/roll_back_local_operations.h"
#include "mongo/db/repl/rollback_source.h"
#include "mongo/db/s/shard_identity_rollback_notifier.h"
#include "mongo/db/session_catalog_mongod.h"
#include "mongo/db/storage/control/journal_flusher.h"
#include "mongo/db/storage/durable_catalog.h"
#include "mongo/db/storage/remove_saver.h"
#include "mongo/db/transaction_participant.h"
#include "mongo/logv2/log.h"
#include "mongo/s/client/shard_registry.h"
#include "mongo/s/grid.h"
#include "mongo/util/exit.h"
#include "mongo/util/fail_point.h"
#include "mongo/util/scopeguard.h"
namespace mongo {
using std::list;
using std::map;
using std::pair;
using std::set;
using std::shared_ptr;
using std::string;
using std::unique_ptr;
namespace repl {
MONGO_FAIL_POINT_DEFINE(rollbackExitEarlyAfterCollectionDrop);
using namespace rollback_internal;
bool DocID::operator<(const DocID& other) const {
int comp = uuid.toString().compare(other.uuid.toString());
if (comp < 0)
return true;
if (comp > 0)
return false;
const StringData::ComparatorInterface* stringComparator = nullptr;
BSONElementComparator eltCmp(BSONElementComparator::FieldNamesMode::kIgnore, stringComparator);
return eltCmp.evaluate(_id < other._id);
}
bool DocID::operator==(const DocID& other) const {
// Since this is only used for tests, going with the simple impl that reuses operator< which is
// used in the real code.
return !(*this < other || other < *this);
}
void FixUpInfo::removeAllDocsToRefetchFor(UUID collectionUUID) {
docsToRefetch.erase(docsToRefetch.lower_bound(DocID::minFor(collectionUUID)),
docsToRefetch.upper_bound(DocID::maxFor(collectionUUID)));
}
void FixUpInfo::removeRedundantOperations() {
for (const auto& collectionUUID : collectionsToDrop) {
removeAllDocsToRefetchFor(collectionUUID);
indexesToDrop.erase(collectionUUID);
indexesToCreate.erase(collectionUUID);
collectionsToRename.erase(collectionUUID);
collectionsToResyncMetadata.erase(collectionUUID);
}
}
bool FixUpInfo::removeRedundantIndexCommands(UUID uuid, std::string indexName) {
LOGV2_DEBUG(21659,
2,
"Attempting to remove redundant index operations from the set of indexes to create "
"for collection {uuid}, for index '{indexName}'",
"Attempting to remove redundant index operations from the set of indexes to create",
"uuid"_attr = uuid,
"indexName"_attr = indexName);
// See if there are any indexes to create for this collection.
auto indexes = indexesToCreate.find(uuid);
// There are no indexes to create for this collection UUID, so there are no index creation
// operations to remove.
if (indexes == indexesToCreate.end()) {
LOGV2_DEBUG(21660,
2,
"Collection {uuid} has no indexes to create. Not removing any index creation "
"operations for index '{indexName}'.",
"Collection has no indexes to create. Not removing any index creation "
"operations for index",
"uuid"_attr = uuid,
"indexName"_attr = indexName);
return false;
}
// This is the set of all indexes to create for the given collection UUID. Keep a reference so
// we can modify the original object.
std::map<std::string, BSONObj>* indexesToCreateForColl = &(indexes->second);
// If this index was not previously added to the set of indexes that need to be created for this
// collection, then we do nothing.
if (indexesToCreateForColl->find(indexName) == indexesToCreateForColl->end()) {
LOGV2_DEBUG(21661,
2,
"Index '{indexName}' was not previously set to be created for collection "
"{uuid}. Not removing any index creation operations.",
"Index was not previously set to be created for collection. Not removing any "
"index creation operations",
"indexName"_attr = indexName,
"uuid"_attr = uuid);
return false;
}
// This index was previously added to the set of indexes to create for this collection, so we
// remove it from that set.
LOGV2_DEBUG(21662,
2,
"Index '{indexName}' was previously set to be created for collection {uuid}. "
"Removing this redundant index creation operation.",
"Index was previously set to be created for collection. Removing this redundant "
"index creation operation",
"indexName"_attr = indexName,
"uuid"_attr = uuid);
indexesToCreateForColl->erase(indexName);
// If there are now no remaining indexes to create for this collection, remove it from
// the set of collections that we need to create indexes for.
if (indexesToCreateForColl->empty()) {
indexesToCreate.erase(uuid);
}
return true;
}
void FixUpInfo::recordRollingBackDrop(const NamespaceString& nss, OpTime opTime, UUID uuid) {
// Records the collection that needs to be removed from the drop-pending collections
// list in the DropPendingCollectionReaper.
collectionsToRemoveFromDropPendingCollections.emplace(uuid, std::make_pair(opTime, nss));
// Records the collection drop as a rename from the drop pending
// namespace to its namespace before it was dropped.
RenameCollectionInfo info;
info.renameTo = nss;
info.renameFrom = nss.makeDropPendingNamespace(opTime);
// We do not need to check if there is already an entry in collectionsToRename
// for this collection because it is not possible that a renameCollection occurs
// on the same collection after it has been dropped. Thus, we know that this
// will be the first RenameCollectionInfo entry for this collection and do not
// need to change the renameFrom entry to account for multiple renames.
collectionsToRename[uuid] = info;
}
Status FixUpInfo::recordDropTargetInfo(const BSONElement& dropTarget,
const BSONObj& obj,
OpTime opTime) {
StatusWith<UUID> dropTargetUUIDStatus = UUID::parse(dropTarget);
if (!dropTargetUUIDStatus.isOK()) {
LOGV2_ERROR(21729,
"Unable to roll back renameCollection. Cannot parse dropTarget UUID",
"oplogEntry"_attr = redact(obj),
"error"_attr = redact(dropTargetUUIDStatus.getStatus()));
return dropTargetUUIDStatus.getStatus();
}
UUID dropTargetUUID = dropTargetUUIDStatus.getValue();
// The namespace of the collection that was dropped is the same namespace
// that we are trying to rename the collection to.
NamespaceString droppedNs(obj.getStringField("to"));
// Records the information necessary for undoing the dropTarget.
recordRollingBackDrop(droppedNs, opTime, dropTargetUUID);
return Status::OK();
}
Status rollback_internal::updateFixUpInfoFromLocalOplogEntry(OperationContext* opCtx,
const OplogInterface& localOplog,
FixUpInfo& fixUpInfo,
const BSONObj& ourObj,
bool isNestedApplyOpsCommand) {
// Checks that the oplog entry is smaller than 512 MB. We do not roll back if the
// oplog entry is larger than 512 MB.
if (ourObj.objsize() > 512 * 1024 * 1024)
throw RSFatalException(str::stream()
<< "Rollback too large, oplog size: " << ourObj.objsize());
// If required fields are not present in the BSONObj for an applyOps entry, create these fields
// and populate them with dummy values before parsing ourObj as an oplog entry.
BSONObjBuilder bob;
if (isNestedApplyOpsCommand) {
if (!ourObj.hasField(OplogEntry::kTimestampFieldName)) {
bob.appendTimestamp(OplogEntry::kTimestampFieldName);
}
if (!ourObj.hasField(OplogEntry::kWallClockTimeFieldName)) {
bob.append(OplogEntry::kWallClockTimeFieldName, Date_t());
}
}
bob.appendElements(ourObj);
BSONObj fixedObj = bob.obj();
// Parse the oplog entry.
const OplogEntry oplogEntry(fixedObj);
if (isNestedApplyOpsCommand) {
LOGV2_DEBUG(21663,
2,
"Updating rollback FixUpInfo for nested applyOps oplog entry: {oplogEntry}",
"Updating rollback FixUpInfo for nested applyOps oplog entry",
"oplogEntry"_attr = redact(oplogEntry.toBSONForLogging()));
}
// Extract the op's collection namespace and UUID.
NamespaceString nss = oplogEntry.getNss();
auto uuid = oplogEntry.getUuid();
if (oplogEntry.getOpType() == OpTypeEnum::kNoop)
return Status::OK();
if (oplogEntry.getNss().isEmpty()) {
throw RSFatalException(str::stream() << "Local op on rollback has no ns: "
<< redact(oplogEntry.toBSONForLogging()));
}
auto obj = oplogEntry.getOperationToApply();
if (obj.isEmpty()) {
throw RSFatalException(str::stream() << "Local op on rollback has no object field: "
<< redact(oplogEntry.toBSONForLogging()));
}
// If the operation being rolled back has a txnNumber, then the corresponding entry in the
// session transaction table needs to be refetched.
const auto& operationSessionInfo = oplogEntry.getOperationSessionInfo();
auto txnNumber = operationSessionInfo.getTxnNumber();
if (txnNumber) {
auto sessionId = operationSessionInfo.getSessionId();
invariant(sessionId);
auto transactionTableUUID = fixUpInfo.transactionTableUUID;
if (transactionTableUUID) {
BSONObjBuilder txnBob;
txnBob.append("_id", sessionId->toBSON());
auto txnObj = txnBob.obj();
DocID txnDoc(txnObj, txnObj.firstElement(), transactionTableUUID.get());
txnDoc.ns = NamespaceString::kSessionTransactionsTableNamespace.ns();
fixUpInfo.docsToRefetch.insert(txnDoc);
fixUpInfo.refetchTransactionDocs = true;
} else {
throw RSFatalException(
str::stream() << NamespaceString::kSessionTransactionsTableNamespace.ns()
<< " does not have a UUID, but local op has a transaction number: "
<< redact(oplogEntry.toBSONForLogging()));
}
if (oplogEntry.isPartialTransaction()) {
// If this is a transaction which did not commit, we need do nothing more than
// rollback the transaction table entry. If it did commit, we will have rolled it
// back when we rolled back the commit.
return Status::OK();
}
}
if (oplogEntry.getOpType() == OpTypeEnum::kCommand) {
// The first element of the object is the name of the command
// and the collection it is acting on, e.x. {renameCollection: "test.x"}.
BSONElement first = obj.firstElement();
switch (oplogEntry.getCommandType()) {
case OplogEntry::CommandType::kCreate: {
// Example create collection oplog entry
// {
// ts: ...,
// h: ...,
// op: "c",
// ns: "foo.$cmd",
// ui: BinData(...),
// o: {
// create: "abc", ...
// }
// ...
// }
fixUpInfo.collectionsToDrop.insert(*uuid);
return Status::OK();
}
case OplogEntry::CommandType::kDrop: {
// Example drop collection oplog entry
// {
// ts: ...,
// h: ...,
// op: "c",
// ns: "foo.$cmd",
// ui: BinData(...),
// o: {
// drop: "abc"
// }
// ...
// }
NamespaceString collectionNamespace(nss.getSisterNS(first.valuestr()));
// Registers the collection to be removed from the drop pending collection
// reaper and to be renamed from its drop pending namespace to original namespace.
fixUpInfo.recordRollingBackDrop(collectionNamespace, oplogEntry.getOpTime(), *uuid);
return Status::OK();
}
case OplogEntry::CommandType::kDropIndexes: {
// Example drop indexes objects
// o: {
// dropIndexes: "x",
// index: "x_1"
// }
// o2:{
// v: 2,
// key: { x: 1 },
// name: "x_1",
// ns: "foo.x"
// }
string ns = nss.db().toString() + '.' + first.valuestr();
string indexName;
auto status = bsonExtractStringField(obj, "index", &indexName);
if (!status.isOK()) {
LOGV2_FATAL_CONTINUE(21731,
"Missing index name in dropIndexes operation on rollback, "
"document: {oplogEntry}",
"Missing index name in dropIndexes operation on rollback",
"oplogEntry"_attr = redact(oplogEntry.toBSONForLogging()));
throw RSFatalException(
"Missing index name in dropIndexes operation on rollback.");
}
BSONObj obj2 = oplogEntry.getObject2().get().getOwned();
// Inserts the index name and the index spec of the index to be created into the map
// of index name and index specs that need to be created for the given collection.
//
// If this dropped index was a two-phase index build, we add it to the list to
// build in the foreground, without the IndexBuildsCoordinator, since we have no
// knowledge of the original build UUID information. If no start or commit oplog
// entries are rolled-back, this forces the index build to complete before rollback
// finishes.
//
// If we find by processing earlier oplog entries that the commit or abort
// entries are also rolled-back, we will instead rebuild the index with the
// Coordinator so it can wait for a replicated commit or abort.
fixUpInfo.indexesToCreate[*uuid].insert(
std::pair<std::string, BSONObj>(indexName, obj2));
return Status::OK();
}
case OplogEntry::CommandType::kCreateIndexes: {
// Example create indexes obj
// o:{
// createIndex: x,
// v: 2,
// key: { x: 1 },
// name: "x_1",
// }
string indexName;
auto status = bsonExtractStringField(obj, "name", &indexName);
if (!status.isOK()) {
LOGV2_FATAL_CONTINUE(
21732,
"Missing index name in createIndexes operation on rollback, "
"document: {oplogEntry}",
"Missing index name in createIndexes operation on rollback",
"oplogEntry"_attr = redact(oplogEntry.toBSONForLogging()));
throw RSFatalException(
"Missing index name in createIndexes operation on rollback.");
}
// Checks if a drop was previously done on this index. If so, we remove it from the
// indexesToCreate because a dropIndex and createIndex operation on the same
// collection for the same index cancel each other out. We do not record the
// createIndexes command in the fixUpInfo struct since applying both of these
// commands will lead to the same final state as not applying either of the
// commands. We only cancel out in the direction of [create] -> [drop] indexes
// because it is possible that in the [drop] -> [create] direction, when we create
// an index with the same name it may have a different index spec from that index
// that was previously dropped.
if (fixUpInfo.removeRedundantIndexCommands(*uuid, indexName)) {
return Status::OK();
}
// Inserts the index name to be dropped into the set of indexes that
// need to be dropped for the collection. Any errors dropping the index are ignored
// if it does not exist.
fixUpInfo.indexesToDrop[*uuid].insert(indexName);
return Status::OK();
}
case OplogEntry::CommandType::kStartIndexBuild: {
auto swIndexBuildOplogEntry = IndexBuildOplogEntry::parse(oplogEntry);
if (!swIndexBuildOplogEntry.isOK()) {
return {ErrorCodes::UnrecoverableRollbackError,
str::stream()
<< "Error parsing 'startIndexBuild' oplog entry: "
<< swIndexBuildOplogEntry.getStatus() << ": " << redact(obj)};
}
auto& indexBuildOplogEntry = swIndexBuildOplogEntry.getValue();
// If the index build has been committed or aborted, and the commit or abort
// oplog entry has also been rolled back, the index build will have been added
// to the set to be restarted. An index build may also be in the set to be restarted
// if it was in-progress and stopped before rollback.
// Remove it, and then add it to the set to be dropped. If the index has already
// been dropped by abort, then this is a no-op.
auto& buildsToRestart = fixUpInfo.indexBuildsToRestart;
auto buildUUID = indexBuildOplogEntry.buildUUID;
auto existingIt = buildsToRestart.find(buildUUID);
if (existingIt != buildsToRestart.end()) {
LOGV2_DEBUG(
21664,
2,
"Index build that was previously marked to be restarted will now be "
"dropped due to a rolled-back 'startIndexBuild' oplog entry: {buildUUID}",
"Index build that was previously marked to be restarted will now be "
"dropped due to a rolled-back 'startIndexBuild' oplog entry",
"buildUUID"_attr = buildUUID);
buildsToRestart.erase(existingIt);
// If the index build was committed or aborted, we must mark the index as
// needing to be dropped. Add each index to drop by name individually.
for (auto& indexName : indexBuildOplogEntry.indexNames) {
fixUpInfo.indexesToDrop[*uuid].insert(indexName);
}
// Intentionally allow this index build to be added to both 'indexesToDrop' and
// 'unfinishedIndexesToDrop', since we can not tell at this point if it is
// finished or not.
}
// If the index build was not committed or aborted, the index build is
// unfinished in the catalog will need to be dropped before any other collection
// operations.
for (auto& indexName : indexBuildOplogEntry.indexNames) {
fixUpInfo.unfinishedIndexesToDrop[*uuid].insert(indexName);
}
return Status::OK();
}
case OplogEntry::CommandType::kAbortIndexBuild: {
auto swIndexBuildOplogEntry = IndexBuildOplogEntry::parse(oplogEntry);
if (!swIndexBuildOplogEntry.isOK()) {
return {ErrorCodes::UnrecoverableRollbackError,
str::stream()
<< "Error parsing 'abortIndexBuild' oplog entry: "
<< swIndexBuildOplogEntry.getStatus() << ": " << redact(obj)};
}
auto& indexBuildOplogEntry = swIndexBuildOplogEntry.getValue();
auto& buildsToRestart = fixUpInfo.indexBuildsToRestart;
auto buildUUID = indexBuildOplogEntry.buildUUID;
invariant(buildsToRestart.find(buildUUID) == buildsToRestart.end(),
str::stream()
<< "Tried to restart an index build after rolling back an "
"'abortIndexBuild' oplog entry, but a build with the same "
"UUID is already marked to be restarted: "
<< buildUUID);
LOGV2_DEBUG(21665,
2,
"Index build will be restarted after a rolled-back 'abortIndexBuild': "
"{buildUUID}",
"Index build will be restarted after a rolled-back 'abortIndexBuild'",
"buildUUID"_attr = buildUUID);
IndexBuildDetails details{*uuid};
for (auto& spec : indexBuildOplogEntry.indexSpecs) {
invariant(spec.isOwned());
details.indexSpecs.emplace_back(spec);
}
buildsToRestart.insert({buildUUID, details});
return Status::OK();
}
case OplogEntry::CommandType::kCommitIndexBuild: {
auto swIndexBuildOplogEntry = IndexBuildOplogEntry::parse(oplogEntry);
if (!swIndexBuildOplogEntry.isOK()) {
return {ErrorCodes::UnrecoverableRollbackError,
str::stream()
<< "Error parsing 'commitIndexBuild' oplog entry: "
<< swIndexBuildOplogEntry.getStatus() << ": " << redact(obj)};
}
auto& indexBuildOplogEntry = swIndexBuildOplogEntry.getValue();
// If a dropIndexes oplog entry was already rolled-back, the index build needs to
// be restarted, but not committed. If the index is in the set to be created, then
// its drop was rolled-back and it should be removed.
auto& toCreate = fixUpInfo.indexesToCreate[*uuid];
for (auto& indexName : indexBuildOplogEntry.indexNames) {
auto existing = toCreate.find(indexName);
if (existing != toCreate.end()) {
toCreate.erase(existing);
}
}
// Add the index build to be restarted.
auto& buildsToRestart = fixUpInfo.indexBuildsToRestart;
auto buildUUID = indexBuildOplogEntry.buildUUID;
invariant(buildsToRestart.find(buildUUID) == buildsToRestart.end(),
str::stream()
<< "Tried to restart an index build after rolling back a "
"'commitIndexBuild' oplog entry, but a build with the same "
"UUID is already marked to be restarted: "
<< buildUUID);
LOGV2_DEBUG(21666,
2,
"Index build will be restarted after a rolled-back 'commitIndexBuild': "
"{buildUUID}",
"Index build will be restarted after a rolled-back 'commitIndexBuild'",
"buildUUID"_attr = buildUUID);
IndexBuildDetails details{*uuid};
for (auto& spec : indexBuildOplogEntry.indexSpecs) {
invariant(spec.isOwned());
details.indexSpecs.emplace_back(spec);
}
buildsToRestart.insert({buildUUID, details});
return Status::OK();
}
case OplogEntry::CommandType::kRenameCollection: {
// Example rename collection obj
// o:{
// renameCollection: "foo.x",
// to: "foo.y",
// stayTemp: false,
// dropTarget: BinData(...),
// }
// dropTarget will be false if no collection is dropped during the rename.
// The ui field will contain the UUID of the new collection that is created.
BSONObj cmd = obj;
std::string ns = first.valuestrsafe();
if (ns.empty()) {
static constexpr char message[] = "Collection name missing from oplog entry";
LOGV2(21667, message, "oplogEntry"_attr = redact(obj));
return Status(ErrorCodes::UnrecoverableRollbackError,
str::stream() << message << ": " << redact(obj));
}
// Checks if dropTarget is present. If it has a UUID value, we need to
// make sure to un-drop the collection that was dropped in the process
// of renaming.
if (auto dropTarget = obj.getField("dropTarget")) {
auto status =
fixUpInfo.recordDropTargetInfo(dropTarget, obj, oplogEntry.getOpTime());
if (!status.isOK()) {
return status;
}
}
RenameCollectionInfo info;
info.renameTo = NamespaceString(ns);
info.renameFrom = NamespaceString(obj.getStringField("to"));
// Checks if this collection has been renamed before within the same database.
// If it has been, update the renameFrom field of the RenameCollectionInfo
// that we will use to create the oplog entry necessary to rename the
// collection back to its original state.
auto collToRename = fixUpInfo.collectionsToRename.find(*uuid);
if (collToRename != fixUpInfo.collectionsToRename.end()) {
info.renameFrom = (*collToRename).second.renameFrom;
}
fixUpInfo.collectionsToRename[*uuid] = info;
// Because of the stayTemp field, we add any collections that have been renamed
// to collectionsToResyncMetadata to ensure that the collection is properly set
// as either a temporary or permanent collection.
fixUpInfo.collectionsToResyncMetadata.insert(*uuid);
return Status::OK();
}
case OplogEntry::CommandType::kDropDatabase: {
// Example drop database oplog entry
// {
// ts: ...,
// h: ...,
// op: "c",
// ns: "foo.$cmd",
// o:{
// "dropDatabase": 1
// }
// ...
// }
// Since we wait for all internal collection drops to be committed before recording
// a 'dropDatabase' oplog entry, this will always create an empty database.
// Creating an empty database doesn't mean anything, so we do nothing.
return Status::OK();
}
case OplogEntry::CommandType::kCollMod: {
for (auto field : obj) {
// Example collMod obj
// o:{
// collMod : "x",
// validationLevel : "off",
// index: {
// name: "indexName_1",
// expireAfterSeconds: 600
// }
// }
const auto modification = field.fieldNameStringData();
if (modification == "collMod") {
continue; // Skips the command name. The first field in the obj will be the
// command name.
}
if (modification == "validator" || modification == "validationAction" ||
modification == "validationLevel") {
fixUpInfo.collectionsToResyncMetadata.insert(*uuid);
continue;
}
// Some collMod fields cannot be rolled back, such as the index field.
static constexpr char message[] = "Cannot roll back a collMod command";
LOGV2_FATAL_CONTINUE(21733, message, "oplogEntry"_attr = redact(obj));
throw RSFatalException(message);
}
return Status::OK();
}
case OplogEntry::CommandType::kApplyOps: {
// Example Apply Ops oplog entry
//{
// op : "c",
// ns : admin.$cmd,
// o : {
// applyOps : [ {
// op : "u", // must be idempotent!
// ns : "test.x",
// ui : BinData(...),
// o2 : {
// _id : 1
// },
// o : {
// _id : 2
// }
// }]
// }
// }
// Additionally, for transactions, applyOps entries may be linked by their
// previousTransactionOpTimes. For those, we need to walk the chain and get to
// all the entries. We don't worry about the order that we walk the entries.
auto operations = first;
auto prevWriteOpTime = oplogEntry.getPrevWriteOpTimeInTransaction();
auto txnHistoryIter = prevWriteOpTime
? localOplog.makeTransactionHistoryIterator(*prevWriteOpTime)
: nullptr;
do {
if (operations.type() != Array) {
static constexpr char message[] =
"Expected applyOps argument to be an array";
LOGV2_FATAL_CONTINUE(
21734, message, "operations"_attr = redact(operations));
return Status(ErrorCodes::UnrecoverableRollbackError,
str::stream() << message << "; found " << redact(operations));
}
for (const auto& subopElement : operations.Array()) {
if (subopElement.type() != Object) {
static constexpr char message[] =
"Expected applyOps operations to be of Object type";
LOGV2_FATAL_CONTINUE(
21735, message, "operation"_attr = redact(subopElement));
return Status(ErrorCodes::UnrecoverableRollbackError,
str::stream()
<< message << ", but found " << redact(subopElement));
}
// In applyOps, the object contains an array of different oplog entries, we
// call
// updateFixUpInfoFromLocalOplogEntry here in order to record the
// information
// needed for rollback that is contained within the applyOps, creating a
// nested
// call.
auto subStatus = updateFixUpInfoFromLocalOplogEntry(
opCtx, localOplog, fixUpInfo, subopElement.Obj(), true);
if (!subStatus.isOK()) {
return subStatus;
}
}
if (!txnHistoryIter || !txnHistoryIter->hasNext())
break;
try {
auto nextApplyOps = txnHistoryIter->next(opCtx);
operations = nextApplyOps.getObject().firstElement();
} catch (const DBException& ex) {
// If we can't get the full transaction history, we can't roll back;
return {ErrorCodes::UnrecoverableRollbackError, ex.reason()};
}
} while (1);
return Status::OK();
}
case OplogEntry::CommandType::kAbortTransaction: {
return Status::OK();
}
default: {
static constexpr char message[] = "Can't roll back this command yet";
LOGV2_FATAL_CONTINUE(21736,
message,
"commandName"_attr = first.fieldName(),
"command"_attr = redact(obj));
throw RSFatalException(str::stream()
<< message << ": cmdname = " << first.fieldName());
}
}
}
// If we are inserting/updating/deleting a document in the oplog entry, we will update
// the doc._id field when we actually insert the docID into the docsToRefetch set.
DocID doc = DocID(fixedObj, BSONElement(), *uuid);
doc._id = oplogEntry.getIdElement();
if (doc._id.eoo()) {
static constexpr char message[] = "Cannot roll back op with no _id";
LOGV2_FATAL_CONTINUE(21737,
message,
"namespace"_attr = nss.ns(),
"oplogEntry"_attr = redact(oplogEntry.toBSONForLogging()));
throw RSFatalException(str::stream() << message << ". ns: " << nss.ns());
}
fixUpInfo.docsToRefetch.insert(doc);
return Status::OK();
}
namespace {
/**
* This must be called before making any changes to our local data and after fetching any
* information from the upstream node. If any information is fetched from the upstream node after we
* have written locally, the function must be called again.
*/
void checkRbidAndUpdateMinValid(OperationContext* opCtx,
const int rbid,
const RollbackSource& rollbackSource,
ReplicationProcess* replicationProcess) {
// It is important that the steps are performed in order to avoid racing with upstream
// rollbacks.
// 1. Gets the last doc in their oplog.
// 2. Gets their RBID and fail if it has changed.
// 3. Sets our minValid to the previously fetched OpTime of the top of their oplog.
const auto newMinValidDoc = rollbackSource.getLastOperation();
if (newMinValidDoc.isEmpty()) {
uasserted(40500, "rollback error newest oplog entry on source is missing or empty");
}
if (rbid != rollbackSource.getRollbackId()) {
// Our source rolled back so the data we received is not necessarily consistent.
uasserted(40508, "rollback rbid on source changed during rollback, canceling this attempt");
}
// We have items we are writing that aren't from a point-in-time. Thus, it is best not to come
// online until we get to that point in freshness. In other words, we do not transition from
// RECOVERING state to SECONDARY state until we have reached the minValid oplog entry.
OpTime minValid = fassert(40492, OpTime::parseFromOplogEntry(newMinValidDoc));
LOGV2(21668, "Setting minvalid to {minValid}", "Setting minvalid", "minValid"_attr = minValid);
// This method is only used with storage engines that do not support recover to stable
// timestamp. As a result, the timestamp on the 'appliedThrough' update does not matter.
invariant(!opCtx->getServiceContext()->getStorageEngine()->supportsRecoverToStableTimestamp());
replicationProcess->getConsistencyMarkers()->clearAppliedThrough(opCtx, {});
replicationProcess->getConsistencyMarkers()->setMinValid(opCtx, minValid);
if (MONGO_unlikely(rollbackHangThenFailAfterWritingMinValid.shouldFail())) {
// This log output is used in jstests so please leave it.
LOGV2(21669,
"rollback - rollbackHangThenFailAfterWritingMinValid fail point "
"enabled. Blocking until fail point is disabled.");
while (MONGO_unlikely(rollbackHangThenFailAfterWritingMinValid.shouldFail())) {
invariant(!globalInShutdownDeprecated()); // It is an error to shutdown while enabled.
mongo::sleepsecs(1);
}
uasserted(40502,
"failing rollback due to rollbackHangThenFailAfterWritingMinValid fail point");
}
}
/**
* Drops an index from the collection based on its name by removing it from the indexCatalog of the
* collection.
*/
void dropIndex(OperationContext* opCtx,
IndexCatalog* indexCatalog,
const string& indexName,
NamespaceString& nss) {
bool includeUnfinishedIndexes = true;
auto indexDescriptor =
indexCatalog->findIndexByName(opCtx, indexName, includeUnfinishedIndexes);
if (!indexDescriptor) {
LOGV2_WARNING(21725,
"Rollback failed to drop index {indexName} in {namespace}: index not found.",
"Rollback failed to drop index: index not found",
"indexName"_attr = indexName,
"namespace"_attr = nss.toString());
return;
}
auto entry = indexCatalog->getEntry(indexDescriptor);
if (entry->isReady(opCtx)) {
auto status = indexCatalog->dropIndex(opCtx, indexDescriptor);
if (!status.isOK()) {
LOGV2_ERROR(21738,
"Rollback failed to drop index {indexName} in {namespace}: {error}",
"Rollback failed to drop index",
"indexName"_attr = indexName,
"namespace"_attr = nss.toString(),
"error"_attr = redact(status));
}
} else {
auto status = indexCatalog->dropUnfinishedIndex(opCtx, indexDescriptor);
if (!status.isOK()) {
LOGV2_ERROR(
21739,
"Rollback failed to drop unfinished index {indexName} in {namespace}: {error}",
"Rollback failed to drop unfinished index",
"indexName"_attr = indexName,
"namespace"_attr = nss.toString(),
"error"_attr = redact(status));
}
}
}
/**
* Rolls back all createIndexes operations for the collection by dropping the
* created indexes.
*/
void rollbackCreateIndexes(OperationContext* opCtx, UUID uuid, std::set<std::string> indexNames) {
boost::optional<NamespaceString> nss =
CollectionCatalog::get(opCtx)->lookupNSSByUUID(opCtx, uuid);
invariant(nss);
Lock::DBLock dbLock(opCtx, nss->db(), MODE_X);
CollectionWriter collection(opCtx, uuid);
// If we cannot find the collection, we skip over dropping the index.
if (!collection) {
LOGV2_DEBUG(21670,
2,
"Cannot find the collection with uuid: {uuid} in CollectionCatalog during roll "
"back of a createIndexes command.",
"Cannot find the collection in CollectionCatalog during rollback of a "
"createIndexes command",
"uuid"_attr = uuid.toString());
return;
}
// If we cannot find the index catalog, we skip over dropping the index.
auto indexCatalog = collection->getIndexCatalog();
if (!indexCatalog) {
LOGV2_DEBUG(21671,
2,
"Cannot find the index catalog in collection with uuid: {uuid} during roll "
"back of a createIndexes command.",
"Cannot find the index catalog in collection during rollback of a "
"createIndexes command",
"uuid"_attr = uuid.toString());
return;
}
for (auto itIndex = indexNames.begin(); itIndex != indexNames.end(); itIndex++) {
const string& indexName = *itIndex;
LOGV2(21672,
"Dropping index in rollback for collection: {namespace}, UUID: {uuid}, index: "
"{indexName}",
"Dropping index in rollback",
"namespace"_attr = *nss,
"uuid"_attr = uuid,
"indexName"_attr = indexName);
WriteUnitOfWork wuow(opCtx);
dropIndex(opCtx, collection.getWritableCollection()->getIndexCatalog(), indexName, *nss);
wuow.commit();
LOGV2_DEBUG(21673,
1,
"Dropped index in rollback for collection: {namespace}, UUID: {uuid}, index: "
"{indexName}",
"Dropped index in rollback",
"namespace"_attr = *nss,
"uuid"_attr = uuid,
"indexName"_attr = indexName);
}
}
/**
* Rolls back all the dropIndexes operations for the collection by re-creating
* the indexes that were dropped.
*/
void rollbackDropIndexes(OperationContext* opCtx,
UUID uuid,
std::map<std::string, BSONObj> indexNames) {
auto catalog = CollectionCatalog::get(opCtx);
boost::optional<NamespaceString> nss = catalog->lookupNSSByUUID(opCtx, uuid);
invariant(nss);
Lock::DBLock dbLock(opCtx, nss->db(), MODE_IX);
Lock::CollectionLock collLock(opCtx, *nss, MODE_X);
CollectionPtr collection = catalog->lookupCollectionByNamespace(opCtx, *nss);
// If we cannot find the collection, we skip over dropping the index.
if (!collection) {
LOGV2_DEBUG(21674,
2,
"Cannot find the collection with uuid: {uuid}in CollectionCatalog during roll "
"back of a dropIndexes command.",
"Cannot find the collection in CollectionCatalog during rollback of a "
"dropIndexes command",
"uuid"_attr = uuid.toString());
return;
}
for (auto itIndex = indexNames.begin(); itIndex != indexNames.end(); itIndex++) {
const string indexName = itIndex->first;
BSONObj indexSpec = itIndex->second;
LOGV2(21675,
"Creating index in rollback for collection: {namespace}, UUID: {uuid}, index: "
"{indexName}",
"Creating index in rollback",
"namespace"_attr = *nss,
"uuid"_attr = uuid,
"indexName"_attr = indexName);
createIndexForApplyOps(opCtx, indexSpec, *nss, OplogApplication::Mode::kRecovering);