summaryrefslogtreecommitdiff
path: root/src/mongo/db/storage/storage_engine_test_fixture.h
blob: 064969715ab8df5a7e3e7f5b1b0673c54a397889 (plain)
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
/**
 *    Copyright (C) 2019-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.
 */

#pragma once

#include "mongo/db/catalog/collection_catalog.h"
#include "mongo/db/catalog/collection_impl.h"
#include "mongo/db/catalog_raii.h"
#include "mongo/db/multitenancy.h"
#include "mongo/db/repl/replication_coordinator_mock.h"
#include "mongo/db/service_context_d_test_fixture.h"
#include "mongo/db/storage/durable_catalog.h"
#include "mongo/db/storage/durable_catalog_impl.h"
#include "mongo/db/storage/kv/kv_engine.h"
#include "mongo/db/storage/storage_engine_impl.h"
#include "mongo/db/storage/storage_repair_observer.h"
#include "mongo/logv2/log.h"

#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kDefault

namespace mongo {

class StorageEngineTest : public ServiceContextMongoDTest {
public:
    explicit StorageEngineTest(Options options = {})
        : ServiceContextMongoDTest(std::move(options)),
          _storageEngine(getServiceContext()->getStorageEngine()) {
        repl::ReplicationCoordinator::set(
            getServiceContext(),
            std::make_unique<repl::ReplicationCoordinatorMock>(getServiceContext()));
    }

    StatusWith<DurableCatalog::EntryIdentifier> createCollection(OperationContext* opCtx,
                                                                 NamespaceString ns) {
        Lock::GlobalWrite lk(opCtx);
        AutoGetDb db(opCtx, ns.dbName(), LockMode::MODE_X);
        CollectionOptions options;
        options.uuid = UUID::gen();
        RecordId catalogId;
        std::unique_ptr<RecordStore> rs;
        {
            WriteUnitOfWork wuow(opCtx);
            std::tie(catalogId, rs) = unittest::assertGet(
                _storageEngine->getCatalog()->createCollection(opCtx, ns, options, true));
            wuow.commit();
        }
        std::shared_ptr<Collection> coll = std::make_shared<CollectionImpl>(
            opCtx,
            ns,
            catalogId,
            _storageEngine->getCatalog()->getMetaData(opCtx, catalogId),
            std::move(rs));

        CollectionCatalog::write(opCtx, [&](CollectionCatalog& catalog) {
            catalog.registerCollection(
                opCtx, options.uuid.get(), std::move(coll), /*ts=*/boost::none);
        });

        return {{_storageEngine->getCatalog()->getEntry(catalogId)}};
    }

    std::unique_ptr<TemporaryRecordStore> makeTemporary(OperationContext* opCtx) {
        return _storageEngine->makeTemporaryRecordStore(opCtx, KeyFormat::Long);
    }

    std::unique_ptr<TemporaryRecordStore> makeTemporaryClustered(OperationContext* opCtx) {
        return _storageEngine->makeTemporaryRecordStore(opCtx, KeyFormat::String);
    }

    /**
     * Create a collection table in the KVEngine not reflected in the DurableCatalog.
     */
    Status createCollTable(OperationContext* opCtx, NamespaceString collName) {
        const std::string identName = "collection-" + collName.ns();
        return _storageEngine->getEngine()->createRecordStore(
            opCtx, collName, identName, CollectionOptions());
    }

    Status dropIndexTable(OperationContext* opCtx, NamespaceString nss, std::string indexName) {
        RecordId catalogId =
            CollectionCatalog::get(opCtx)->lookupCollectionByNamespace(opCtx, nss)->getCatalogId();
        std::string indexIdent =
            _storageEngine->getCatalog()->getIndexIdent(opCtx, catalogId, indexName);
        return dropIdent(opCtx->recoveryUnit(), indexIdent);
    }

    Status dropIdent(RecoveryUnit* ru, StringData ident) {
        return _storageEngine->getEngine()->dropIdent(ru, ident);
    }

    StatusWith<StorageEngine::ReconcileResult> reconcile(OperationContext* opCtx) {
        Lock::GlobalLock globalLock{opCtx, MODE_IX};
        return _storageEngine->reconcileCatalogAndIdents(
            opCtx, Timestamp::min(), StorageEngine::LastShutdownState::kClean);
    }

