summaryrefslogtreecommitdiff
path: root/src/mongo/db/s/config/sharding_catalog_manager_shard_collection_test.cpp
blob: b6b937722e6128649bb26d5fa5c502f02b9c62c9 (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
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
/**
 *    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_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kSharding

#include "mongo/platform/basic.h"

#include <set>
#include <string>
#include <vector>

#include "mongo/client/read_preference.h"
#include "mongo/client/remote_command_targeter_factory_mock.h"
#include "mongo/client/remote_command_targeter_mock.h"
#include "mongo/db/s/config/initial_split_policy.h"
#include "mongo/db/s/config/sharding_catalog_manager.h"
#include "mongo/rpc/metadata/tracking_metadata.h"
#include "mongo/s/catalog/type_chunk.h"
#include "mongo/s/catalog/type_shard.h"
#include "mongo/s/client/shard_registry.h"
#include "mongo/s/config_server_test_fixture.h"
#include "mongo/s/grid.h"
#include "mongo/s/shard_key_pattern.h"
#include "mongo/util/log.h"
#include "mongo/util/scopeguard.h"
#include "mongo/util/time_support.h"

namespace mongo {
namespace {

using executor::NetworkInterfaceMock;
using executor::RemoteCommandRequest;
using executor::RemoteCommandResponse;
using executor::TaskExecutor;
using std::set;
using std::string;
using std::vector;
using unittest::assertGet;

class ShardCollectionTestBase : public ConfigServerTestFixture {
protected:
    void expectSplitVector(const HostAndPort& shardHost,
                           const ShardKeyPattern& keyPattern,
                           const BSONObj& splitPoints) {
        onCommand([&](const RemoteCommandRequest& request) {
            ASSERT_EQUALS(shardHost, request.target);
            string cmdName = request.cmdObj.firstElement().fieldName();
            ASSERT_EQUALS("splitVector", cmdName);
            ASSERT_EQUALS(kNamespace.ns(),
                          request.cmdObj["splitVector"].String());  // splitVector uses full ns

            ASSERT_BSONOBJ_EQ(keyPattern.toBSON(), request.cmdObj["keyPattern"].Obj());
            ASSERT_BSONOBJ_EQ(keyPattern.getKeyPattern().globalMin(), request.cmdObj["min"].Obj());
            ASSERT_BSONOBJ_EQ(keyPattern.getKeyPattern().globalMax(), request.cmdObj["max"].Obj());
            ASSERT_EQUALS(64 * 1024 * 1024ULL,
                          static_cast<uint64_t>(request.cmdObj["maxChunkSizeBytes"].numberLong()));
            ASSERT_EQUALS(0, request.cmdObj["maxSplitPoints"].numberLong());
            ASSERT_EQUALS(0, request.cmdObj["maxChunkObjects"].numberLong());

            ASSERT_BSONOBJ_EQ(
                ReadPreferenceSetting(ReadPreference::PrimaryPreferred).toContainingBSON(),
                rpc::TrackingMetadata::removeTrackingData(request.metadata));

            return BSON("ok" << 1 << "splitKeys" << splitPoints);
        });
    }

    const ShardId testPrimaryShard{"shard0"};
    const NamespaceString kNamespace{"db1.foo"};

private:
    const HostAndPort configHost{"configHost1"};
    const ConnectionString configCS{ConnectionString::forReplicaSet("configReplSet", {configHost})};
    const HostAndPort clientHost{"clientHost1"};
};


// Tests which exercise the ShardingCatalogManager::shardCollection logic, which is what the config
// server uses to shard collections, when the '_shardsvrShardCollection' command is not available
// (fast initial split optimization)
class ConfigServerShardCollectionTest : public ShardCollectionTestBase {
protected:
    void checkWrittenChunks(const std::vector<ChunkType>& expectedChunks) {
        const auto grid = Grid::get(operationContext());
        const auto catalogClient = grid->catalogClient();
        repl::OpTime unusedOpTime;
        const auto writtenChunks =
            assertGet(catalogClient->getChunks(operationContext(),
                                               BSON("ns" << kNamespace.ns()),
                                               BSON("min" << 1),
                                               boost::none,
                                               &unusedOpTime,
                                               repl::ReadConcernLevel::kLocalReadConcern));
        ASSERT_EQ(expectedChunks.size(), writtenChunks.size());

        auto itE = expectedChunks.begin();
        auto itW = writtenChunks.begin();
        for (; itE != expectedChunks.end(); itE++, itW++) {
            const auto& expected = *itE;
            const auto& written = *itW;
            ASSERT_BSONOBJ_EQ(expected.getMin(), expected.getMin());
            ASSERT_BSONOBJ_EQ(expected.getMax(), expected.getMax());
            ASSERT_EQ(expected.getShard(), written.getShard());
        }
    }

    const ShardKeyPattern keyPattern{BSON("_id" << 1)};
    const BSONObj defaultCollation;
};

TEST_F(ConfigServerShardCollectionTest, Partially_Written_Chunks_Present) {
    ShardType shard;
    shard.setName("shard0");
    shard.setHost("shardHost");
    ASSERT_OK(setupShards(vector<ShardType>{shard}));

    setupDatabase(kNamespace.db().toString(), shard.getName(), true);

    // Set up chunks in the collection, indicating that another mongos must have already started
    // sharding the collection.
    ChunkType chunk;
    chunk.setNS(kNamespace);
    chunk.setVersion(ChunkVersion(2, 0, OID::gen()));
    chunk.setShard(shard.getName());
    chunk.setMin(BSON("_id" << 1));
    chunk.setMax(BSON("_id" << 5));
    ASSERT_OK(setupChunks({chunk}));

    ASSERT_THROWS_CODE(ShardingCatalogManager::get(operationContext())
                           ->shardCollection(operationContext(),
                                             kNamespace,
                                             boost::none,  // UUID
                                             keyPattern,
                                             defaultCollation,
                                             false,
                                             {},
                                             false,  // isFromMapReduce
                                             testPrimaryShard),
                       AssertionException,
                       ErrorCodes::ManualInterventionRequired);
}

TEST_F(ConfigServerShardCollectionTest, RangeSharding_ForMapReduce_NoInitialSplitPoints) {
    const HostAndPort shardHost{"shardHost"};
    ShardType shard;
    shard.setName("shard0");
    shard.setHost(shardHost.toString());

    std::unique_ptr<RemoteCommandTargeterMock> targeter(
        stdx::make_unique<RemoteCommandTargeterMock>());
    targeter->setConnectionStringReturnValue(ConnectionString(shardHost));
    targeter->setFindHostReturnValue(shardHost);
    targeterFactory()->addTargeterToReturn(ConnectionString(shardHost), std::move(targeter));

    ASSERT_OK(setupShards(vector<ShardType>{shard}));

    setupDatabase(kNamespace.db().toString(), shard.getName(), true);

    // Now start actually sharding the collection.
    auto future = launchAsync([&] {
        ThreadClient tc("Test", getServiceContext());
        auto opCtx = cc().makeOperationContext();
        ShardingCatalogManager::get(operationContext())
            ->shardCollection(opCtx.get(),
                              kNamespace,
                              boost::none,  // UUID
                              keyPattern,
                              defaultCollation,
                              false,
                              {},    // No split points
                              true,  // isFromMapReduce
                              testPrimaryShard);
    });

    // Expect the set shard version for that namespace.
    // We do not check for a specific ChunkVersion, because we cannot easily know the OID that was
    // generated by shardCollection for the first chunk.
    // TODO SERVER-29451: add hooks to the mock storage engine to expect reads and writes.
    expectSetShardVersion(shardHost, shard, kNamespace, boost::none /* expected ChunkVersion */);

    future.timed_get(kFutureTimeout);

    checkWrittenChunks(
        {ChunkType(kNamespace,
                   {keyPattern.getKeyPattern().globalMin(), keyPattern.getKeyPattern().globalMax()},
                   ChunkVersion::IGNORED(),
                   testPrimaryShard)});
}

