/
collection_impl.cpp
1569 lines (1309 loc) · 63.1 KB
/
collection_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.
*/
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kStorage
#include "mongo/platform/basic.h"
#include "mongo/db/catalog/collection_impl.h"
#include "mongo/base/counter.h"
#include "mongo/base/init.h"
#include "mongo/base/owned_pointer_map.h"
#include "mongo/bson/ordering.h"
#include "mongo/bson/simple_bsonelement_comparator.h"
#include "mongo/bson/simple_bsonobj_comparator.h"
#include "mongo/db/catalog/collection_catalog.h"
#include "mongo/db/catalog/collection_options.h"
#include "mongo/db/catalog/document_validation.h"
#include "mongo/db/catalog/index_catalog_impl.h"
#include "mongo/db/catalog/index_consistency.h"
#include "mongo/db/catalog/index_key_validate.h"
#include "mongo/db/clientcursor.h"
#include "mongo/db/commands/server_status_metric.h"
#include "mongo/db/concurrency/d_concurrency.h"
#include "mongo/db/concurrency/write_conflict_exception.h"
#include "mongo/db/curop.h"
#include "mongo/db/index/index_access_method.h"
#include "mongo/db/index/index_descriptor.h"
#include "mongo/db/keypattern.h"
#include "mongo/db/matcher/doc_validation_error.h"
#include "mongo/db/matcher/expression_always_boolean.h"
#include "mongo/db/matcher/expression_parser.h"
#include "mongo/db/op_observer.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/ops/update_request.h"
#include "mongo/db/query/collation/collator_factory_interface.h"
#include "mongo/db/query/collation/collator_interface.h"
#include "mongo/db/query/collection_query_info.h"
#include "mongo/db/query/internal_plans.h"
#include "mongo/db/record_id_helpers.h"
#include "mongo/db/repl/oplog.h"
#include "mongo/db/repl/replication_coordinator.h"
#include "mongo/db/server_options.h"
#include "mongo/db/server_recovery.h"
#include "mongo/db/service_context.h"
#include "mongo/db/storage/durable_catalog.h"
#include "mongo/db/storage/key_string.h"
#include "mongo/db/storage/record_store.h"
#include "mongo/db/ttl_collection_cache.h"
#include "mongo/db/update/update_driver.h"
#include "mongo/db/auth/user_document_parser.h" // XXX-ANDY
#include "mongo/logv2/log.h"
#include "mongo/rpc/object_check.h"
#include "mongo/util/fail_point.h"
namespace mongo {
namespace {
// This fail point injects insertion failures for all collections unless a collection name is
// provided in the optional data object during configuration:
// data: {
// collectionNS: <fully-qualified collection namespace>,
// }
MONGO_FAIL_POINT_DEFINE(failCollectionInserts);
// Used to pause after inserting collection data and calling the opObservers. Inserts to
// replicated collections that are not part of a multi-statement transaction will have generated
// their OpTime and oplog entry. Supports parameters to limit pause by namespace and by _id
// of first data item in an insert (must be of type string):
// data: {
// collectionNS: <fully-qualified collection namespace>,
// first_id: <string>
// }
MONGO_FAIL_POINT_DEFINE(hangAfterCollectionInserts);
// This fail point throws a WriteConflictException after a successful call to insertRecords.
MONGO_FAIL_POINT_DEFINE(failAfterBulkLoadDocInsert);
// This fail point allows collections to be given malformed validator. A malformed validator
// will not (and cannot) be enforced but it will be persisted.
MONGO_FAIL_POINT_DEFINE(allowSettingMalformedCollectionValidators);
// This fail point introduces corruption to documents during insert.
MONGO_FAIL_POINT_DEFINE(corruptDocumentOnInsert);
/**
* Checks the 'failCollectionInserts' fail point at the beginning of an insert operation to see if
* the insert should fail. Returns Status::OK if The function should proceed with the insertion.
* Otherwise, the function should fail and return early with the error Status.
*/
Status checkFailCollectionInsertsFailPoint(const NamespaceString& ns, const BSONObj& firstDoc) {
Status s = Status::OK();
failCollectionInserts.executeIf(
[&](const BSONObj& data) {
const std::string msg = str::stream()
<< "Failpoint (failCollectionInserts) has been enabled (" << data
<< "), so rejecting insert (first doc): " << firstDoc;
LOGV2(20287,
"Failpoint (failCollectionInserts) has been enabled, so rejecting insert",
"data"_attr = data,
"document"_attr = firstDoc);
s = {ErrorCodes::FailPointEnabled, msg};
},
[&](const BSONObj& data) {
// If the failpoint specifies no collection or matches the existing one, fail.
const auto collElem = data["collectionNS"];
return !collElem || ns.ns() == collElem.str();
});
return s;
}
// Uses the collator factory to convert the BSON representation of a collator to a
// CollatorInterface. Returns null if the BSONObj is empty. We expect the stored collation to be
// valid, since it gets validated on collection create.
std::unique_ptr<CollatorInterface> parseCollation(OperationContext* opCtx,
const NamespaceString& nss,
BSONObj collationSpec) {
if (collationSpec.isEmpty()) {
return {nullptr};
}
auto collator =
CollatorFactoryInterface::get(opCtx->getServiceContext())->makeFromBSON(collationSpec);
// If the collection's default collator has a version not currently supported by our ICU
// integration, shut down the server. Errors other than IncompatibleCollationVersion should not
// be possible, so these are an invariant rather than fassert.
if (collator == ErrorCodes::IncompatibleCollationVersion) {
LOGV2(20288,
"Collection {nss} has a default collation which is incompatible with this version: "
"{collationSpec}",
"Collection has a default collation incompatible with this version",
"namespace"_attr = nss,
"collationSpec"_attr = collationSpec);
fassertFailedNoTrace(40144);
}
invariant(collator.getStatus());
return std::move(collator.getValue());
}
Status checkValidatorCanBeUsedOnNs(const BSONObj& validator,
const NamespaceString& nss,
const UUID& uuid) {
if (validator.isEmpty())
return Status::OK();
if (nss.isTemporaryReshardingCollection()) {
// In resharding, if the user's original collection has a validator, then the temporary
// resharding collection is created with it as well.
return Status::OK();
}
if (nss.isTimeseriesBucketsCollection()) {
return Status::OK();
}
if (nss.isSystem() && !nss.isDropPendingNamespace()) {
return {ErrorCodes::InvalidOptions,
str::stream() << "Document validators not allowed on system collection " << nss
<< " with UUID " << uuid};
}
if (nss.isOnInternalDb()) {
return {ErrorCodes::InvalidOptions,
str::stream() << "Document validators are not allowed on collection " << nss.ns()
<< " with UUID " << uuid << " in the " << nss.db()
<< " internal database"};
}
return Status::OK();
}
Status validatePreImageRecording(OperationContext* opCtx, const NamespaceString& ns) {
if (ns.db() == NamespaceString::kAdminDb || ns.db() == NamespaceString::kLocalDb) {
return {ErrorCodes::InvalidOptions,
str::stream() << "recordPreImages collection option is not supported on the "
<< ns.db() << " database"};
}
if (serverGlobalParams.clusterRole != ClusterRole::None) {
return {ErrorCodes::InvalidOptions,
"recordPreImages collection option is not supported on shards or config servers"};
}
return Status::OK();
}
class CappedDeleteSideTxn {
public:
CappedDeleteSideTxn(OperationContext* opCtx) : _opCtx(opCtx) {
_originalRecoveryUnit = _opCtx->releaseRecoveryUnit().release();
invariant(_originalRecoveryUnit);
_originalRecoveryUnitState = _opCtx->setRecoveryUnit(
std::unique_ptr<RecoveryUnit>(
_opCtx->getServiceContext()->getStorageEngine()->newRecoveryUnit()),
WriteUnitOfWork::RecoveryUnitState::kNotInUnitOfWork);
}
~CappedDeleteSideTxn() {
_opCtx->releaseRecoveryUnit();
_opCtx->setRecoveryUnit(std::unique_ptr<RecoveryUnit>(_originalRecoveryUnit),
_originalRecoveryUnitState);
}
private:
OperationContext* const _opCtx;
RecoveryUnit* _originalRecoveryUnit;
WriteUnitOfWork::RecoveryUnitState _originalRecoveryUnitState;
};
} // namespace
CollectionImpl::SharedState::SharedState(CollectionImpl* collection,
std::unique_ptr<RecordStore> recordStore,
const CollectionOptions& options)
: _collectionLatest(collection),
_recordStore(std::move(recordStore)),
_cappedNotifier(_recordStore && options.capped ? std::make_shared<CappedInsertNotifier>()
: nullptr),
_needCappedLock(options.capped && collection->ns().db() != "local"),
_isCapped(options.capped),
_cappedMaxDocs(options.cappedMaxDocs),
_cappedMaxSize(options.cappedSize) {
if (_cappedNotifier) {
_recordStore->setCappedCallback(this);
}
}
CollectionImpl::SharedState::~SharedState() {
if (_cappedNotifier) {
_recordStore->setCappedCallback(nullptr);
_cappedNotifier->kill();
}
}
void CollectionImpl::SharedState::instanceCreated(CollectionImpl* collection) {
_collectionPrev = _collectionLatest;
_collectionLatest = collection;
}
void CollectionImpl::SharedState::instanceDeleted(CollectionImpl* collection) {
// We have three possible cases to handle in this function, we know that these are the only
// possible cases as we can only have 1 clone at a time for a specific collection as we are
// holding a MODE_X lock when cloning for a DDL operation.
// 1. Previous (second newest) known CollectionImpl got deleted. That means that a clone has
// been committed into the catalog and what was in there got deleted.
// 2. Latest known CollectionImpl got deleted. This means that a clone that was created by the
// catalog never got committed into it and is deleted in a rollback handler. We need to set
// what was previous to latest in this case.
// 3. An older CollectionImpl that was kept alive by a read operation got deleted, nothing to do
// as we're not tracking these pointers (not needed for CappedCallback)
if (collection == _collectionPrev)
_collectionPrev = nullptr;
if (collection == _collectionLatest)
_collectionLatest = _collectionPrev;
}
CollectionImpl::CollectionImpl(OperationContext* opCtx,
const NamespaceString& nss,
RecordId catalogId,
const CollectionOptions& options,
std::unique_ptr<RecordStore> recordStore)
: _ns(nss),
_catalogId(catalogId),
_uuid(options.uuid.get()),
_shared(std::make_shared<SharedState>(this, std::move(recordStore), options)),
_indexCatalog(std::make_unique<IndexCatalogImpl>(this)) {}
CollectionImpl::~CollectionImpl() {
_shared->instanceDeleted(this);
}
void CollectionImpl::onDeregisterFromCatalog(OperationContext* opCtx) {
if (ns().isOplog()) {
repl::clearLocalOplogPtr(opCtx->getServiceContext());
}
}
std::shared_ptr<Collection> CollectionImpl::FactoryImpl::make(
OperationContext* opCtx,
const NamespaceString& nss,
RecordId catalogId,
const CollectionOptions& options,
std::unique_ptr<RecordStore> rs) const {
return std::make_shared<CollectionImpl>(opCtx, nss, catalogId, options, std::move(rs));
}
std::shared_ptr<Collection> CollectionImpl::clone() const {
auto cloned = std::make_shared<CollectionImpl>(*this);
checked_cast<IndexCatalogImpl*>(cloned->_indexCatalog.get())->setCollection(cloned.get());
cloned->_shared->instanceCreated(cloned.get());
// We are per definition committed if we get cloned
cloned->_cachedCommitted = true;
return cloned;
}
SharedCollectionDecorations* CollectionImpl::getSharedDecorations() const {
return &_shared->_sharedDecorations;
}
void CollectionImpl::init(OperationContext* opCtx) {
auto collectionOptions =
DurableCatalog::get(opCtx)->getCollectionOptions(opCtx, getCatalogId());
_shared->_collator = parseCollation(opCtx, _ns, collectionOptions.collation);
auto validatorDoc = collectionOptions.validator.getOwned();
// Enforce that the validator can be used on this namespace.
uassertStatusOK(checkValidatorCanBeUsedOnNs(validatorDoc, ns(), _uuid));
// Make sure to copy the action and level before parsing MatchExpression, since certain features
// are not supported with certain combinations of action and level.
_validationAction = collectionOptions.validationAction;
_validationLevel = collectionOptions.validationLevel;
if (collectionOptions.recordPreImages) {
uassertStatusOK(validatePreImageRecording(opCtx, _ns));
_recordPreImages = true;
}
// Store the result (OK / error) of parsing the validator, but do not enforce that the result is
// OK. This is intentional, as users may have validators on disk which were considered well
// formed in older versions but not in newer versions.
_validator =
parseValidator(opCtx, validatorDoc, MatchExpressionParser::kAllowAllSpecialFeatures);
if (!_validator.isOK()) {
// Log an error and startup warning if the collection validator is malformed.
LOGV2_WARNING_OPTIONS(20293,
{logv2::LogTag::kStartupWarnings},
"Collection {ns} has malformed validator: {validatorStatus}",
"Collection has malformed validator",
"namespace"_attr = _ns,
"validatorStatus"_attr = _validator.getStatus());
}
_timeseriesOptions = collectionOptions.timeseries;
if (collectionOptions.clusteredIndex) {
_clustered = true;
if (collectionOptions.clusteredIndex->getExpireAfterSeconds()) {
// TTL indexes are not compatible with capped collections.
invariant(!collectionOptions.capped);
// If this collection has been newly created, we need to register with the TTL cache at
// commit time, otherwise it is startup and we can register immediately.
auto svcCtx = opCtx->getClient()->getServiceContext();
auto uuid = *collectionOptions.uuid;
if (opCtx->lockState()->inAWriteUnitOfWork()) {
opCtx->recoveryUnit()->onCommit([svcCtx, uuid](auto ts) {
TTLCollectionCache::get(svcCtx).registerTTLInfo(
uuid, TTLCollectionCache::ClusteredId{});
});
} else {
TTLCollectionCache::get(svcCtx).registerTTLInfo(uuid,
TTLCollectionCache::ClusteredId{});
}
}
}
getIndexCatalog()->init(opCtx).transitional_ignore();
_initialized = true;
}
bool CollectionImpl::isInitialized() const {
return _initialized;
}
bool CollectionImpl::isCommitted() const {
return _cachedCommitted || _shared->_committed.load();
}
void CollectionImpl::setCommitted(bool val) {
bool previous = isCommitted();
invariant((!previous && val) || (previous && !val));
_shared->_committed.store(val);
// Going from false->true need to be synchronized by an atomic. Leave this as false and read
// from the atomic in the shared state that will be flipped to true at first clone.
if (!val) {
_cachedCommitted = val;
}
}
bool CollectionImpl::requiresIdIndex() const {
if (_ns.isOplog()) {
// No indexes on the oplog.
return false;
}
if (isClustered()) {
// Collections clustered by _id do not have a separate _id index.
return false;
}
if (_ns.isSystem()) {
StringData shortName = _ns.coll().substr(_ns.coll().find('.') + 1);
if (shortName == "indexes" || shortName == "namespaces" || shortName == "profile") {
return false;
}
}
return true;
}
std::unique_ptr<SeekableRecordCursor> CollectionImpl::getCursor(OperationContext* opCtx,
bool forward) const {
return _shared->_recordStore->getCursor(opCtx, forward);
}
bool CollectionImpl::findDoc(OperationContext* opCtx,
RecordId loc,
Snapshotted<BSONObj>* out) const {
RecordData rd;
if (!_shared->_recordStore->findRecord(opCtx, loc, &rd))
return false;
*out = Snapshotted<BSONObj>(opCtx->recoveryUnit()->getSnapshotId(), rd.releaseToBson());
return true;
}
Status CollectionImpl::checkValidatorAPIVersionCompatability(OperationContext* opCtx) const {
if (!_validator.expCtxForFilter) {
return Status::OK();
}
const auto& apiParams = APIParameters::get(opCtx);
const auto apiVersion = apiParams.getAPIVersion().value_or("");
if (apiParams.getAPIStrict().value_or(false) && apiVersion == "1" &&
_validator.expCtxForFilter->exprUnstableForApiV1) {
return {ErrorCodes::APIStrictError,
"The validator uses unstable expression(s) for API Version 1."};
}
if (apiParams.getAPIDeprecationErrors().value_or(false) && apiVersion == "1" &&
_validator.expCtxForFilter->exprDeprectedForApiV1) {
return {ErrorCodes::APIDeprecationError,
"The validator uses deprecated expression(s) for API Version 1."};
}
return Status::OK();
}
Status CollectionImpl::checkValidation(OperationContext* opCtx, const BSONObj& document) const {
if (!_validator.isOK()) {
return _validator.getStatus();
}
const auto* const validatorMatchExpr = _validator.filter.getValue().get();
if (!validatorMatchExpr)
return Status::OK();
if (validationLevelOrDefault(_validationLevel) == ValidationLevelEnum::off)
return Status::OK();
if (DocumentValidationSettings::get(opCtx).isSchemaValidationDisabled())
return Status::OK();
if (ns().isTemporaryReshardingCollection()) {
// In resharding, the donor shard primary is responsible for performing document validation
// and the recipient should not perform validation on documents inserted into the temporary
// resharding collection.
return Status::OK();
}
auto status = checkValidatorAPIVersionCompatability(opCtx);
if (!status.isOK()) {
return status;
}
// TODO SERVER-50524: remove these FCV checks when 5.0 becomes last-lts in order to make sure
// that an upgrade from 4.4 directly to the 5.0 LTS version is supported.
const auto isFCVAtLeast47 = serverGlobalParams.featureCompatibility.isVersionInitialized() &&
serverGlobalParams.featureCompatibility.isGreaterThanOrEqualTo(
ServerGlobalParams::FeatureCompatibility::Version::kVersion47);
try {
if (validatorMatchExpr->matchesBSON(document))
return Status::OK();
} catch (DBException& e) {
// If the FCV is lower than 4.7 and we're in error mode, then we cannot generate detailed
// errors. As such, we simply add extra context to the error and rethrow. Note that
// writes which result in the validator throwing an exception are accepted when we're in
// warn mode.
if (!isFCVAtLeast47 &&
validationActionOrDefault(_validationAction) == ValidationActionEnum::error) {
e.addContext("Document validation failed");
throw;
}
}
BSONObj generatedError;
if (isFCVAtLeast47) {
generatedError = doc_validation_error::generateError(*validatorMatchExpr, document);
}
if (validationActionOrDefault(_validationAction) == ValidationActionEnum::warn) {
LOGV2_WARNING(20294,
"Document would fail validation",
"namespace"_attr = ns(),
"document"_attr = redact(document),
"errInfo"_attr = generatedError);
return Status::OK();
}
static constexpr auto kValidationFailureErrorStr = "Document failed validation"_sd;
if (isFCVAtLeast47) {
return {doc_validation_error::DocumentValidationFailureInfo(generatedError),
kValidationFailureErrorStr};
} else {
return {ErrorCodes::DocumentValidationFailure, kValidationFailureErrorStr};
}
}
Collection::Validator CollectionImpl::parseValidator(
OperationContext* opCtx,
const BSONObj& validator,
MatchExpressionParser::AllowedFeatureSet allowedFeatures,
boost::optional<ServerGlobalParams::FeatureCompatibility::Version>
maxFeatureCompatibilityVersion) const {
if (MONGO_unlikely(allowSettingMalformedCollectionValidators.shouldFail())) {
return {validator, nullptr, nullptr};
}
if (validator.isEmpty())
return {validator, nullptr, nullptr};
Status canUseValidatorInThisContext = checkValidatorCanBeUsedOnNs(validator, ns(), _uuid);
if (!canUseValidatorInThisContext.isOK()) {
return {validator, nullptr, canUseValidatorInThisContext};
}
auto expCtx = make_intrusive<ExpressionContext>(
opCtx, CollatorInterface::cloneCollator(_shared->_collator.get()), ns());
// The MatchExpression and contained ExpressionContext created as part of the validator are
// owned by the Collection and will outlive the OperationContext they were created under.
expCtx->opCtx = nullptr;
// Enforce a maximum feature version if requested.
expCtx->maxFeatureCompatibilityVersion = maxFeatureCompatibilityVersion;
// The match expression parser needs to know that we're parsing an expression for a
// validator to apply some additional checks.
expCtx->isParsingCollectionValidator = true;
// If the validation action is "warn" or the level is "moderate", then disallow any encryption
// keywords. This is to prevent any plaintext data from showing up in the logs.
if (validationActionOrDefault(_validationAction) == ValidationActionEnum::warn ||
validationLevelOrDefault(_validationLevel) == ValidationLevelEnum::moderate)
allowedFeatures &= ~MatchExpressionParser::AllowedFeatures::kEncryptKeywords;
auto statusWithMatcher =
MatchExpressionParser::parse(validator, expCtx, ExtensionsCallbackNoop(), allowedFeatures);
if (!statusWithMatcher.isOK()) {
return {
validator,
boost::intrusive_ptr<ExpressionContext>(nullptr),
statusWithMatcher.getStatus().withContext("Parsing of collection validator failed")};
}
return Collection::Validator{
validator, std::move(expCtx), std::move(statusWithMatcher.getValue())};
}
Status CollectionImpl::insertDocumentsForOplog(OperationContext* opCtx,
std::vector<Record>* records,
const std::vector<Timestamp>& timestamps) const {
dassert(opCtx->lockState()->isWriteLocked());
// Since this is only for the OpLog, we can assume these for simplicity.
invariant(_validator.isOK());
invariant(_validator.filter.getValue() == nullptr);
invariant(!_indexCatalog->haveAnyIndexes());
Status status = _shared->_recordStore->insertRecords(opCtx, records, timestamps);
if (!status.isOK())
return status;
_cappedDeleteAsNeeded(opCtx, records->begin()->id);
opCtx->recoveryUnit()->onCommit(
[this](boost::optional<Timestamp>) { _shared->notifyCappedWaitersIfNeeded(); });
return status;
}
Status CollectionImpl::insertDocuments(OperationContext* opCtx,
const std::vector<InsertStatement>::const_iterator begin,
const std::vector<InsertStatement>::const_iterator end,
OpDebug* opDebug,
bool fromMigrate) const {
auto status = checkFailCollectionInsertsFailPoint(_ns, (begin != end ? begin->doc : BSONObj()));
if (!status.isOK()) {
return status;
}
// Should really be done in the collection object at creation and updated on index create.
const bool hasIdIndex = _indexCatalog->findIdIndex(opCtx);
for (auto it = begin; it != end; it++) {
if (hasIdIndex && it->doc["_id"].eoo()) {
return Status(ErrorCodes::InternalError,
str::stream()
<< "Collection::insertDocument got document without _id for ns:"
<< _ns);
}
auto status = checkValidation(opCtx, it->doc);
if (!status.isOK())
return status;
}
const SnapshotId sid = opCtx->recoveryUnit()->getSnapshotId();
status = _insertDocuments(opCtx, begin, end, opDebug, fromMigrate);
if (!status.isOK()) {
return status;
}
invariant(sid == opCtx->recoveryUnit()->getSnapshotId());
opCtx->recoveryUnit()->onCommit(
[this](boost::optional<Timestamp>) { _shared->notifyCappedWaitersIfNeeded(); });
hangAfterCollectionInserts.executeIf(
[&](const BSONObj& data) {
const auto& firstIdElem = data["first_id"];
std::string whenFirst;
if (firstIdElem) {
whenFirst += " when first _id is ";
whenFirst += firstIdElem.str();
}
LOGV2(20289,
"hangAfterCollectionInserts fail point enabled. Blocking "
"until fail point is disabled.",
"namespace"_attr = _ns,
"whenFirst"_attr = whenFirst);
hangAfterCollectionInserts.pauseWhileSet(opCtx);
},
[&](const BSONObj& data) {
const auto& collElem = data["collectionNS"];
const auto& firstIdElem = data["first_id"];
// If the failpoint specifies no collection or matches the existing one, hang.
return (!collElem || _ns.ns() == collElem.str()) &&
(!firstIdElem ||
(begin != end && firstIdElem.type() == mongo::String &&
begin->doc["_id"].str() == firstIdElem.str()));
});
return Status::OK();
}
Status CollectionImpl::insertDocument(OperationContext* opCtx,
const InsertStatement& docToInsert,
OpDebug* opDebug,
bool fromMigrate) const {
std::vector<InsertStatement> docs;
docs.push_back(docToInsert);
return insertDocuments(opCtx, docs.begin(), docs.end(), opDebug, fromMigrate);
}
Status CollectionImpl::insertDocumentForBulkLoader(
OperationContext* opCtx, const BSONObj& doc, const OnRecordInsertedFn& onRecordInserted) const {
auto status = checkFailCollectionInsertsFailPoint(_ns, doc);
if (!status.isOK()) {
return status;
}
status = checkValidation(opCtx, doc);
if (!status.isOK()) {
return status;
}
dassert(opCtx->lockState()->isCollectionLockedForMode(ns(), MODE_IX));
RecordId recordId;
if (isClustered()) {
invariant(_shared->_recordStore->keyFormat() == KeyFormat::String);
recordId = uassertStatusOK(record_id_helpers::keyForDoc(doc));
}
// Using timestamp 0 for these inserts, which are non-oplog so we don't have an appropriate
// timestamp to use.
StatusWith<RecordId> loc = _shared->_recordStore->insertRecord(
opCtx, recordId, doc.objdata(), doc.objsize(), Timestamp());
if (!loc.isOK())
return loc.getStatus();
status = onRecordInserted(loc.getValue());
if (MONGO_unlikely(failAfterBulkLoadDocInsert.shouldFail())) {
LOGV2(20290,
"Failpoint failAfterBulkLoadDocInsert enabled. Throwing "
"WriteConflictException",
"namespace"_attr = _ns);
throw WriteConflictException();
}
std::vector<InsertStatement> inserts;
OplogSlot slot;
// Fetch a new optime now, if necessary.
auto replCoord = repl::ReplicationCoordinator::get(opCtx);
if (!replCoord->isOplogDisabledFor(opCtx, _ns)) {
// Populate 'slot' with a new optime.
slot = repl::getNextOpTime(opCtx);
}
inserts.emplace_back(kUninitializedStmtId, doc, slot);
getGlobalServiceContext()->getOpObserver()->onInserts(
opCtx, ns(), uuid(), inserts.begin(), inserts.end(), false);
_cappedDeleteAsNeeded(opCtx, loc.getValue());
opCtx->recoveryUnit()->onCommit(
[this](boost::optional<Timestamp>) { _shared->notifyCappedWaitersIfNeeded(); });
return loc.getStatus();
}
Status CollectionImpl::_insertDocuments(OperationContext* opCtx,
const std::vector<InsertStatement>::const_iterator begin,
const std::vector<InsertStatement>::const_iterator end,
OpDebug* opDebug,
bool fromMigrate) const {
dassert(opCtx->lockState()->isCollectionLockedForMode(ns(), MODE_IX));
const size_t count = std::distance(begin, end);
if (isCapped() && _indexCatalog->haveAnyIndexes() && count > 1) {
// We require that inserts to indexed capped collections be done one-at-a-time to avoid the
// possibility that a later document causes an earlier document to be deleted before it can
// be indexed.
// TODO SERVER-21512 It would be better to handle this here by just doing single inserts.
return {ErrorCodes::OperationCannotBeBatched,
"Can't batch inserts into indexed capped collections"};
}
if (_shared->_needCappedLock) {
// X-lock the metadata resource for this capped collection until the end of the WUOW. This
// prevents the primary from executing with more concurrency than secondaries.
// See SERVER-21646.
Lock::ResourceLock heldUntilEndOfWUOW{
opCtx->lockState(), ResourceId(RESOURCE_METADATA, _ns.ns()), MODE_X};
}
std::vector<Record> records;
records.reserve(count);
std::vector<Timestamp> timestamps;
timestamps.reserve(count);
for (auto it = begin; it != end; it++) {
const auto& doc = it->doc;
RecordId recordId;
if (isClustered()) {
invariant(_shared->_recordStore->keyFormat() == KeyFormat::String);
recordId = uassertStatusOK(record_id_helpers::keyForDoc(doc));
}
if (MONGO_unlikely(corruptDocumentOnInsert.shouldFail())) {
// Insert a truncated record that is half the expected size of the source document.
records.emplace_back(Record{recordId, RecordData(doc.objdata(), doc.objsize() / 2)});
timestamps.emplace_back(it->oplogSlot.getTimestamp());
continue;
}
records.emplace_back(Record{recordId, RecordData(doc.objdata(), doc.objsize())});
timestamps.emplace_back(it->oplogSlot.getTimestamp());
}
Status status = _shared->_recordStore->insertRecords(opCtx, &records, timestamps);
if (!status.isOK())
return status;
std::vector<BsonRecord> bsonRecords;
bsonRecords.reserve(count);
int recordIndex = 0;
for (auto it = begin; it != end; it++) {
RecordId loc = records[recordIndex++].id;
if (_shared->_recordStore->keyFormat() == KeyFormat::Long) {
invariant(RecordId::minLong() < loc);
invariant(loc < RecordId::maxLong());
}
BsonRecord bsonRecord = {loc, Timestamp(it->oplogSlot.getTimestamp()), &(it->doc)};
bsonRecords.push_back(bsonRecord);
}
int64_t keysInserted;
status = _indexCatalog->indexRecords(
opCtx, {this, CollectionPtr::NoYieldTag{}}, bsonRecords, &keysInserted);
if (!status.isOK()) {
return status;
}
if (opDebug) {
opDebug->additiveMetrics.incrementKeysInserted(keysInserted);
}
opCtx->getServiceContext()->getOpObserver()->onInserts(
opCtx, ns(), uuid(), begin, end, fromMigrate);
_cappedDeleteAsNeeded(opCtx, records.begin()->id);
return Status::OK();
}
bool CollectionImpl::_cappedAndNeedDelete(OperationContext* opCtx) const {
if (!isCapped()) {
return false;
}
if (ns().isOplog() && _shared->_recordStore->selfManagedOplogTruncation()) {
// Storage engines can choose to manage oplog truncation internally.
return false;
}
if (dataSize(opCtx) > _shared->_cappedMaxSize) {
return true;
}
if ((_shared->_cappedMaxDocs != 0) && (numRecords(opCtx) > _shared->_cappedMaxDocs)) {
return true;
}
return false;
}
void CollectionImpl::_cappedDeleteAsNeeded(OperationContext* opCtx,
const RecordId& justInserted) const {
if (!_cappedAndNeedDelete(opCtx)) {
return;
}
bool useOldCappedDeleteBehaviour = serverGlobalParams.featureCompatibility.isLessThan(
ServerGlobalParams::FeatureCompatibility::Version::kVersion50);
if (!useOldCappedDeleteBehaviour && !opCtx->isEnforcingConstraints()) {
// With new capped delete behavior, secondaries only delete from capped collections via
// oplog application when there are explicit delete oplog entries.
return;
}
// If the collection does not need size adjustment, then we are in replication recovery and
// replaying operations we've already played. This may occur after rollback or after a shutdown.
// Any inserts beyond the stable timestamp have been undone, but any documents deleted from
// capped collections did not come back due to being performed in an un-timestamped side
// transaction. Additionally, the SizeStorer's information reflects the state of the collection
// before rollback/shutdown, post capped deletions.
//
// If we have a collection whose size we know accurately as of the stable timestamp, rather
// than as of the top of the oplog, then we must actually perform capped deletions because they
// have not previously been accounted for. The collection will be marked as needing size
// adjustment when entering this function.
//
// One edge case to consider is where we need to delete a document that we insert as part of
// replication recovery. If we don't mark the collection for size adjustment then we will not
// perform the capped deletions as expected. In that case, the collection is guaranteed to be
// empty at the stable timestamp and thus guaranteed to be marked for size adjustment.
//
// This is only applicable for the old capped delete behaviour.
if (useOldCappedDeleteBehaviour &&
!sizeRecoveryState(opCtx->getServiceContext())
.collectionNeedsSizeAdjustment(getSharedIdent()->getIdent())) {
return;
}
stdx::lock_guard<Latch> lk(_shared->_cappedDeleterMutex);
boost::optional<CappedDeleteSideTxn> cappedDeleteSideTxn;
if (useOldCappedDeleteBehaviour) {
cappedDeleteSideTxn.emplace(opCtx);
}
const long long currentDataSize = dataSize(opCtx);
const long long currentNumRecords = numRecords(opCtx);
const long long sizeOverCap =
(currentDataSize > _shared->_cappedMaxSize) ? currentDataSize - _shared->_cappedMaxSize : 0;
const long long docsOverCap =
(_shared->_cappedMaxDocs != 0 && currentNumRecords > _shared->_cappedMaxDocs)
? currentNumRecords - _shared->_cappedMaxDocs
: 0;
long long sizeSaved = 0;
long long docsRemoved = 0;
WriteUnitOfWork wuow(opCtx);
boost::optional<Record> record;
auto cursor = getCursor(opCtx, /*forward=*/true);
// If the next RecordId to be deleted is known, navigate to it using seekExact(). Using a cursor
// and advancing it to the first element by calling next() will be slow for capped collections
// on particular storage engines, such as WiredTiger. In WiredTiger, there may be many
// tombstones (invisible deleted records) to traverse at the beginning of the table.
if (!_shared->_cappedFirstRecord.isNull()) {
record = cursor->seekExact(_shared->_cappedFirstRecord);
} else {
record = cursor->next();
}
while (sizeSaved < sizeOverCap || docsRemoved < docsOverCap) {
if (!record) {
break;
}
if (record->id == justInserted) {
// We're prohibited from deleting what was just inserted.
break;
}
docsRemoved++;
sizeSaved += record->data.size();
try {
BSONObj doc = record->data.toBson();
if (!useOldCappedDeleteBehaviour && ns().isReplicated()) {
// Only generate oplog entries on replicated collections in FCV >= 5.0.
OpObserver* opObserver = opCtx->getServiceContext()->getOpObserver();
opObserver->aboutToDelete(opCtx, ns(), doc);
// Reserves an optime for the deletion and sets the timestamp for future writes.
opObserver->onDelete(opCtx,
ns(),
uuid(),
kUninitializedStmtId,
/*fromMigrate=*/false,
/*deletedDoc=*/boost::none);
}
int64_t unusedKeysDeleted = 0;
_indexCatalog->unindexRecord(
opCtx, doc, record->id, /*logIfError=*/false, &unusedKeysDeleted);
// We're about to delete the record our cursor is positioned on, so advance the cursor.
RecordId toDelete = record->id;
record = cursor->next();
_shared->_recordStore->deleteRecord(opCtx, toDelete);
} catch (const WriteConflictException&) {
if (!useOldCappedDeleteBehaviour) {
throw;
}
invariant(cappedDeleteSideTxn);
LOGV2(22398, "Got write conflict removing capped records, ignoring");
return;
}
}
// Save the RecordId of the next record to be deleted, if it exists.
if (!record) {
_shared->_cappedFirstRecord = RecordId();
} else {
_shared->_cappedFirstRecord = record->id;
}
// Capped deletes can be part of a larger transaction. If that transaction ultimately gets
// rolled back, we need to reset the cached value of the next record to be deleted otherwise
// we'll skip deleting records at the beginning of the capped collection.
opCtx->recoveryUnit()->onRollback([this]() {
stdx::lock_guard<Latch> lk(_shared->_cappedDeleterMutex);
_shared->_cappedFirstRecord = RecordId();
});
wuow.commit();
}
void CollectionImpl::setMinimumVisibleSnapshot(Timestamp newMinimumVisibleSnapshot) {
if (!_minVisibleSnapshot || (newMinimumVisibleSnapshot > _minVisibleSnapshot.get())) {
_minVisibleSnapshot = newMinimumVisibleSnapshot;
}
}
bool CollectionImpl::SharedState::haveCappedWaiters() const {
// Waiters keep a shared_ptr to '_cappedNotifier', so there are waiters if this CollectionImpl's