    StatusWith<StorageEngine::ReconcileResult> reconcileAfterUncleanShutdown(
        OperationContext* opCtx) {
        return _storageEngine->reconcileCatalogAndIdents(
            opCtx, Timestamp::min(), StorageEngine::LastShutdownState::kUnclean);
    }

    std::vector<std::string> getAllKVEngineIdents(OperationContext* opCtx) {
        return _storageEngine->getEngine()->getAllIdents(opCtx);
    }

    bool collectionExists(OperationContext* opCtx, const NamespaceString& nss) {
        std::vector<DurableCatalog::EntryIdentifier> allCollections =
            _storageEngine->getCatalog()->getAllCatalogEntries(opCtx);
        return std::count_if(allCollections.begin(), allCollections.end(), [&](auto& entry) {
            return nss == entry.nss;
        });
    }

    bool identExists(OperationContext* opCtx, const std::string& ident) {
        auto idents = getAllKVEngineIdents(opCtx);
        return std::find(idents.begin(), idents.end(), ident) != idents.end();
    }

    /**
     * Create an index with a key of `{<key>: 1}` and a `name` of <key>.
     */
    Status createIndex(OperationContext* opCtx,
                       NamespaceString collNs,
                       std::string key,
                       bool isBackgroundSecondaryBuild) {
        auto buildUUID = UUID::gen();
        auto ret = startIndexBuild(opCtx, collNs, key, isBackgroundSecondaryBuild, buildUUID);
        if (!ret.isOK()) {
            return ret;
        }

        indexBuildSuccess(opCtx, collNs, key);
        return Status::OK();
    }

    Status startIndexBuild(OperationContext* opCtx,
                           NamespaceString collNs,
                           std::string key,
                           bool isBackgroundSecondaryBuild,
                           boost::optional<UUID> buildUUID) {
        BSONObjBuilder builder;
        {
            BSONObjBuilder keyObj;
            builder.append("key", keyObj.append(key, 1).done());
        }
        BSONObj spec = builder.append("name", key).append("v", 2).done();

        Collection* collection =
            CollectionCatalog::get(opCtx)->lookupCollectionByNamespaceForMetadataWrite(opCtx,
                                                                                       collNs);
        auto descriptor = std::make_unique<IndexDescriptor>(IndexNames::findPluginName(spec), spec);

        auto ret = collection->prepareForIndexBuild(
            opCtx, descriptor.get(), buildUUID, isBackgroundSecondaryBuild);
        return ret;
    }

    void indexBuildSuccess(OperationContext* opCtx, NamespaceString collNs, std::string key) {
        Collection* collection =
            CollectionCatalog::get(opCtx)->lookupCollectionByNamespaceForMetadataWrite(opCtx,
                                                                                       collNs);
        auto descriptor = collection->getIndexCatalog()->findIndexByName(
            opCtx,
            key,
            IndexCatalog::InclusionPolicy::kReady | IndexCatalog::InclusionPolicy::kUnfinished);
        collection->indexBuildSuccess(opCtx, descriptor->getEntry());
    }

    Status removeEntry(OperationContext* opCtx, StringData collNs, DurableCatalog* catalog) {
        CollectionPtr collection = CollectionCatalog::get(opCtx)->lookupCollectionByNamespace(
            opCtx, NamespaceString(collNs));
        return dynamic_cast<DurableCatalogImpl*>(catalog)->_removeEntry(opCtx,
                                                                        collection->getCatalogId());
    }

    StorageEngine* _storageEngine;
};

class StorageEngineRepairTest : public StorageEngineTest {
public:
    StorageEngineRepairTest()
        : StorageEngineTest(Options{}.repair(RepairAction::kRepair).ephemeral(false)) {}

    void tearDown() {
        auto repairObserver = StorageRepairObserver::get(getGlobalServiceContext());
        ASSERT(repairObserver->isDone());

        auto asString = [](const StorageRepairObserver::Modification& mod) {
            return mod.getDescription();
        };
        auto modifications = repairObserver->getModifications();
        LOGV2(24150,
              "Modifications",
              "modifications"_attr =
                  logv2::seqLog(boost::make_transform_iterator(modifications.begin(), asString),
                                boost::make_transform_iterator(modifications.end(), asString)));
    }
};

class StorageEngineTestNotEphemeral : public StorageEngineTest {
public:
    StorageEngineTestNotEphemeral() : StorageEngineTest(Options{}.ephemeral(false)){};
};

}  // namespace mongo

#undef MONGO_LOGV2_DEFAULT_COMPONENT