TEST_F(ConfigServerShardCollectionTest, RangeSharding_ForMapReduce_WithInitialSplitPoints) {
    const HostAndPort shard0Host{"shardHost0"};
    const HostAndPort shard1Host{"shardHost1"};
    const HostAndPort shard2Host{"shardHost2"};

    ShardType shard0;
    shard0.setName("shard0");
    shard0.setHost(shard0Host.toString());

    ShardType shard1;
    shard1.setName("shard1");
    shard1.setHost(shard1Host.toString());

    ShardType shard2;
    shard2.setName("shard2");
    shard2.setHost(shard2Host.toString());

    std::unique_ptr<RemoteCommandTargeterMock> targeter0(
        stdx::make_unique<RemoteCommandTargeterMock>());
    std::unique_ptr<RemoteCommandTargeterMock> targeter1(
        stdx::make_unique<RemoteCommandTargeterMock>());
    std::unique_ptr<RemoteCommandTargeterMock> targeter2(
        stdx::make_unique<RemoteCommandTargeterMock>());
    targeter0->setConnectionStringReturnValue(ConnectionString(shard0Host));
    targeter0->setFindHostReturnValue(shard0Host);
    targeterFactory()->addTargeterToReturn(ConnectionString(shard0Host), std::move(targeter0));
    targeter1->setConnectionStringReturnValue(ConnectionString(shard1Host));
    targeter1->setFindHostReturnValue(shard1Host);
    targeterFactory()->addTargeterToReturn(ConnectionString(shard1Host), std::move(targeter1));
    targeter2->setConnectionStringReturnValue(ConnectionString(shard2Host));
    targeter2->setFindHostReturnValue(shard2Host);
    targeterFactory()->addTargeterToReturn(ConnectionString(shard2Host), std::move(targeter2));

    ASSERT_OK(setupShards(vector<ShardType>{shard0, shard1, shard2}));

    setupDatabase(kNamespace.db().toString(), shard0.getName(), true);

    BSONObj splitPoint0 = BSON("_id" << 1);
    BSONObj splitPoint1 = BSON("_id" << 100);
    BSONObj splitPoint2 = BSON("_id" << 200);
    BSONObj splitPoint3 = BSON("_id" << 300);

    // Now start actually sharding the collection.
    auto future = launchAsync([&] {
        ThreadClient tc("Test", getServiceContext());
        auto opCtx = cc().makeOperationContext();
        ShardingCatalogManager::get(operationContext())
            ->shardCollection(opCtx.get(),
                              kNamespace,
                              boost::none,  // UUID
                              keyPattern,
                              defaultCollation,
                              true,
                              {splitPoint0, splitPoint1, splitPoint2, splitPoint3},
                              true,  // isFromMapReduce
                              testPrimaryShard);
    });

    // Expect the set shard version for that namespace
    // We do not check for a specific ChunkVersion, because we cannot easily know the OID that was
    // generated by shardCollection for the first chunk.
    // TODO SERVER-29451: add hooks to the mock storage engine to expect reads and writes.
    expectSetShardVersion(shard0Host, shard0, kNamespace, boost::none /* expected ChunkVersion */);

    future.timed_get(kFutureTimeout);

    checkWrittenChunks({ChunkType(kNamespace,
                                  ChunkRange{keyPattern.getKeyPattern().globalMin(), splitPoint0},
                                  ChunkVersion::IGNORED(),
                                  shard0.getName()),
                        ChunkType(kNamespace,
                                  ChunkRange{splitPoint0, splitPoint1},
                                  ChunkVersion::IGNORED(),
                                  shard1.getName()),
                        ChunkType(kNamespace,
                                  ChunkRange{splitPoint1, splitPoint2},
                                  ChunkVersion::IGNORED(),
                                  shard2.getName()),
                        ChunkType(kNamespace,
                                  ChunkRange{splitPoint2, splitPoint3},
                                  ChunkVersion::IGNORED(),
                                  shard0.getName()),
                        ChunkType(kNamespace,
                                  ChunkRange{splitPoint3, keyPattern.getKeyPattern().globalMax()},
                                  ChunkVersion::IGNORED(),
                                  shard1.getName())});
}

