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
|
/**
* Copyright (C) 2022-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/db/commands/list_collections_filter.h"
#include "mongo/db/dbdirectclient.h"
#include "mongo/db/op_observer/op_observer_noop.h"
#include "mongo/db/op_observer/op_observer_registry.h"
#include "mongo/db/read_write_concern_defaults_cache_lookup_mock.h"
#include "mongo/db/repl/database_cloner_gen.h"
#include "mongo/db/repl/primary_only_service_test_fixture.h"
#include "mongo/db/repl/storage_interface.h"
#include "mongo/db/repl/storage_interface_mock.h"
#include "mongo/db/s/global_index/global_index_cloning_external_state.h"
#include "mongo/db/s/global_index/global_index_cloning_service.h"
#include "mongo/db/s/global_index/global_index_util.h"
#include "mongo/db/s/resharding/resharding_service_test_helpers.h"
#include "mongo/db/session/logical_session_cache_noop.h"
#include "mongo/db/session/session_catalog_mongod.h"
#include "mongo/db/transaction/session_catalog_mongod_transaction_interface_impl.h"
#include "mongo/idl/server_parameter_test_util.h"
#include "mongo/logv2/log.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kTest
namespace mongo {
namespace global_index {
namespace {
using StateTransitionController =
resharding_service_test_helpers::StateTransitionController<GlobalIndexClonerStateEnum>;
using OpObserverForTest =
resharding_service_test_helpers::StateTransitionControllerOpObserver<GlobalIndexClonerStateEnum,
GlobalIndexClonerDoc>;
using PauseDuringStateTransitions =
resharding_service_test_helpers::PauseDuringStateTransitions<GlobalIndexClonerStateEnum>;
const ShardId kRecipientShardId{"myShardId"};
const NamespaceString kSourceNss{"sourcedb", "sourcecollection"};
constexpr auto kSourceShardKey = "key"_sd;
class GlobalIndexExternalStateForTest : public GlobalIndexCloningService::CloningExternalState {
public:
ShardId myShardId(ServiceContext* serviceContext) const override {
return kRecipientShardId;
}
ChunkManager getShardedCollectionRoutingInfo(OperationContext* opCtx,
const NamespaceString& nss) const override {
invariant(nss == kSourceNss);
const OID epoch = OID::gen();
std::vector<ChunkType> chunks = {
ChunkType{_sourceUUID,
ChunkRange{BSON(kSourceShardKey << MINKEY), BSON(kSourceShardKey << MAXKEY)},
ChunkVersion({epoch, Timestamp(1, 1)}, {100, 0}),
_someDonorId}};
auto rt = RoutingTableHistory::makeNew(kSourceNss,
_sourceUUID,
BSON(kSourceShardKey << 1),
nullptr /* defaultCollator */,
false /* unique */,
std::move(epoch),
Timestamp(1, 1),
boost::none /* timeseriesFields */,
boost::none /* reshardingFields */,
boost::none /* chunkSizeBytes */,
true /* allowMigrations */,
chunks);
return ChunkManager(_someDonorId,
DatabaseVersion(UUID::gen(), Timestamp(1, 1)),
_makeStandaloneRoutingTableHistory(std::move(rt)),
boost::none /* clusterTime */);
}
private:
RoutingTableHistoryValueHandle _makeStandaloneRoutingTableHistory(
RoutingTableHistory rt) const {
const auto version = rt.getVersion();
return RoutingTableHistoryValueHandle(
std::make_shared<RoutingTableHistory>(std::move(rt)),
ComparableChunkVersion::makeComparableChunkVersion(version));
}
const UUID _sourceUUID{UUID::gen()};
const ShardId _someDonorId{"otherShardId"};
};
class MockGlobalIndexClonerFetcher : public GlobalIndexClonerFetcherInterface {
public:
void setResultList(std::list<FetchedEntry> newResults) {
_docs = std::move(newResults);
}
boost::optional<FetchedEntry> getNext(OperationContext* opCtx) override {
if (_docs.empty()) {
return boost::none;
}
auto ret = _docs.front();
_docs.pop_front();
return ret;
}
private:
std::list<FetchedEntry> _docs;
};
class GlobalIndexCloningFetcherFactoryForTest : public GlobalIndexClonerFetcherFactoryInterface {
public:
explicit GlobalIndexCloningFetcherFactoryForTest(MockGlobalIndexClonerFetcher* mockFetcher)
: _mockFetcher(mockFetcher) {}
std::unique_ptr<GlobalIndexClonerFetcherInterface> make(
NamespaceString nss,
UUID collUUId,
UUID indexUUID,
ShardId myShardId,
Timestamp minFetchTimestamp,
KeyPattern sourceShardKeyPattern,
KeyPattern globalIndexPattern) override {
return std::make_unique<MockGlobalIndexClonerFetcher>(*_mockFetcher);
}
private:
MockGlobalIndexClonerFetcher* _mockFetcher;
};
class GlobalIndexCloningServiceForTest : public GlobalIndexCloningService {
public:
explicit GlobalIndexCloningServiceForTest(ServiceContext* serviceContext,
MockGlobalIndexClonerFetcher* mockFetcher)
: GlobalIndexCloningService(serviceContext),
_serviceContext(serviceContext),
_mockFetcher(mockFetcher) {}
std::shared_ptr<repl::PrimaryOnlyService::Instance> constructInstance(
BSONObj initialState) override {
return std::make_shared<GlobalIndexCloningService::CloningStateMachine>(
_serviceContext,
this,
std::make_unique<GlobalIndexExternalStateForTest>(),
std::make_unique<GlobalIndexCloningFetcherFactoryForTest>(_mockFetcher),
GlobalIndexClonerDoc::parse(IDLParserContext{"GlobalIndexCloningServiceForTest"},
initialState));
}
private:
ServiceContext* _serviceContext;
MockGlobalIndexClonerFetcher* _mockFetcher;
};
GlobalIndexCloningService::InstanceID extractInstanceId(const GlobalIndexClonerDoc& doc) {
return BSON("_id" << doc.getIndexCollectionUUID());
}
using GlobalIndexStateMachine = GlobalIndexCloningServiceForTest::CloningStateMachine;
class GlobalIndexClonerServiceTest : public repl::PrimaryOnlyServiceMongoDTest {
public:
std::unique_ptr<repl::PrimaryOnlyService> makeService(ServiceContext* serviceContext) override {
return std::make_unique<GlobalIndexCloningServiceForTest>(serviceContext, &_mockFetcher);
}
void setUp() override {
repl::PrimaryOnlyServiceMongoDTest::setUp();
auto serviceContext = getServiceContext();
auto storageMock = std::make_unique<repl::StorageInterfaceMock>();
repl::StorageInterface::set(serviceContext, std::move(storageMock));
// The ReadWriteConcernDefaults decoration on the service context won't always be created,
// so we should manually instantiate it to ensure it exists in our tests.
ReadWriteConcernDefaults::create(getServiceContext(), _lookupMock.getFetchDefaultsFn());
_stateTransitionController = std::make_shared<StateTransitionController>();
_opObserverRegistry->addObserver(
std::make_unique<OpObserverForTest>(_stateTransitionController,
NamespaceString::kGlobalIndexClonerNamespace,
[](const GlobalIndexClonerDoc& stateDoc) {
return stateDoc.getMutableState().getState();
}));
// Create config.transactions collection
auto opCtx = serviceContext->makeOperationContext(Client::getCurrent());
DBDirectClient client(opCtx.get());
client.createCollection(NamespaceString::kSessionTransactionsTableNamespace.ns());
client.createIndexes(NamespaceString::kSessionTransactionsTableNamespace.ns(),
{MongoDSessionCatalog::getConfigTxnPartialIndexSpec()});
MongoDSessionCatalog::set(
getServiceContext(),
std::make_unique<MongoDSessionCatalog>(
std::make_unique<MongoDSessionCatalogTransactionInterfaceImpl>()));
// Session cache is needed otherwise client session info will ignored.
LogicalSessionCache::set(getServiceContext(), std::make_unique<LogicalSessionCacheNoop>());
std::list<GlobalIndexClonerFetcherInterface::FetchedEntry> fetcherResults;
fetcherResults.push_front(
{BSON("_id" << 10 << kSourceShardKey << 20), BSON(_indexKey << 30)});
replaceFetcherResultList(std::move(fetcherResults));
const auto& indexNs = globalIndexNss(kSourceNss, _indexName);
client.createCollection(indexNs.ns());
auto all = client.getCollectionInfos(indexNs.db().toString(),
BSON("name" << indexNs.coll().toString()));
ASSERT_EQ(1, all.size());
_indexCollectionUUID.emplace(uassertStatusOK(UUID::parse(all.front()["info"]["uuid"])));
}
void checkIndexCollection(OperationContext* opCtx) {
DBDirectClient client(opCtx);
MockGlobalIndexClonerFetcher fetcherCopy(_fetcherCopyForVerification);
while (auto next = fetcherCopy.getNext(opCtx)) {
FindCommandRequest query(globalIndexNss(kSourceNss, _indexName));
query.setFilter(BSON("_id" << next->indexKeyValues));
auto doc = client.findOne(query);
ASSERT_TRUE(!doc.isEmpty())
<< "doc with index key: " << next->indexKeyValues
<< " missing in global index output collection: " << dumpOutputColl(opCtx);
}
}
GlobalIndexClonerDoc makeStateDocument() {
return GlobalIndexClonerDoc(*_indexCollectionUUID,
kSourceNss,
_collectionUUID,
_indexName,
_indexSpec,
{},
GlobalIndexClonerStateEnum::kUnused);
}
bool doesCollectionExist(OperationContext* opCtx, const NamespaceString& nss) {
DBDirectClient client(opCtx);
auto collectionInfos = client.getCollectionInfos(
nss.db().toString(), ListCollectionsFilter::makeTypeCollectionFilter());
for (auto&& info : collectionInfos) {
auto coll =
repl::ListCollectionResult::parse(IDLParserContext("doesCollectionExist"), info);
if (coll.getName() == nss.coll()) {
return true;
}
}
return false;
}
StateTransitionController* stateTransitionController() {
return _stateTransitionController.get();
}
void replaceFetcherResultList(
std::list<GlobalIndexClonerFetcherInterface::FetchedEntry> newResults) {
_mockFetcher.setResultList(std::move(newResults));
_fetcherCopyForVerification = _mockFetcher;
}
StringData indexKey() const {
return _indexKey;
}
private:
std::string dumpOutputColl(OperationContext* opCtx) {
DBDirectClient client(opCtx);
FindCommandRequest query(globalIndexNss(kSourceNss, _indexName));
std::ostringstream outputStr;
auto res = client.find(query);
if (!res || !res->more()) {
return "<empty>";
}
outputStr << "docs: " << std::endl;
while (res->more()) {
auto doc = res->next();
outputStr << doc.toString() << std::endl;
}
return outputStr.str();
}
boost::optional<UUID> _indexCollectionUUID;
const UUID _collectionUUID{UUID::gen()};
const std::string _indexName{"global_x_1"};
const StringData _indexKey{"x"};
const BSONObj _indexSpec{BSON("key" << BSON(_indexKey << 1) << "unique" << true)};
ReadWriteConcernDefaultsLookupMock _lookupMock;
std::shared_ptr<StateTransitionController> _stateTransitionController;
MockGlobalIndexClonerFetcher _mockFetcher;
MockGlobalIndexClonerFetcher _fetcherCopyForVerification;
};
TEST_F(GlobalIndexClonerServiceTest, CloneInsertsToGlobalIndexCollection) {
auto doc = makeStateDocument();
auto opCtx = makeOperationContext();
auto rawOpCtx = opCtx.get();
auto cloner = GlobalIndexStateMachine::getOrCreate(rawOpCtx, _service, doc.toBSON());
auto future = cloner->getCompletionFuture();
cloner->getReadyToCommitFuture().get();
cloner->cleanup();
future.get();
ASSERT_TRUE(doesCollectionExist(rawOpCtx, skipIdNss(doc.getNss(), doc.getIndexName())));
checkIndexCollection(rawOpCtx);
}
TEST_F(GlobalIndexClonerServiceTest, ShouldBeSafeToRetryOnStepDown) {
auto doc = makeStateDocument();
auto opCtx = makeOperationContext();
auto rawOpCtx = opCtx.get();
const std::vector<GlobalIndexClonerStateEnum> states{GlobalIndexClonerStateEnum::kCloning,
GlobalIndexClonerStateEnum::kReadyToCommit,
GlobalIndexClonerStateEnum::kDone};
PauseDuringStateTransitions stateTransitionsGuard{stateTransitionController(), states};
auto prevState = GlobalIndexClonerStateEnum::kUnused;
for (const auto& nextState : states) {
LOGV2(6870601,
"Testing next state",
"state"_attr = GlobalIndexClonerState_serializer(nextState));
auto cloner = ([&] {
if (nextState == GlobalIndexClonerStateEnum::kCloning ||
nextState == GlobalIndexClonerStateEnum::kReadyToCommit) {
return GlobalIndexStateMachine::getOrCreate(rawOpCtx, _service, doc.toBSON());
}
return *GlobalIndexStateMachine::lookup(rawOpCtx, _service, extractInstanceId(doc));
})();
if (prevState != GlobalIndexClonerStateEnum::kUnused) {
stateTransitionsGuard.unset(prevState);
}
auto readyToCommitFuture = cloner->getReadyToCommitFuture();
if (nextState == GlobalIndexClonerStateEnum::kDone) {
readyToCommitFuture.get();
cloner->cleanup();
}
stateTransitionsGuard.wait(nextState);
stepDown();
if (nextState != GlobalIndexClonerStateEnum::kDone) {
ASSERT_THROWS(readyToCommitFuture.get(), DBException);
}
// Note: can either throw InterruptDueToRepl or ShutdownInProgress (from executor).
ASSERT_THROWS(cloner->getCompletionFuture().get(), DBException);
stepUp(rawOpCtx);
prevState = nextState;
}
auto cloner = *GlobalIndexStateMachine::lookup(rawOpCtx, _service, extractInstanceId(doc));
stateTransitionsGuard.unset(GlobalIndexClonerStateEnum::kDone);
cloner->cleanup();
cloner->getCompletionFuture().get();
checkIndexCollection(rawOpCtx);
}
TEST_F(GlobalIndexClonerServiceTest, ShouldBeAbleToConsumeMultipleBatchesWorthofDocs) {
std::list<GlobalIndexClonerFetcherInterface::FetchedEntry> fetcherResults;
RAIIServerParameterControllerForTest batchSizeForTest(
"globalIndexClonerServiceFetchBatchMaxSizeBytes", 50);
std::string padding(50, 'x');
// Populate enough to have more than one batch worth of documents.
for (int x = 0; x < 4; x++) {
fetcherResults.push_front({BSON("_id" << x << kSourceShardKey << x),
BSON(indexKey() << (std::to_string(x) + padding))});
}
replaceFetcherResultList(std::move(fetcherResults));
auto doc = makeStateDocument();
auto opCtx = makeOperationContext();
auto rawOpCtx = opCtx.get();
auto cloner = GlobalIndexStateMachine::getOrCreate(rawOpCtx, _service, doc.toBSON());
auto future = cloner->getCompletionFuture();
cloner->getReadyToCommitFuture().get();
cloner->cleanup();
future.get();
ASSERT_TRUE(doesCollectionExist(rawOpCtx, skipIdNss(doc.getNss(), doc.getIndexName())));
checkIndexCollection(rawOpCtx);
}
TEST_F(GlobalIndexClonerServiceTest, ShouldWorkWithEmptyCollection) {
replaceFetcherResultList({});
auto doc = makeStateDocument();
auto opCtx = makeOperationContext();
auto rawOpCtx = opCtx.get();
auto cloner = GlobalIndexStateMachine::getOrCreate(rawOpCtx, _service, doc.toBSON());
auto future = cloner->getCompletionFuture();
cloner->getReadyToCommitFuture().get();
cloner->cleanup();
future.get();
ASSERT_TRUE(doesCollectionExist(rawOpCtx, skipIdNss(doc.getNss(), doc.getIndexName())));
checkIndexCollection(rawOpCtx);
}
} // namespace
} // namespace global_index
} // namespace mongo
|