Storage Engine API
collection_impl.h
Go to the documentation of this file.
1 /*-
2  * Copyright (C) 2017 MongoDB Inc.
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU Affero General Public License, version 3,
6  * as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  * GNU Affero General Public License for more details.
12  *
13  * You should have received a copy of the GNU Affero General Public License
14  * along with this program. If not, see <http://www.gnu.org/licenses/>.
15  *
16  * As a special exception, the copyright holders give permission to link the
17  * code of portions of this program with the OpenSSL library under certain
18  * conditions as described in each individual source file and distribute
19  * linked combinations including the program with the OpenSSL library. You
20  * must comply with the GNU Affero General Public License in all respects for
21  * all of the code used other than as permitted herein. If you modify file(s)
22  * with this exception, you may extend this exception to your version of the
23  * file(s), but you are not obligated to do so. If you do not wish to do so,
24  * delete this exception statement from your version. If you delete this
25  * exception statement from all source files in the program, then also delete
26  * it in the license file.
27  */
28 
29 #pragma once
30 
31 #include "mongo/bson/timestamp.h"
36 
37 namespace mongo {
38 class IndexConsistency;
39 class UUIDCatalog;
40 class CollectionImpl final : virtual public Collection::Impl,
41  virtual CappedCallback,
42  virtual UpdateNotifier {
43 private:
44  static const int kMagicNumber = 1357924;
45 
46 public:
48  OperationContext* opCtx,
49  StringData fullNS,
51  CollectionCatalogEntry* details, // does not own
52  RecordStore* recordStore, // does not own
53  DatabaseCatalogEntry* dbce); // does not own
54 
56 
57  void init(OperationContext* opCtx) final;
58 
59  bool ok() const final {
60  return _magic == kMagicNumber;
61  }
62 
64  return _details;
65  }
66 
67  const CollectionCatalogEntry* getCatalogEntry() const final {
68  return _details;
69  }
70 
72  return &_infoCache;
73  }
74 
75  const CollectionInfoCache* infoCache() const final {
76  return &_infoCache;
77  }
78 
79  const NamespaceString& ns() const final {
80  return _ns;
81  }
82 
84  return _uuid;
85  }
86 
87  const IndexCatalog* getIndexCatalog() const final {
88  return &_indexCatalog;
89  }
90 
92  return &_indexCatalog;
93  }
94 
95  const RecordStore* getRecordStore() const final {
96  return _recordStore;
97  }
98 
100  return _recordStore;
101  }
102 
103  CursorManager* getCursorManager() const final {
104  return &_cursorManager;
105  }
106 
107  bool requiresIdIndex() const final;
108 
109  Snapshotted<BSONObj> docFor(OperationContext* opCtx, const RecordId& loc) const final {
110  return Snapshotted<BSONObj>(opCtx->recoveryUnit()->getSnapshotId(),
112  }
113 
118  bool findDoc(OperationContext* opCtx,
119  const RecordId& loc,
120  Snapshotted<BSONObj>* out) const final;
121 
122  std::unique_ptr<SeekableRecordCursor> getCursor(OperationContext* opCtx,
123  bool forward = true) const final;
124 
129  std::vector<std::unique_ptr<RecordCursor>> getManyCursors(OperationContext* opCtx) const final;
130 
146  void deleteDocument(
147  OperationContext* opCtx,
148  StmtId stmtId,
149  const RecordId& loc,
150  OpDebug* opDebug,
151  bool fromMigrate = false,
152  bool noWarn = false,
153  Collection::StoreDeletedDoc storeDeletedDoc = Collection::StoreDeletedDoc::Off) final;
154 
155  /*
156  * Inserts all documents inside one WUOW.
157  * Caller should ensure vector is appropriately sized for this.
158  * If any errors occur (including WCE), caller should retry documents individually.
159  *
160  * 'opDebug' Optional argument. When not null, will be used to record operation statistics.
161  */
162  Status insertDocuments(OperationContext* opCtx,
163  std::vector<InsertStatement>::const_iterator begin,
164  std::vector<InsertStatement>::const_iterator end,
165  OpDebug* opDebug,
166  bool enforceQuota,
167  bool fromMigrate = false) final;
168 
176  Status insertDocument(OperationContext* opCtx,
177  const InsertStatement& doc,
178  OpDebug* opDebug,
179  bool enforceQuota,
180  bool fromMigrate = false) final;
181 
186  Status insertDocumentsForOplog(OperationContext* opCtx,
187  const DocWriter* const* docs,
188  Timestamp* timestamps,
189  size_t nDocs) final;
190 
196  Status insertDocument(OperationContext* opCtx,
197  const BSONObj& doc,
198  const std::vector<MultiIndexBlock*>& indexBlocks,
199  bool enforceQuota) final;
200 
210  RecordId updateDocument(OperationContext* opCtx,
211  const RecordId& oldLocation,
212  const Snapshotted<BSONObj>& oldDoc,
213  const BSONObj& newDoc,
214  bool enforceQuota,
215  bool indexesAffected,
216  OpDebug* opDebug,
217  OplogUpdateEntryArgs* args) final;
218 
219  bool updateWithDamagesSupported() const final;
220 
229  const RecordId& loc,
230  const Snapshotted<RecordData>& oldRec,
231  const char* damageSource,
232  const mutablebson::DamageVector& damages,
233  OplogUpdateEntryArgs* args) final;
234 
235  // -----------
236 
237  StatusWith<CompactStats> compact(OperationContext* opCtx, const CompactOptions* options) final;
238 
244  Status truncate(OperationContext* opCtx) final;
245 
251  Status validate(OperationContext* opCtx,
252  ValidateCmdLevel level,
253  bool background,
254  std::unique_ptr<Lock::CollectionLock> collLk,
255  ValidateResults* results,
256  BSONObjBuilder* output) final;
257 
261  Status touch(OperationContext* opCtx,
262  bool touchData,
263  bool touchIndexes,
264  BSONObjBuilder* output) const final;
265 
272  void cappedTruncateAfter(OperationContext* opCtx, RecordId end, bool inclusive) final;
273 
275 
277 
281  StatusWithMatchExpression parseValidator(
282  OperationContext* opCtx,
283  const BSONObj& validator,
284  MatchExpressionParser::AllowedFeatureSet allowedFeatures,
285  boost::optional<ServerGlobalParams::FeatureCompatibility::Version>
286  maxFeatureCompatibilityVersion = boost::none) const final;
287 
288  static StatusWith<ValidationLevel> parseValidationLevel(StringData);
290 
297  Status setValidator(OperationContext* opCtx, BSONObj validator) final;
298 
299  Status setValidationLevel(OperationContext* opCtx, StringData newLevel) final;
300  Status setValidationAction(OperationContext* opCtx, StringData newAction) final;
301 
302  StringData getValidationLevel() const final;
303  StringData getValidationAction() const final;
304 
310  Status updateValidator(OperationContext* opCtx,
311  BSONObj newValidator,
312  StringData newLevel,
313  StringData newAction) final;
314 
315  // -----------
316 
317  //
318  // Stats
319  //
320 
321  bool isCapped() const final;
322 
329  std::shared_ptr<CappedInsertNotifier> getCappedInsertNotifier() const final;
330 
331  uint64_t numRecords(OperationContext* opCtx) const final;
332 
333  uint64_t dataSize(OperationContext* opCtx) const final;
334 
335  inline int averageObjectSize(OperationContext* opCtx) const {
336  uint64_t n = numRecords(opCtx);
337 
338  if (n == 0)
339  return 5;
340  return static_cast<int>(dataSize(opCtx) / n);
341  }
342 
343  uint64_t getIndexSize(OperationContext* opCtx,
344  BSONObjBuilder* details = NULL,
345  int scale = 1) final;
346 
351  boost::optional<Timestamp> getMinimumVisibleSnapshot() final {
352  return _minVisibleSnapshot;
353  }
354 
355  void setMinimumVisibleSnapshot(Timestamp name) final {
357  }
358 
359  bool haveCappedWaiters() final;
360 
364  void notifyCappedWaitersIfNeeded() final;
365 
370  const CollatorInterface* getDefaultCollator() const final;
371 
372 private:
373  inline DatabaseCatalogEntry* dbce() const final {
374  return this->_dbce;
375  }
376 
377  inline CollectionCatalogEntry* details() const final {
378  return this->_details;
379  }
380 
384  Status checkValidation(OperationContext* opCtx, const BSONObj& document) const;
385 
386  Status recordStoreGoingToUpdateInPlace(OperationContext* opCtx, const RecordId& loc);
387 
388  Status aboutToDeleteCapped(OperationContext* opCtx, const RecordId& loc, RecordData data);
389 
395  Status _insertDocument(OperationContext* opCtx, const BSONObj& doc, bool enforceQuota);
396 
397  Status _insertDocuments(OperationContext* opCtx,
398  std::vector<InsertStatement>::const_iterator begin,
399  std::vector<InsertStatement>::const_iterator end,
400  bool enforceQuota,
401  OpDebug* opDebug);
402 
403 
408  const RecordId& oldLocation,
409  const Snapshotted<BSONObj>& oldDoc,
410  const BSONObj& newDoc,
411  bool enforceQuota,
412  OpDebug* opDebug,
413  OplogUpdateEntryArgs* args,
414  const SnapshotId& sid);
415 
416  bool _enforceQuota(bool userEnforeQuota) const;
417 
418  int _magic;
419 
420  const NamespaceString _ns;
425  const bool _needCappedLock;
428 
429 
430  // The default collation which is applied to operations and indices which have no collation of
431  // their own. The collection's validator will respect this collation.
432  //
433  // If null, the default collation is simple binary compare.
434  std::unique_ptr<CollatorInterface> _collator;
435 
436  // Empty means no filter.
437  BSONObj _validatorDoc;
438 
439  // Points into _validatorDoc. Null means no filter.
440  std::unique_ptr<MatchExpression> _validator;
441 
444 
445  // this is mutable because read only users of the Collection class
446  // use it keep state. This seems valid as const correctness of Collection
447  // should be about the data.
448  mutable CursorManager _cursorManager;
449 
450  // Notifier object for awaitData. Threads polling a capped collection for new data can wait
451  // on this object until notified of the arrival of new data.
452  //
453  // This is non-null if and only if the collection is a capped collection.
454  const std::shared_ptr<CappedInsertNotifier> _cappedNotifier;
455 
456  // The earliest snapshot that is allowed to use this collection.
457  boost::optional<Timestamp> _minVisibleSnapshot;
458 
460 
461  friend class NamespaceDetails;
462 };
463 } // namespace mongo
Queries with the awaitData option use this notifier object to wait for more data to be inserted into ...
Definition: collection.h:105
ValidateCmdLevel
Definition: record_store.h:93
CursorManager _cursorManager
Definition: collection_impl.h:448
StatusWith< CompactStats > compact(OperationContext *opCtx, const CompactOptions *options) final
Definition: collection_compact.cpp:108
ValidationLevel _validationLevel
Definition: collection_impl.h:443
Copyright (C) 2017 MongoDB Inc.
Definition: encryption_hooks.h:38
Definition: snapshot.h:69
Status setValidationLevel(OperationContext *opCtx, StringData newLevel) final
Definition: collection_impl.cpp:985
Definition: record_store.h:673
std::unique_ptr< SeekableRecordCursor > getCursor(OperationContext *opCtx, bool forward=true) const final
Definition: collection_impl.cpp:214
Status _insertDocuments(OperationContext *opCtx, std::vector< InsertStatement >::const_iterator begin, std::vector< InsertStatement >::const_iterator end, bool enforceQuota, OpDebug *opDebug)
Definition: collection_impl.cpp:451
ValidationAction _validationAction
Definition: collection_impl.h:442
StringData getValidationAction() const final
Definition: collection_impl.cpp:975
Status aboutToDeleteCapped(OperationContext *opCtx, const RecordId &loc, RecordData data)
This will be called right before loc is deleted when wrapping.
Definition: collection_impl.cpp:526
bool requiresIdIndex() const final
Definition: collection_impl.cpp:198
const NamespaceString _ns
Definition: collection_impl.h:420
CollectionCatalogEntry * details() const final
Definition: collection_impl.h:377
RecordStore * getRecordStore() final
Definition: collection_impl.h:99
static StatusWith< ValidationAction > parseValidationAction(StringData)
Definition: collection_impl.cpp:949
Copyright (C) 2014 MongoDB Inc.
Definition: bson_collection_catalog_entry.cpp:38
bool _enforceQuota(bool userEnforeQuota) const
Definition: collection_impl.cpp:798
Definition: collection_catalog_entry.h:47
Definition: d_concurrency.h:42
Definition: collection_impl.h:40
A replacement for the Record class.
Definition: record_data.h:43
const NamespaceString & ns() const final
Definition: collection_impl.h:79
Status _insertDocument(OperationContext *opCtx, const BSONObj &doc, bool enforceQuota)
same semantics as insertDocument, but doesn't do:
int _magic
Definition: collection_impl.h:418
std::unique_ptr< CollatorInterface > _collator
Definition: collection_impl.h:434
const CollatorInterface * getDefaultCollator() const final
Get a pointer to the collection's default collator.
Definition: collection_impl.cpp:1065
Status setValidator(OperationContext *opCtx, BSONObj validator) final
Sets the validator for this collection.
Definition: collection_impl.cpp:904
Definition: collection.h:166
CollectionCatalogEntry * getCatalogEntry() final
Definition: collection_impl.h:63
Definition: record_store.h:78
BSONObj _validatorDoc
Definition: collection_impl.h:437
Status insertDocument(OperationContext *opCtx, const InsertStatement &doc, OpDebug *opDebug, bool enforceQuota, bool fromMigrate=false) final
this does NOT modify the doc before inserting i.e.
Definition: collection_impl.cpp:381
RecordStore *const _recordStore
Definition: collection_impl.h:423
Snapshotted< BSONObj > docFor(OperationContext *opCtx, const RecordId &loc) const final
Definition: collection_impl.h:109
bool inclusive
Definition: btree_interface.cpp:335
CollectionCatalogEntry *const _details
Definition: collection_impl.h:422
CollectionInfoCache * infoCache() final
Definition: collection_impl.h:71
int averageObjectSize(OperationContext *opCtx) const
Definition: collection_impl.h:335
this is NOT safe through a yield right now.
Definition: collection.h:160
bool findDoc(OperationContext *opCtx, const RecordId &loc, Snapshotted< BSONObj > *out) const final
Definition: collection_impl.cpp:230
Definition: collection.h:77
Allows inserting a Record "in-place" without creating a copy ahead of time.
Definition: record_store.h:62
StatusWith< RecordId > _updateDocumentWithMove(OperationContext *opCtx, const RecordId &oldLocation, const Snapshotted< BSONObj > &oldDoc, const BSONObj &newDoc, bool enforceQuota, OpDebug *opDebug, OplogUpdateEntryArgs *args, const SnapshotId &sid)
Perform update when document move will be required.
Definition: collection_impl.cpp:703
ValidationAction
Definition: collection.h:162
Definition: namespace_details.h:47
std::shared_ptr< void > data
Definition: ephemeral_for_test_record_store_test.cpp:74
Status touch(OperationContext *opCtx, bool touchData, bool touchIndexes, BSONObjBuilder *output) const final
forces data into cache
Definition: collection_impl.cpp:1343
RecordId updateDocument(OperationContext *opCtx, const RecordId &oldLocation, const Snapshotted< BSONObj > &oldDoc, const BSONObj &newDoc, bool enforceQuota, bool indexesAffected, OpDebug *opDebug, OplogUpdateEntryArgs *args) final
Updates the document @ oldLocation with newDoc.
Definition: collection_impl.cpp:584
Status checkValidation(OperationContext *opCtx, const BSONObj &document) const
Returns a non-ok Status if document does not pass this collection's validator.
Definition: collection_impl.cpp:242
const CollectionInfoCache * infoCache() const final
Definition: collection_impl.h:75
how many: 1 per Collection.
Definition: index_catalog.h:62
uint64_t getIndexSize(OperationContext *opCtx, BSONObjBuilder *details=NULL, int scale=1) final
Definition: collection_impl.cpp:831
bool updateWithDamagesSupported() const final
Definition: collection_impl.cpp:766
const bool _needCappedLock
Definition: collection_impl.h:425
bool isCapped() const final
Definition: collection_impl.cpp:814
Collection *const OperationContext *const const StringData OptionalCollectionUUID CollectionCatalogEntry *const RecordStore *const recordStore
Definition: collection_impl.cpp:80
CollectionInfoCache _infoCache
Definition: collection_impl.h:426
Status insertDocuments(OperationContext *opCtx, std::vector< InsertStatement >::const_iterator begin, std::vector< InsertStatement >::const_iterator end, OpDebug *opDebug, bool enforceQuota, bool fromMigrate=false) final
Definition: collection_impl.cpp:329
OperationContext Database StringData CollectionOptions bool const BSONObj &idIndex Status
Definition: database_impl.cpp:955
boost::optional< CollectionUUID > OptionalCollectionUUID
Definition: collection_options.h:55
static const int kMagicNumber
Definition: collection_impl.h:44
bool haveCappedWaiters() final
Returns true if there may be waiters.
Definition: collection_impl.cpp:513
IndexCatalog _indexCatalog
Definition: collection_impl.h:427
OptionalCollectionUUID uuid() const
Definition: collection_impl.h:83
Definition: index_key_validate.h:40
static StatusWith< ValidationLevel > parseValidationLevel(StringData)
Definition: collection_impl.cpp:933
void init(OperationContext *opCtx) final
Definition: collection_impl.cpp:169
Retrieves Records from a RecordStore.
Definition: record_store.h:141
virtual RecordData dataFor(OperationContext *opCtx, const RecordId &loc) const
Get the RecordData at loc, which must exist.
Definition: record_store.h:339
An abstraction used for storing documents in a collection or entries in an index.
Definition: record_store.h:282
When a capped collection is modified (delete/insert/etc) then certain notifications need to be made,...
Definition: capped_callback.h:44
Status validate(OperationContext *opCtx, ValidateCmdLevel level, bool background, std::unique_ptr< Lock::CollectionLock > collLk, ValidateResults *results, BSONObjBuilder *output) final
Definition: collection_impl.cpp:1272
std::vector< std::unique_ptr< RecordCursor > > getManyCursors(OperationContext *opCtx) const final
Returns many cursors that partition the Collection into many disjoint sets.
Definition: collection_impl.cpp:222
Status truncate(OperationContext *opCtx) final
removes all documents as fast as possible indexes before and after will be the same as will other cha...
Definition: collection_impl.cpp:860
BSONObj releaseToBson()
Definition: record_data.h:74
StringData getValidationLevel() const final
Definition: collection_impl.cpp:963
uint64_t numRecords(OperationContext *opCtx) const final
Definition: collection_impl.cpp:823
~CollectionImpl()
Definition: collection_impl.cpp:178
IndexCatalog * getIndexCatalog() final
Definition: collection_impl.h:91
Status insertDocumentsForOplog(OperationContext *opCtx, const DocWriter *const *docs, Timestamp *timestamps, size_t nDocs) final
Callers must ensure no document validation is performed for this collection when calling this method.
Definition: collection_impl.cpp:306
CursorManager * getCursorManager() const final
Definition: collection_impl.h:103
Builds one or more indexes.
Definition: index_create.h:61
Definition: database_catalog_entry.h:50
Collection *const OperationContext *const const StringData fullNS
Definition: collection_impl.cpp:80
std::shared_ptr< CappedInsertNotifier > getCappedInsertNotifier() const final
Get a pointer to a capped insert notifier object.
Definition: collection_impl.cpp:818
boost::optional< Timestamp > _minVisibleSnapshot
Definition: collection_impl.h:457
Collection * _this
Definition: collection_impl.h:459
Status setValidationAction(OperationContext *opCtx, StringData newAction) final
Definition: collection_impl.cpp:1003
DatabaseCatalogEntry *const _dbce
Definition: collection_impl.h:424
const IndexCatalog * getIndexCatalog() const final
Definition: collection_impl.h:87
Status updateValidator(OperationContext *opCtx, BSONObj newValidator, StringData newLevel, StringData newAction) final
Sets the validator to exactly what's provided.
Definition: collection_impl.cpp:1021
Definition: collection.h:97
void cappedTruncateAfter(OperationContext *opCtx, RecordId end, bool inclusive) final
Truncate documents newer than the document at 'end' from the capped collection.
Definition: collection_impl.cpp:894
StatusWithMatchExpression parseValidator(OperationContext *opCtx, const BSONObj &validator, MatchExpressionParser::AllowedFeatureSet allowedFeatures, boost::optional< ServerGlobalParams::FeatureCompatibility::Version > maxFeatureCompatibilityVersion=boost::none) const final
Returns a non-ok Status if validator is not legal for this collection.
Definition: collection_impl.cpp:264
Status recordStoreGoingToUpdateInPlace(OperationContext *opCtx, const RecordId &loc)
Definition: collection_impl.cpp:758
boost::optional< Timestamp > getMinimumVisibleSnapshot() final
If return value is not boost::none, reads with majority read concern using an older snapshot must err...
Definition: collection_impl.h:351
Definition: snapshot.h:37
ValidationLevel
Definition: collection.h:163
bool ok() const final
Definition: collection_impl.h:59
uint64_t dataSize(OperationContext *opCtx) const final
Definition: collection_impl.cpp:827
Database *const OperationContext *const const StringData name
Definition: database_impl.cpp:82
Collection *const OperationContext *const opCtx
Definition: collection_impl.cpp:80
CollectionImpl(Collection *_this, OperationContext *opCtx, StringData fullNS, OptionalCollectionUUID uuid, CollectionCatalogEntry *details, RecordStore *recordStore, DatabaseCatalogEntry *dbce)
Definition: collection_impl.cpp:141
OptionalCollectionUUID _uuid
Definition: collection_impl.h:421
this is for storing things that you want to cache about a single collection life cycle is managed for...
Definition: collection_info_cache.h:47
DatabaseCatalogEntry * dbce() const final
Definition: collection_impl.h:373
const RecordStore * getRecordStore() const final
Definition: collection_impl.h:95
void setMinimumVisibleSnapshot(Timestamp name) final
Definition: collection_impl.h:355
const CollectionCatalogEntry * getCatalogEntry() const final
Definition: collection_impl.h:67
void notifyCappedWaitersIfNeeded() final
Notify (capped collection) waiters of data changes, like an insert.
Definition: collection_impl.cpp:519
void deleteDocument(OperationContext *opCtx, StmtId stmtId, const RecordId &loc, OpDebug *opDebug, bool fromMigrate=false, bool noWarn=false, Collection::StoreDeletedDoc storeDeletedDoc=Collection::StoreDeletedDoc::Off) final
Deletes the document with the given RecordId from the collection.
Definition: collection_impl.cpp:545
StatusWith< RecordData > updateDocumentWithDamages(OperationContext *opCtx, const RecordId &loc, const Snapshotted< RecordData > &oldRec, const char *damageSource, const mutablebson::DamageVector &damages, OplogUpdateEntryArgs *args) final
Not allowed to modify indexes.
Definition: collection_impl.cpp:773
std::unique_ptr< MatchExpression > _validator
Definition: collection_impl.h:440
const std::shared_ptr< CappedInsertNotifier > _cappedNotifier
Definition: collection_impl.h:454