TEST_F(ConfigServerShardCollectionTest, RangeSharding_NoInitialSplitPoints_NoSplitVectorPoints) {
    const HostAndPort shardHost{"shardHost"};
    ShardType shard;
    shard.setName("shard0");
    shard.setHost(shardHost.toString());

    std::unique_ptr<RemoteCommandTargeterMock> targeter(
        stdx::make_unique<RemoteCommandTargeterMock>());
    targeter->setConnectionStringReturnValue(ConnectionString(shardHost));
    targeter->setFindHostReturnValue(shardHost);
    targeterFactory()->addTargeterToReturn(ConnectionString(shardHost), std::move(targeter));

    ASSERT_OK(setupShards(vector<ShardType>{shard}));

    setupDatabase(kNamespace.db().toString(), shard.getName(), true);

    // Now start actually sharding the collection.
    auto future = launchAsync([&] {
        ThreadClient tc("Test", getServiceContext());
        auto opCtx = cc().makeOperationContext();
        ShardingCatalogManager::get(operationContext())
            ->shardCollection(opCtx.get(),
                              kNamespace,
                              boost::none,  // UUID
                              keyPattern,
                              defaultCollation,
                              false,
                              {},     // No split points
                              false,  // isFromMapReduce
                              testPrimaryShard);
    });

    // Respond to the splitVector command sent to the shard to figure out initial split points.
    expectSplitVector(shardHost, keyPattern, BSONObj());

    // Expect the set shard version for that namespace.
    // We do not check for a specific ChunkVersion, because we cannot easily know the OID that was
    // generated by shardCollection for the first chunk.
    // TODO SERVER-29451: add hooks to the mock storage engine to expect reads and writes.
    expectSetShardVersion(shardHost, shard, kNamespace, boost::none /* expected ChunkVersion */);

    future.timed_get(kFutureTimeout);

    checkWrittenChunks(
        {ChunkType(kNamespace,
                   {keyPattern.getKeyPattern().globalMin(), keyPattern.getKeyPattern().globalMax()},
                   ChunkVersion::IGNORED(),
                   testPrimaryShard)});
}

