/
collection_catalog.cpp
2004 lines (1674 loc) · 79.6 KB
/
collection_catalog.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 "collection_catalog.h"
#include "mongo/db/catalog/database.h"
#include "mongo/db/catalog/uncommitted_catalog_updates.h"
#include "mongo/db/concurrency/exception_util.h"
#include "mongo/db/concurrency/lock_manager_defs.h"
#include "mongo/db/concurrency/resource_catalog.h"
#include "mongo/db/multitenancy_gen.h"
#include "mongo/db/server_feature_flags_gen.h"
#include "mongo/db/server_options.h"
#include "mongo/db/storage/kv/kv_engine.h"
#include "mongo/db/storage/recovery_unit.h"
#include "mongo/db/storage/snapshot_helper.h"
#include "mongo/db/storage/storage_parameters_gen.h"
#include "mongo/logv2/log.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/uuid.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kStorage
namespace mongo {
namespace {
struct LatestCollectionCatalog {
std::shared_ptr<CollectionCatalog> catalog = std::make_shared<CollectionCatalog>();
};
const ServiceContext::Decoration<LatestCollectionCatalog> getCatalog =
ServiceContext::declareDecoration<LatestCollectionCatalog>();
std::shared_ptr<CollectionCatalog> batchedCatalogWriteInstance;
const OperationContext::Decoration<std::shared_ptr<const CollectionCatalog>> stashedCatalog =
OperationContext::declareDecoration<std::shared_ptr<const CollectionCatalog>>();
/**
* Returns true if the collection is compatible with the read timestamp.
*/
bool isCollectionCompatible(std::shared_ptr<Collection> coll, Timestamp readTimestamp) {
if (!coll) {
return false;
}
boost::optional<Timestamp> minValidSnapshot = coll->getMinimumValidSnapshot();
if (!minValidSnapshot) {
// Collection is valid in all snapshots.
return true;
}
return readTimestamp >= *minValidSnapshot;
}
} // namespace
class IgnoreExternalViewChangesForDatabase {
public:
IgnoreExternalViewChangesForDatabase(OperationContext* opCtx, const DatabaseName& dbName)
: _opCtx(opCtx), _dbName(dbName) {
auto& uncommittedCatalogUpdates = UncommittedCatalogUpdates::get(_opCtx);
uncommittedCatalogUpdates.setIgnoreExternalViewChanges(_dbName, true);
}
~IgnoreExternalViewChangesForDatabase() {
auto& uncommittedCatalogUpdates = UncommittedCatalogUpdates::get(_opCtx);
uncommittedCatalogUpdates.setIgnoreExternalViewChanges(_dbName, false);
}
private:
OperationContext* _opCtx;
DatabaseName _dbName;
};
/**
* Publishes all uncommitted Collection actions registered on UncommittedCatalogUpdates to the
* catalog. All catalog updates are performed under the same write to ensure no external observer
* can see a partial update. Cleans up UncommittedCatalogUpdates on both commit and rollback to
* make it behave like a decoration on a WriteUnitOfWork.
*
* It needs to be registered with registerChangeForCatalogVisibility so other commit handlers can
* still write to this Collection.
*/
class CollectionCatalog::PublishCatalogUpdates final : public RecoveryUnit::Change {
public:
static constexpr size_t kNumStaticActions = 2;
static void setCollectionInCatalog(CollectionCatalog& catalog,
std::shared_ptr<Collection> collection,
boost::optional<Timestamp> commitTime) {
if (commitTime) {
collection->setMinimumValidSnapshot(*commitTime);
}
catalog._collections[collection->ns()] = collection;
catalog._catalog[collection->uuid()] = collection;
auto dbIdPair = std::make_pair(collection->ns().dbName(), collection->uuid());
catalog._orderedCollections[dbIdPair] = collection;
}
PublishCatalogUpdates(OperationContext* opCtx,
UncommittedCatalogUpdates& uncommittedCatalogUpdates)
: _uncommittedCatalogUpdates(uncommittedCatalogUpdates) {}
static void ensureRegisteredWithRecoveryUnit(
OperationContext* opCtx, UncommittedCatalogUpdates& UncommittedCatalogUpdates) {
if (opCtx->recoveryUnit()->hasRegisteredChangeForCatalogVisibility())
return;
opCtx->recoveryUnit()->registerChangeForCatalogVisibility(
std::make_unique<PublishCatalogUpdates>(opCtx, UncommittedCatalogUpdates));
}
void commit(OperationContext* opCtx, boost::optional<Timestamp> commitTime) override {
boost::container::small_vector<CollectionCatalog::CatalogWriteFn, kNumStaticActions>
writeJobs;
// Create catalog write jobs for all updates registered in this WriteUnitOfWork
auto entries = _uncommittedCatalogUpdates.releaseEntries();
for (auto&& entry : entries) {
switch (entry.action) {
case UncommittedCatalogUpdates::Entry::Action::kWritableCollection: {
writeJobs.push_back([collection = std::move(entry.collection),
commitTime](CollectionCatalog& catalog) {
setCollectionInCatalog(catalog, std::move(collection), commitTime);
});
break;
}
case UncommittedCatalogUpdates::Entry::Action::kRenamedCollection: {
writeJobs.push_back([opCtx,
&from = entry.nss,
&to = entry.renameTo,
commitTime](CollectionCatalog& catalog) {
// We just need to do modifications on 'from' here. 'to' is taken care
// of by a separate kWritableCollection entry.
catalog._collections.erase(from);
auto& resourceCatalog = ResourceCatalog::get(opCtx->getServiceContext());
resourceCatalog.remove({RESOURCE_COLLECTION, from}, from);
resourceCatalog.add({RESOURCE_COLLECTION, to}, to);
catalog._pushCatalogIdForRename(from, to, commitTime);
});
break;
}
case UncommittedCatalogUpdates::Entry::Action::kDroppedCollection: {
writeJobs.push_back([opCtx,
uuid = *entry.uuid(),
isDropPending = *entry.isDropPending,
commitTime](CollectionCatalog& catalog) {
catalog.deregisterCollection(opCtx, uuid, isDropPending, commitTime);
});
break;
}
case UncommittedCatalogUpdates::Entry::Action::kRecreatedCollection: {
writeJobs.push_back([opCtx,
collection = entry.collection,
uuid = *entry.externalUUID,
commitTime](CollectionCatalog& catalog) {
catalog.registerCollection(opCtx, uuid, std::move(collection), commitTime);
});
// Fallthrough to the createCollection case to finish committing the collection.
[[fallthrough]];
}
case UncommittedCatalogUpdates::Entry::Action::kCreatedCollection: {
// By this point, we may or may not have reserved an oplog slot for the
// collection creation.
// For example, multi-document transactions will only reserve the oplog slot at
// commit time. As a result, we may or may not have a reliable value to use to
// set the new collection's minimum visible snapshot until commit time.
// Pre-commit hooks do not presently have awareness of the commit timestamp, so
// we must update the minVisibleTimestamp with the appropriate value. This is
// fine because the collection should not be visible in the catalog until we
// call setCommitted(true).
writeJobs.push_back([coll = entry.collection.get(),
commitTime](CollectionCatalog& catalog) {
if (commitTime) {
coll->setMinimumVisibleSnapshot(commitTime.value());
coll->setMinimumValidSnapshot(commitTime.value());
}
catalog._pushCatalogIdForNSS(coll->ns(), coll->getCatalogId(), commitTime);
coll->setCommitted(true);
});
break;
}
case UncommittedCatalogUpdates::Entry::Action::kReplacedViewsForDatabase: {
writeJobs.push_back(
[dbName = entry.nss.dbName(),
&viewsForDb = entry.viewsForDb.value()](CollectionCatalog& catalog) {
catalog._replaceViewsForDatabase(dbName, std::move(viewsForDb));
});
break;
}
case UncommittedCatalogUpdates::Entry::Action::kAddViewResource: {
writeJobs.push_back([opCtx, &viewName = entry.nss](CollectionCatalog& catalog) {
ResourceCatalog::get(opCtx->getServiceContext())
.add({RESOURCE_COLLECTION, viewName}, viewName);
catalog.deregisterUncommittedView(viewName);
});
break;
}
case UncommittedCatalogUpdates::Entry::Action::kRemoveViewResource: {
writeJobs.push_back([opCtx, &viewName = entry.nss](CollectionCatalog& catalog) {
ResourceCatalog::get(opCtx->getServiceContext())
.remove({RESOURCE_COLLECTION, viewName}, viewName);
});
break;
}
case UncommittedCatalogUpdates::Entry::Action::kDroppedIndex: {
writeJobs.push_back(
[opCtx,
indexEntry = entry.indexEntry,
isDropPending = *entry.isDropPending](CollectionCatalog& catalog) {
catalog.deregisterIndex(opCtx, std::move(indexEntry), isDropPending);
});
break;
}
};
}
// Write all catalog updates to the catalog in the same write to ensure atomicity.
if (!writeJobs.empty()) {
CollectionCatalog::write(opCtx, [&writeJobs](CollectionCatalog& catalog) {
for (auto&& job : writeJobs) {
job(catalog);
}
});
}
}
void rollback(OperationContext* opCtx) override {
_uncommittedCatalogUpdates.releaseEntries();
}
private:
UncommittedCatalogUpdates& _uncommittedCatalogUpdates;
};
CollectionCatalog::iterator::iterator(OperationContext* opCtx,
const DatabaseName& dbName,
const CollectionCatalog& catalog)
: _opCtx(opCtx), _dbName(dbName), _catalog(&catalog) {
auto minUuid = UUID::parse("00000000-0000-0000-0000-000000000000").getValue();
_mapIter = _catalog->_orderedCollections.lower_bound(std::make_pair(_dbName, minUuid));
// Start with the first collection that is visible outside of its transaction.
while (!_exhausted() && !_mapIter->second->isCommitted()) {
_mapIter++;
}
if (!_exhausted()) {
_uuid = _mapIter->first.second;
}
}
CollectionCatalog::iterator::iterator(
OperationContext* opCtx,
std::map<std::pair<DatabaseName, UUID>, std::shared_ptr<Collection>>::const_iterator mapIter,
const CollectionCatalog& catalog)
: _opCtx(opCtx), _mapIter(mapIter), _catalog(&catalog) {}
CollectionCatalog::iterator::value_type CollectionCatalog::iterator::operator*() {
if (_exhausted()) {
return CollectionPtr();
}
return {
_opCtx, _mapIter->second.get(), LookupCollectionForYieldRestore(_mapIter->second->ns())};
}
Collection* CollectionCatalog::iterator::getWritableCollection(OperationContext* opCtx) {
return CollectionCatalog::get(opCtx)->lookupCollectionByUUIDForMetadataWrite(
opCtx, operator*()->uuid());
}
boost::optional<UUID> CollectionCatalog::iterator::uuid() {
return _uuid;
}
CollectionCatalog::iterator CollectionCatalog::iterator::operator++() {
_mapIter++;
// Skip any collections that are not yet visible outside of their respective transactions.
while (!_exhausted() && !_mapIter->second->isCommitted()) {
_mapIter++;
}
if (_exhausted()) {
// If the iterator is at the end of the map or now points to an entry that does not
// correspond to the correct database.
_mapIter = _catalog->_orderedCollections.end();
_uuid = boost::none;
return *this;
}
_uuid = _mapIter->first.second;
return *this;
}
CollectionCatalog::iterator CollectionCatalog::iterator::operator++(int) {
auto oldPosition = *this;
++(*this);
return oldPosition;
}
bool CollectionCatalog::iterator::operator==(const iterator& other) const {
invariant(_catalog == other._catalog);
if (other._mapIter == _catalog->_orderedCollections.end()) {
return _uuid == boost::none;
}
return _uuid == other._uuid;
}
bool CollectionCatalog::iterator::operator!=(const iterator& other) const {
return !(*this == other);
}
bool CollectionCatalog::iterator::_exhausted() {
return _mapIter == _catalog->_orderedCollections.end() || _mapIter->first.first != _dbName;
}
std::shared_ptr<const CollectionCatalog> CollectionCatalog::get(ServiceContext* svcCtx) {
return atomic_load(&getCatalog(svcCtx).catalog);
}
std::shared_ptr<const CollectionCatalog> CollectionCatalog::get(OperationContext* opCtx) {
// If there is a batched catalog write ongoing and we are the one doing it return this instance
// so we can observe our own writes. There may be other callers that reads the CollectionCatalog
// without any locks, they must see the immutable regular instance.
if (batchedCatalogWriteInstance && opCtx->lockState()->isW()) {
return batchedCatalogWriteInstance;
}
const auto& stashed = stashedCatalog(opCtx);
if (stashed)
return stashed;
return get(opCtx->getServiceContext());
}
void CollectionCatalog::stash(OperationContext* opCtx,
std::shared_ptr<const CollectionCatalog> catalog) {
stashedCatalog(opCtx) = std::move(catalog);
}
void CollectionCatalog::write(ServiceContext* svcCtx, CatalogWriteFn job) {
// We should never have ongoing batching here. When batching is in progress the caller should
// use the overload with OperationContext so we can verify that the global exlusive lock is
// being held.
invariant(!batchedCatalogWriteInstance);
// It is potentially expensive to copy the collection catalog so we batch the operations by only
// having one concurrent thread copying the catalog and executing all the write jobs.
struct JobEntry {
JobEntry(CatalogWriteFn write) : job(std::move(write)) {}
CatalogWriteFn job;
struct CompletionInfo {
// Used to wait for job to complete by worker thread
Mutex mutex;
stdx::condition_variable cv;
// Exception storage if we threw during job execution, so we can transfer the exception
// back to the calling thread
std::exception_ptr exception;
// The job is completed when the catalog we modified has been committed back to the
// storage or if we threw during its execution
bool completed = false;
};
// Shared state for completion info as JobEntry's gets deleted when we are finished
// executing. No shared state means that this job belongs to the same thread executing them.
std::shared_ptr<CompletionInfo> completion;
};
static std::list<JobEntry> queue;
static bool workerExists = false;
static Mutex mutex =
MONGO_MAKE_LATCH("CollectionCatalog::write"); // Protecting the two globals above
invariant(job);
// Current batch of jobs to execute
std::list<JobEntry> pending;
{
stdx::unique_lock lock(mutex);
queue.emplace_back(std::move(job));
// If worker already exists, then wait on our condition variable until the job is completed
if (workerExists) {
auto completion = std::make_shared<JobEntry::CompletionInfo>();
queue.back().completion = completion;
lock.unlock();
stdx::unique_lock completionLock(completion->mutex);
const bool& completed = completion->completed;
completion->cv.wait(completionLock, [&completed]() { return completed; });
// Throw any exception that was caught during execution of our job. Make sure we destroy
// the exception_ptr on the same thread that throws the exception to avoid a data race
// between destroying the exception_ptr and reading the exception.
auto ex = std::move(completion->exception);
if (ex)
std::rethrow_exception(ex);
return;
}
// No worker existed, then we take this responsibility
workerExists = true;
pending.splice(pending.end(), queue);
}
// Implementation for thread with worker responsibility below, only one thread at a time can be
// in here. Keep track of completed jobs so we can notify them when we've written back the
// catalog to storage
std::list<JobEntry> completed;
std::exception_ptr myException;
auto& storage = getCatalog(svcCtx);
// hold onto base so if we need to delete it we can do it outside of the lock
auto base = atomic_load(&storage.catalog);
// copy the collection catalog, this could be expensive, but we will only have one pending
// collection in flight at a given time
auto clone = std::make_shared<CollectionCatalog>(*base);
// Execute jobs until we drain the queue
while (true) {
for (auto&& current : pending) {
// Store any exception thrown during job execution so we can notify the calling thread
try {
current.job(*clone);
} catch (...) {
if (current.completion)
current.completion->exception = std::current_exception();
else
myException = std::current_exception();
}
}
// Transfer the jobs we just executed to the completed list
completed.splice(completed.end(), pending);
stdx::lock_guard lock(mutex);
if (queue.empty()) {
// Queue is empty, store catalog and relinquish responsibility of being worker thread
atomic_store(&storage.catalog, std::move(clone));
workerExists = false;
break;
}
// Transfer jobs in queue to the pending list
pending.splice(pending.end(), queue);
}
for (auto&& entry : completed) {
if (!entry.completion) {
continue;
}
stdx::lock_guard completionLock(entry.completion->mutex);
entry.completion->completed = true;
entry.completion->cv.notify_one();
}
LOGV2_DEBUG(
5255601, 1, "Finished writing to the CollectionCatalog", "jobs"_attr = completed.size());
if (myException)
std::rethrow_exception(myException);
}
void CollectionCatalog::write(OperationContext* opCtx,
std::function<void(CollectionCatalog&)> job) {
// If global MODE_X lock are held we can re-use a cloned CollectionCatalog instance when
// 'batchedCatalogWriteInstance' is set. Make sure we are the one holding the write lock.
if (batchedCatalogWriteInstance) {
invariant(opCtx->lockState()->isW());
job(*batchedCatalogWriteInstance);
return;
}
write(opCtx->getServiceContext(), std::move(job));
}
Status CollectionCatalog::createView(OperationContext* opCtx,
const NamespaceString& viewName,
const NamespaceString& viewOn,
const BSONArray& pipeline,
const BSONObj& collation,
const ViewsForDatabase::PipelineValidatorFn& pipelineValidator,
const ViewUpsertMode insertViewMode) const {
// A view document direct write can occur via the oplog application path, which may only hold a
// lock on the collection being updated (the database views collection).
invariant(insertViewMode == ViewUpsertMode::kAlreadyDurableView ||
opCtx->lockState()->isCollectionLockedForMode(viewName, MODE_IX));
invariant(opCtx->lockState()->isCollectionLockedForMode(
NamespaceString(viewName.dbName(), NamespaceString::kSystemDotViewsCollectionName),
MODE_X));
invariant(_viewsForDatabase.contains(viewName.dbName()));
const ViewsForDatabase& viewsForDb = *_getViewsForDatabase(opCtx, viewName.dbName());
auto& uncommittedCatalogUpdates = UncommittedCatalogUpdates::get(opCtx);
if (uncommittedCatalogUpdates.shouldIgnoreExternalViewChanges(viewName.dbName())) {
return Status::OK();
}
if (viewName.db() != viewOn.db())
return Status(ErrorCodes::BadValue,
"View must be created on a view or collection in the same database");
if (viewsForDb.lookup(viewName) || _collections.contains(viewName))
return Status(ErrorCodes::NamespaceExists, "Namespace already exists");
if (!NamespaceString::validCollectionName(viewOn.coll()))
return Status(ErrorCodes::InvalidNamespace,
str::stream() << "invalid name for 'viewOn': " << viewOn.coll());
auto collator = ViewsForDatabase::parseCollator(opCtx, collation);
if (!collator.isOK())
return collator.getStatus();
Status result = Status::OK();
{
IgnoreExternalViewChangesForDatabase ignore(opCtx, viewName.dbName());
result = _createOrUpdateView(opCtx,
viewName,
viewOn,
pipeline,
pipelineValidator,
std::move(collator.getValue()),
ViewsForDatabase{viewsForDb},
insertViewMode);
}
return result;
}
Status CollectionCatalog::modifyView(
OperationContext* opCtx,
const NamespaceString& viewName,
const NamespaceString& viewOn,
const BSONArray& pipeline,
const ViewsForDatabase::PipelineValidatorFn& pipelineValidator) const {
invariant(opCtx->lockState()->isCollectionLockedForMode(viewName, MODE_X));
invariant(opCtx->lockState()->isCollectionLockedForMode(
NamespaceString(viewName.dbName(), NamespaceString::kSystemDotViewsCollectionName),
MODE_X));
invariant(_viewsForDatabase.contains(viewName.dbName()));
const ViewsForDatabase& viewsForDb = *_getViewsForDatabase(opCtx, viewName.dbName());
if (viewName.db() != viewOn.db())
return Status(ErrorCodes::BadValue,
"View must be created on a view or collection in the same database");
auto viewPtr = viewsForDb.lookup(viewName);
if (!viewPtr)
return Status(ErrorCodes::NamespaceNotFound,
str::stream() << "cannot modify missing view " << viewName.ns());
if (!NamespaceString::validCollectionName(viewOn.coll()))
return Status(ErrorCodes::InvalidNamespace,
str::stream() << "invalid name for 'viewOn': " << viewOn.coll());
Status result = Status::OK();
{
IgnoreExternalViewChangesForDatabase ignore(opCtx, viewName.dbName());
result = _createOrUpdateView(opCtx,
viewName,
viewOn,
pipeline,
pipelineValidator,
CollatorInterface::cloneCollator(viewPtr->defaultCollator()),
ViewsForDatabase{viewsForDb},
ViewUpsertMode::kUpdateView);
}
return result;
}
Status CollectionCatalog::dropView(OperationContext* opCtx, const NamespaceString& viewName) const {
invariant(opCtx->lockState()->isCollectionLockedForMode(viewName, MODE_IX));
invariant(opCtx->lockState()->isCollectionLockedForMode(
NamespaceString(viewName.dbName(), NamespaceString::kSystemDotViewsCollectionName),
MODE_X));
invariant(_viewsForDatabase.contains(viewName.dbName()));
const ViewsForDatabase& viewsForDb = *_getViewsForDatabase(opCtx, viewName.dbName());
viewsForDb.requireValidCatalog();
// Make sure the view exists before proceeding.
if (auto viewPtr = viewsForDb.lookup(viewName); !viewPtr) {
return {ErrorCodes::NamespaceNotFound,
str::stream() << "cannot drop missing view: " << viewName.ns()};
}
Status result = Status::OK();
{
IgnoreExternalViewChangesForDatabase ignore(opCtx, viewName.dbName());
ViewsForDatabase writable{viewsForDb};
writable.durable->remove(opCtx, viewName);
writable.viewGraph.remove(viewName);
writable.viewMap.erase(viewName);
writable.stats = {};
// Reload the view catalog with the changes applied.
result = writable.reload(opCtx);
if (result.isOK()) {
auto& uncommittedCatalogUpdates = UncommittedCatalogUpdates::get(opCtx);
uncommittedCatalogUpdates.removeView(viewName);
uncommittedCatalogUpdates.replaceViewsForDatabase(viewName.dbName(),
std::move(writable));
PublishCatalogUpdates::ensureRegisteredWithRecoveryUnit(opCtx,
uncommittedCatalogUpdates);
}
}
return result;
}
Status CollectionCatalog::reloadViews(OperationContext* opCtx, const DatabaseName& dbName) const {
invariant(opCtx->lockState()->isCollectionLockedForMode(
NamespaceString(dbName, NamespaceString::kSystemDotViewsCollectionName), MODE_IS));
auto& uncommittedCatalogUpdates = UncommittedCatalogUpdates::get(opCtx);
if (uncommittedCatalogUpdates.shouldIgnoreExternalViewChanges(dbName)) {
return Status::OK();
}
LOGV2_DEBUG(22546, 1, "Reloading view catalog for database", "db"_attr = dbName.toString());
// Create a copy of the ViewsForDatabase instance to modify it. Reset the views for this
// database, but preserve the DurableViewCatalog pointer.
auto it = _viewsForDatabase.find(dbName);
invariant(it != _viewsForDatabase.end());
ViewsForDatabase viewsForDb{it->second.durable};
viewsForDb.valid = false;
viewsForDb.viewGraphNeedsRefresh = true;
viewsForDb.viewMap.clear();
viewsForDb.stats = {};
auto status = viewsForDb.reload(opCtx);
CollectionCatalog::write(opCtx, [&](CollectionCatalog& catalog) {
catalog._replaceViewsForDatabase(dbName, std::move(viewsForDb));
});
return status;
}
std::shared_ptr<Collection> CollectionCatalog::openCollection(OperationContext* opCtx,
const NamespaceString& nss,
Timestamp readTimestamp) const {
if (!feature_flags::gPointInTimeCatalogLookups.isEnabledAndIgnoreFCV()) {
return nullptr;
}
auto catalogId = lookupCatalogIdByNSS(nss, readTimestamp);
if (!catalogId) {
return nullptr;
}
auto catalogEntry = DurableCatalog::get(opCtx)->getParsedCatalogEntry(opCtx, *catalogId);
if (!catalogEntry) {
// Treat the collection as non-existent at a point-in-time the same as not-existent at
// latest.
return nullptr;
}
const auto& collectionOptions = catalogEntry->metadata->options;
// Check if the collection already exists in the catalog and if it's compatible with the read
// timestamp.
std::shared_ptr<Collection> latestColl = _lookupCollectionByUUID(*collectionOptions.uuid);
if (isCollectionCompatible(latestColl, readTimestamp)) {
return latestColl;
}
// Check if the collection is drop pending, not expired, and compatible with the read timestamp.
std::shared_ptr<Collection> dropPendingColl = [&]() -> std::shared_ptr<Collection> {
auto dropPendingIt = _dropPendingCollection.find(catalogEntry->ident);
if (dropPendingIt == _dropPendingCollection.end()) {
return nullptr;
}
return dropPendingIt->second.lock();
}();
if (isCollectionCompatible(dropPendingColl, readTimestamp)) {
return dropPendingColl;
}
// Neither the latest collection or drop pending collection exist, or were compatible with the
// read timestamp. We'll need to instantiate a new Collection instance.
if (latestColl || dropPendingColl) {
// If the latest or drop pending collection exists, instantiate a new collection using
// their shared state.
LOGV2_DEBUG(6825400,
1,
"Instantiating a collection using shared state",
logAttrs(nss),
"ident"_attr = catalogEntry->ident,
"md"_attr = catalogEntry->metadata->toBSON(),
"timestamp"_attr = readTimestamp);
std::shared_ptr<Collection> collToReturn = Collection::Factory::get(opCtx)->make(
opCtx, nss, *catalogId, catalogEntry->metadata, /*rs=*/nullptr);
Status status = collToReturn->initFromExisting(
opCtx, latestColl ? latestColl : dropPendingColl, readTimestamp);
if (!status.isOK()) {
LOGV2_DEBUG(
6857100, 1, "Failed to instantiate collection", "reason"_attr = status.reason());
return nullptr;
}
return collToReturn;
}
// The ident is expired, but it still may not have been dropped by the reaper. Try to mark it as
// in use.
auto storageEngine = opCtx->getServiceContext()->getStorageEngine();
auto newIdent = storageEngine->markIdentInUse(catalogEntry->ident);
if (!newIdent) {
LOGV2_DEBUG(6857101,
1,
"Collection ident is being dropped or is already dropped",
"ident"_attr = catalogEntry->ident);
return nullptr;
}
// Instantiate a new collection without any shared state.
LOGV2_DEBUG(6825401,
1,
"Instantiating a new collection",
logAttrs(nss),
"ident"_attr = catalogEntry->ident,
"md"_attr = catalogEntry->metadata->toBSON(),
"timestamp"_attr = readTimestamp);
std::unique_ptr<RecordStore> rs =
opCtx->getServiceContext()->getStorageEngine()->getEngine()->getRecordStore(
opCtx, nss, catalogEntry->ident, collectionOptions);
// Set the ident to the one returned by the ident reaper. This is to prevent the ident from
// being dropping prematurely.
rs->setIdent(std::move(newIdent));
std::shared_ptr<Collection> collToReturn = Collection::Factory::get(opCtx)->make(
opCtx, nss, *catalogId, catalogEntry->metadata, std::move(rs));
Status status = collToReturn->initFromExisting(opCtx, /*collection=*/nullptr, readTimestamp);
if (!status.isOK()) {
LOGV2_DEBUG(
6857102, 1, "Failed to instantiate collection", "reason"_attr = status.reason());
return nullptr;
}
return collToReturn;
}
std::shared_ptr<IndexCatalogEntry> CollectionCatalog::findDropPendingIndex(
const std::string& ident) const {
auto it = _dropPendingIndex.find(ident);
if (it == _dropPendingIndex.end()) {
return nullptr;
}
return it->second.lock();
}
void CollectionCatalog::onCreateCollection(OperationContext* opCtx,
std::shared_ptr<Collection> coll) const {
invariant(coll);
auto& uncommittedCatalogUpdates = UncommittedCatalogUpdates::get(opCtx);
auto [found, existingColl, newColl] =
UncommittedCatalogUpdates::lookupCollection(opCtx, coll->ns());
uassert(31370,
str::stream() << "collection already exists. ns: " << coll->ns(),
existingColl == nullptr);
// When we already have a drop and recreate the collection, we want to seamlessly swap out the
// collection in the catalog under a single critical section. So we register the recreated
// collection in the same commit handler that we unregister the dropped collection (as opposed
// to registering the new collection inside of a preCommitHook).
if (found) {
uncommittedCatalogUpdates.recreateCollection(opCtx, std::move(coll));
} else {
uncommittedCatalogUpdates.createCollection(opCtx, std::move(coll));
}
PublishCatalogUpdates::ensureRegisteredWithRecoveryUnit(opCtx, uncommittedCatalogUpdates);
}
void CollectionCatalog::onCollectionRename(OperationContext* opCtx,
Collection* coll,
const NamespaceString& fromCollection) const {
invariant(coll);
auto& uncommittedCatalogUpdates = UncommittedCatalogUpdates::get(opCtx);
uncommittedCatalogUpdates.renameCollection(coll, fromCollection);
}
void CollectionCatalog::dropIndex(OperationContext* opCtx,
const NamespaceString& nss,
std::shared_ptr<IndexCatalogEntry> indexEntry,
bool isDropPending) const {
auto& uncommittedCatalogUpdates = UncommittedCatalogUpdates::get(opCtx);
uncommittedCatalogUpdates.dropIndex(nss, std::move(indexEntry), isDropPending);
PublishCatalogUpdates::ensureRegisteredWithRecoveryUnit(opCtx, uncommittedCatalogUpdates);
}
void CollectionCatalog::dropCollection(OperationContext* opCtx,
Collection* coll,
bool isDropPending) const {
invariant(coll);
auto& uncommittedCatalogUpdates = UncommittedCatalogUpdates::get(opCtx);
uncommittedCatalogUpdates.dropCollection(coll, isDropPending);
// Requesting a writable collection normally ensures we have registered PublishCatalogUpdates
// with the recovery unit. However, when the writable Collection was requested in Inplace mode
// (or is the oplog) this is not the case. So make sure we are registered in all cases.
PublishCatalogUpdates::ensureRegisteredWithRecoveryUnit(opCtx, uncommittedCatalogUpdates);
}
void CollectionCatalog::onOpenDatabase(OperationContext* opCtx,
const DatabaseName& dbName,
ViewsForDatabase&& viewsForDb) {
invariant(opCtx->lockState()->isDbLockedForMode(dbName, MODE_IS));
uassert(ErrorCodes::AlreadyInitialized,
str::stream() << "Database " << dbName << " is already initialized",
_viewsForDatabase.find(dbName) == _viewsForDatabase.end());
_viewsForDatabase[dbName] = std::move(viewsForDb);
}
void CollectionCatalog::onCloseDatabase(OperationContext* opCtx, DatabaseName dbName) {
invariant(opCtx->lockState()->isDbLockedForMode(dbName, MODE_X));
ResourceCatalog::get(opCtx->getServiceContext()).remove({RESOURCE_DATABASE, dbName}, dbName);
_viewsForDatabase.erase(dbName);
}
void CollectionCatalog::onCloseCatalog() {
if (_shadowCatalog) {
return;
}
_shadowCatalog.emplace();
for (auto& entry : _catalog)
_shadowCatalog->insert({entry.first, entry.second->ns()});
}
void CollectionCatalog::onOpenCatalog() {
invariant(_shadowCatalog);
_shadowCatalog.reset();
++_epoch;
}
uint64_t CollectionCatalog::getEpoch() const {
return _epoch;
}
std::shared_ptr<const Collection> CollectionCatalog::lookupCollectionByUUIDForRead(
OperationContext* opCtx, const UUID& uuid) const {
auto [found, uncommittedColl, newColl] =
UncommittedCatalogUpdates::lookupCollection(opCtx, uuid);
if (uncommittedColl) {
return uncommittedColl;
}
auto coll = _lookupCollectionByUUID(uuid);
return (coll && coll->isCommitted()) ? coll : nullptr;
}
Collection* CollectionCatalog::lookupCollectionByUUIDForMetadataWrite(OperationContext* opCtx,
const UUID& uuid) const {
auto& uncommittedCatalogUpdates = UncommittedCatalogUpdates::get(opCtx);
auto [found, uncommittedPtr, newColl] =
UncommittedCatalogUpdates::lookupCollection(opCtx, uuid);
if (found) {
// The uncommittedPtr will be nullptr in the case of drop.
if (!uncommittedPtr.get()) {
return nullptr;
}
auto nss = uncommittedPtr->ns();
// If the collection is newly created, invariant on the collection being locked in MODE_IX.
invariant(!newColl || opCtx->lockState()->isCollectionLockedForMode(nss, MODE_IX),
nss.toString());
return uncommittedPtr.get();
}
std::shared_ptr<Collection> coll = _lookupCollectionByUUID(uuid);
if (!coll || !coll->isCommitted())
return nullptr;
if (coll->ns().isOplog())
return coll.get();
invariant(opCtx->lockState()->isCollectionLockedForMode(coll->ns(), MODE_X));
// Skip cloning and return directly if allowed.
if (_alreadyClonedForBatchedWriter(coll)) {
return coll.get();
}
auto cloned = coll->clone();
auto ptr = cloned.get();
// If we are in a batch write, set this Collection instance in the batched catalog write
// instance. We don't want to store as uncommitted in this case as we need to observe the write
// on the thread doing the batch write and it would trigger the regular path where we do a
// copy-on-write on the catalog when committing.
if (_isCatalogBatchWriter()) {
// Do not update min valid timestamp in batched write as the write is not corresponding to
// an oplog entry. If the write require an update to this timestamp it is the responsibility
// of the user.
PublishCatalogUpdates::setCollectionInCatalog(
*batchedCatalogWriteInstance, std::move(cloned), boost::none);
return ptr;
}
uncommittedCatalogUpdates.writableCollection(std::move(cloned));
PublishCatalogUpdates::ensureRegisteredWithRecoveryUnit(opCtx, uncommittedCatalogUpdates);
return ptr;
}
CollectionPtr CollectionCatalog::lookupCollectionByUUID(OperationContext* opCtx, UUID uuid) const {
// If UUID is managed by UncommittedCatalogUpdates (but not newly created) return the pointer
// which will be nullptr in case of a drop.
auto [found, uncommittedPtr, newColl] =
UncommittedCatalogUpdates::lookupCollection(opCtx, uuid);
if (found) {
return uncommittedPtr.get();
}
auto coll = _lookupCollectionByUUID(uuid);
return (coll && coll->isCommitted())
? CollectionPtr(opCtx, coll.get(), LookupCollectionForYieldRestore(coll->ns()))
: CollectionPtr();
}
bool CollectionCatalog::isCollectionAwaitingVisibility(UUID uuid) const {
auto coll = _lookupCollectionByUUID(uuid);
return coll && !coll->isCommitted();
}
std::shared_ptr<Collection> CollectionCatalog::_lookupCollectionByUUID(UUID uuid) const {
auto foundIt = _catalog.find(uuid);
return foundIt == _catalog.end() ? nullptr : foundIt->second;
}
std::shared_ptr<const Collection> CollectionCatalog::lookupCollectionByNamespaceForRead(
OperationContext* opCtx, const NamespaceString& nss) const {
auto [found, uncommittedColl, newColl] =
UncommittedCatalogUpdates::lookupCollection(opCtx, nss);
if (uncommittedColl) {
return uncommittedColl;
}
// Report the drop or rename as nothing new was created.
if (found) {
return nullptr;
}
auto it = _collections.find(nss);
auto coll = (it == _collections.end() ? nullptr : it->second);