TEST_F(ConfigServerShardCollectionTest, RangeSharding_NoInitialSplitPoints_WithSplitVectorPoints) {
    const HostAndPort shardHost{"shardHost"};
    ShardType shard;
    shard.setName("shard0");
    shard.setHost(shardHost.toString());

    std::unique_ptr<RemoteCommandTargeterMock> targeter(
        stdx::make_unique<RemoteCommandTargeterMock>());
    targeter->setConnectionStringReturnValue(ConnectionString(shardHost));
    targeter->setFindHostReturnValue(shardHost);
    targeterFactory()->addTargeterToReturn(ConnectionString(shardHost), std::move(targeter));

    ASSERT_OK(setupShards(vector<ShardType>{shard}));

    setupDatabase(kNamespace.db().toString(), shard.getName(), true);

    // Now start actually sharding the collection.
    auto future = launchAsync([&] {
        ThreadClient tc("Test", getServiceContext());
        auto opCtx = cc().makeOperationContext();
        ShardingCatalogManager::get(operationContext())
            ->shardCollection(opCtx.get(),
                              kNamespace,
                              boost::none,  // UUID
                              keyPattern,
                              defaultCollation,
                              false,
                              {},     // No split points
                              false,  // isFromMapReduce
                              testPrimaryShard);
    });

    BSONObj splitPoint0 = BSON("_id" << 1);
    BSONObj splitPoint1 = BSON("_id" << 100);
    BSONObj splitPoint2 = BSON("_id" << 200);
    BSONObj splitPoint3 = BSON("_id" << 300);

    // Respond to the splitVector command sent to the shard to figure out initial split points.
    expectSplitVector(shardHost,
                      keyPattern,
                      BSON_ARRAY(splitPoint0 << splitPoint1 << splitPoint2 << splitPoint3));

    // Expect the set shard version for that namespace
    // We do not check for a specific ChunkVersion, because we cannot easily know the OID that was
    // generated by shardCollection for the first chunk.
    // TODO SERVER-29451: add hooks to the mock storage engine to expect reads and writes.
    expectSetShardVersion(shardHost, shard, kNamespace, boost::none);

    future.timed_get(kFutureTimeout);

    checkWrittenChunks({ChunkType(kNamespace,
                                  ChunkRange{keyPattern.getKeyPattern().globalMin(), splitPoint0},
                                  ChunkVersion::IGNORED(),
                                  testPrimaryShard),
                        ChunkType(kNamespace,
                                  ChunkRange{splitPoint0, splitPoint1},
                                  ChunkVersion::IGNORED(),
                                  testPrimaryShard),
                        ChunkType(kNamespace,
                                  ChunkRange{splitPoint1, splitPoint2},
                                  ChunkVersion::IGNORED(),
                                  testPrimaryShard),
                        ChunkType(kNamespace,
                                  ChunkRange{splitPoint2, splitPoint3},
                                  ChunkVersion::IGNORED(),
                                  testPrimaryShard),
                        ChunkType(kNamespace,
                                  ChunkRange{splitPoint3, keyPattern.getKeyPattern().globalMax()},
                                  ChunkVersion::IGNORED(),
                                  testPrimaryShard)});
}

TEST_F(ConfigServerShardCollectionTest, RangeSharding_WithInitialSplitPoints_NoSplitVectorPoints) {
    const HostAndPort shardHost{"shardHost"};
    ShardType shard;
    shard.setName("shard0");
    shard.setHost(shardHost.toString());

    std::unique_ptr<RemoteCommandTargeterMock> targeter(
        stdx::make_unique<RemoteCommandTargeterMock>());
    targeter->setConnectionStringReturnValue(ConnectionString(shardHost));
    targeter->setFindHostReturnValue(shardHost);
    targeterFactory()->addTargeterToReturn(ConnectionString(shardHost), std::move(targeter));

    ASSERT_OK(setupShards(vector<ShardType>{shard}));

    setupDatabase(kNamespace.db().toString(), shard.getName(), true);

    BSONObj splitPoint0 = BSON("_id" << 1);
    BSONObj splitPoint1 = BSON("_id" << 100);
    BSONObj splitPoint2 = BSON("_id" << 200);
    BSONObj splitPoint3 = BSON("_id" << 300);

    // Now start actually sharding the collection.
    auto future = launchAsync([&] {
        ThreadClient tc("Test", getServiceContext());
        auto opCtx = cc().makeOperationContext();
        ShardingCatalogManager::get(operationContext())
            ->shardCollection(opCtx.get(),
                              kNamespace,
                              boost::none,  // UUID
                              keyPattern,
                              defaultCollation,
                              false,
                              {splitPoint0, splitPoint1, splitPoint2, splitPoint3},
                              false,  // isFromMapReduce
                              testPrimaryShard);
    });

    // Expect the set shard version for that namespace
    // We do not check for a specific ChunkVersion, because we cannot easily know the OID that was
    // generated by shardCollection for the first chunk.
    // TODO SERVER-29451: add hooks to the mock storage engine to expect reads and writes.
    expectSetShardVersion(shardHost, shard, kNamespace, boost::none);

    future.timed_get(kFutureTimeout);

    checkWrittenChunks({ChunkType(kNamespace,
                                  ChunkRange{keyPattern.getKeyPattern().globalMin(), splitPoint0},
                                  ChunkVersion::IGNORED(),
                                  testPrimaryShard),
                        ChunkType(kNamespace,
                                  ChunkRange{splitPoint0, splitPoint1},
                                  ChunkVersion::IGNORED(),
                                  testPrimaryShard),
                        ChunkType(kNamespace,
                                  ChunkRange{splitPoint1, splitPoint2},
                                  ChunkVersion::IGNORED(),
                                  testPrimaryShard),
                        ChunkType(kNamespace,
                                  ChunkRange{splitPoint2, splitPoint3},
                                  ChunkVersion::IGNORED(),
                                  testPrimaryShard),
                        ChunkType(kNamespace,
                                  ChunkRange{splitPoint3, keyPattern.getKeyPattern().globalMax()},
                                  ChunkVersion::IGNORED(),
                                  testPrimaryShard)});
}


// Direct tests for InitialSplitPolicy::createFirstChunks which is the base call for both the config
// server and shard server's shard collection logic
class CreateFirstChunksTest : public ShardCollectionTestBase {
protected:
    const ShardKeyPattern kShardKeyPattern{BSON("x" << 1)};
};

TEST_F(CreateFirstChunksTest, Split_Disallowed_With_Both_SplitPoints_And_Zones) {
    ASSERT_THROWS_CODE(
        InitialSplitPolicy::createFirstChunks(
            operationContext(),
            kNamespace,
            kShardKeyPattern,
            ShardId("shard1"),
            {BSON("x" << 0)},
            {TagsType(kNamespace,
                      "TestZone",
                      ChunkRange(kShardKeyPattern.getKeyPattern().globalMin(), BSON("x" << 0)))},
            true /* isEmpty */),
        AssertionException,
        ErrorCodes::InvalidOptions);

    ASSERT_THROWS_CODE(
        InitialSplitPolicy::createFirstChunks(
            operationContext(),
            kNamespace,
            kShardKeyPattern,
            ShardId("shard1"),
            {BSON("x" << 0)}, /* No split points */
            {TagsType(kNamespace,
                      "TestZone",
                      ChunkRange(kShardKeyPattern.getKeyPattern().globalMin(), BSON("x" << 0)))},
            false /* isEmpty */),
        AssertionException,
        ErrorCodes::InvalidOptions);
}

TEST_F(CreateFirstChunksTest, NonEmptyCollection_SplitPoints_FromSplitVector_ManyChunksToPrimary) {
    const std::vector<ShardType> kShards{ShardType("shard0", "rs0/shard0:123"),
                                         ShardType("shard1", "rs1/shard1:123"),
                                         ShardType("shard2", "rs2/shard2:123")};

    const auto connStr = assertGet(ConnectionString::parse(kShards[1].getHost()));

    std::unique_ptr<RemoteCommandTargeterMock> targeter(
        stdx::make_unique<RemoteCommandTargeterMock>());
    targeter->setConnectionStringReturnValue(connStr);
    targeter->setFindHostReturnValue(connStr.getServers()[0]);
    targeterFactory()->addTargeterToReturn(connStr, std::move(targeter));

    ASSERT_OK(setupShards(kShards));
    shardRegistry()->reload(operationContext());

    auto future = launchAsync([&] {
        ThreadClient tc("Test", getServiceContext());
        auto opCtx = cc().makeOperationContext();
        return InitialSplitPolicy::createFirstChunks(opCtx.get(),
                                                     kNamespace,
                                                     kShardKeyPattern,
                                                     ShardId("shard1"),
                                                     {}, /* No split points */
                                                     {}, /* No zones */
                                                     false /* isEmpty */);
    });

    expectSplitVector(connStr.getServers()[0], kShardKeyPattern, BSON_ARRAY(BSON("x" << 0)));

    const auto& firstChunks = future.timed_get(kFutureTimeout);
    ASSERT_EQ(2U, firstChunks.chunks.size());
    ASSERT_EQ(kShards[1].getName(), firstChunks.chunks[0].getShard());
    ASSERT_EQ(kShards[1].getName(), firstChunks.chunks[1].getShard());
}

TEST_F(CreateFirstChunksTest, NonEmptyCollection_SplitPoints_FromClient_ManyChunksToPrimary) {
    const std::vector<ShardType> kShards{ShardType("shard0", "rs0/shard0:123"),
                                         ShardType("shard1", "rs1/shard1:123"),
                                         ShardType("shard2", "rs2/shard2:123")};

    const auto connStr = assertGet(ConnectionString::parse(kShards[1].getHost()));

    std::unique_ptr<RemoteCommandTargeterMock> targeter(
        stdx::make_unique<RemoteCommandTargeterMock>());
    targeter->setConnectionStringReturnValue(connStr);
    targeter->setFindHostReturnValue(connStr.getServers()[0]);
    targeterFactory()->addTargeterToReturn(connStr, std::move(targeter));

    ASSERT_OK(setupShards(kShards));
    shardRegistry()->reload(operationContext());

    auto future = launchAsync([&] {
        ThreadClient tc("Test", getServiceContext());
        auto opCtx = cc().makeOperationContext();
        return InitialSplitPolicy::createFirstChunks(opCtx.get(),
                                                     kNamespace,
                                                     kShardKeyPattern,
                                                     ShardId("shard1"),
                                                     {BSON("x" << 0)},
                                                     {}, /* No zones */
                                                     false /* isEmpty */);
    });

    const auto& firstChunks = future.timed_get(kFutureTimeout);
    ASSERT_EQ(2U, firstChunks.chunks.size());
    ASSERT_EQ(kShards[1].getName(), firstChunks.chunks[0].getShard());
    ASSERT_EQ(kShards[1].getName(), firstChunks.chunks[1].getShard());
}

TEST_F(CreateFirstChunksTest, NonEmptyCollection_WithZones_OneChunkToPrimary) {
    const std::vector<ShardType> kShards{ShardType("shard0", "rs0/shard0:123", {"TestZone"}),
                                         ShardType("shard1", "rs1/shard1:123", {"TestZone"}),
                                         ShardType("shard2", "rs2/shard2:123")};
    ASSERT_OK(setupShards(kShards));
    shardRegistry()->reload(operationContext());

    const auto firstChunks = InitialSplitPolicy::createFirstChunks(
        operationContext(),
        kNamespace,
        kShardKeyPattern,
        ShardId("shard1"),
        {}, /* No split points */
        {TagsType(kNamespace,
                  "TestZone",
                  ChunkRange(kShardKeyPattern.getKeyPattern().globalMin(), BSON("x" << 0)))},
        false /* isEmpty */);

    ASSERT_EQ(1U, firstChunks.chunks.size());
    ASSERT_EQ(kShards[1].getName(), firstChunks.chunks[0].getShard());
}

TEST_F(CreateFirstChunksTest, EmptyCollection_SplitPoints_FromClient_ManyChunksDistributed) {
    const std::vector<ShardType> kShards{ShardType("shard0", "rs0/shard0:123"),
                                         ShardType("shard1", "rs1/shard1:123"),
                                         ShardType("shard2", "rs2/shard2:123")};

    const auto connStr = assertGet(ConnectionString::parse(kShards[1].getHost()));

    std::unique_ptr<RemoteCommandTargeterMock> targeter(
        stdx::make_unique<RemoteCommandTargeterMock>());
    targeter->setConnectionStringReturnValue(connStr);
    targeter->setFindHostReturnValue(connStr.getServers()[0]);
    targeterFactory()->addTargeterToReturn(connStr, std::move(targeter));

    ASSERT_OK(setupShards(kShards));
    shardRegistry()->reload(operationContext());

    auto future = launchAsync([&] {
        ThreadClient tc("Test", getServiceContext());
        auto opCtx = cc().makeOperationContext();
        return InitialSplitPolicy::createFirstChunks(opCtx.get(),
                                                     kNamespace,
                                                     kShardKeyPattern,
                                                     ShardId("shard1"),
                                                     {BSON("x" << 0), BSON("x" << 100)},
                                                     {}, /* No zones */
                                                     true /* isEmpty */);
    });

    const auto& firstChunks = future.timed_get(kFutureTimeout);
    ASSERT_EQ(3U, firstChunks.chunks.size());
    ASSERT_EQ(kShards[0].getName(), firstChunks.chunks[0].getShard());
    ASSERT_EQ(kShards[1].getName(), firstChunks.chunks[1].getShard());
    ASSERT_EQ(kShards[2].getName(), firstChunks.chunks[2].getShard());
}

TEST_F(CreateFirstChunksTest, EmptyCollection_NoSplitPoints_OneChunkToPrimary) {
    const std::vector<ShardType> kShards{ShardType("shard0", "rs0/shard0:123"),
                                         ShardType("shard1", "rs1/shard1:123"),
                                         ShardType("shard2", "rs2/shard2:123")};

    const auto connStr = assertGet(ConnectionString::parse(kShards[1].getHost()));

    std::unique_ptr<RemoteCommandTargeterMock> targeter(
        stdx::make_unique<RemoteCommandTargeterMock>());
    targeter->setConnectionStringReturnValue(connStr);
    targeter->setFindHostReturnValue(connStr.getServers()[0]);
    targeterFactory()->addTargeterToReturn(connStr, std::move(targeter));

    ASSERT_OK(setupShards(kShards));
    shardRegistry()->reload(operationContext());

    auto future = launchAsync([&] {
        ThreadClient tc("Test", getServiceContext());
        auto opCtx = cc().makeOperationContext();
        return InitialSplitPolicy::createFirstChunks(opCtx.get(),
                                                     kNamespace,
                                                     kShardKeyPattern,
                                                     ShardId("shard1"),
                                                     {}, /* No split points */
                                                     {}, /* No zones */
                                                     true /* isEmpty */);
    });

    const auto& firstChunks = future.timed_get(kFutureTimeout);
    ASSERT_EQ(1U, firstChunks.chunks.size());
    ASSERT_EQ(kShards[1].getName(), firstChunks.chunks[0].getShard());
}

TEST_F(CreateFirstChunksTest, EmptyCollection_WithZones_ManyChunksOnFirstZoneShard) {
    const std::vector<ShardType> kShards{ShardType("shard0", "rs0/shard0:123", {"TestZone"}),
                                         ShardType("shard1", "rs1/shard1:123", {"TestZone"}),
                                         ShardType("shard2", "rs2/shard2:123")};
    ASSERT_OK(setupShards(kShards));
    shardRegistry()->reload(operationContext());

    const auto firstChunks = InitialSplitPolicy::createFirstChunks(
        operationContext(),
        kNamespace,
        kShardKeyPattern,
        ShardId("shard1"),
        {}, /* No split points */
        {TagsType(kNamespace,
                  "TestZone",
                  ChunkRange(kShardKeyPattern.getKeyPattern().globalMin(), BSON("x" << 0)))},
        true /* isEmpty */);

    ASSERT_EQ(2U, firstChunks.chunks.size());
    ASSERT_EQ(kShards[0].getName(), firstChunks.chunks[0].getShard());
    ASSERT_EQ(kShards[0].getName(), firstChunks.chunks[1].getShard());
}

}  // namespace
}  // namespace mongo