summaryrefslogtreecommitdiff
path: root/src/mongo/db/s/balancer/balancer_chunk_selection_policy_test.cpp
blob: b0630aaf92fcf27927a22845b41804667606e747 (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
/**
 *    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.
 */

#include "mongo/platform/basic.h"

#include "mongo/db/commands.h"
#include "mongo/db/s/balancer/balancer_chunk_selection_policy_impl.h"
#include "mongo/db/s/balancer/cluster_statistics_impl.h"
#include "mongo/db/s/balancer/migration_test_fixture.h"
#include "mongo/platform/random.h"

namespace mongo {
namespace {

const std::string kDbName = "TestDb";
const NamespaceString kNamespace(kDbName, "TestColl");
const int kSizeOnDisk = 1;

class BalancerChunkSelectionTest : public MigrationTestFixture {
protected:
    BalancerChunkSelectionTest()
        : _random(std::random_device{}()),
          _clusterStats(std::make_unique<ClusterStatisticsImpl>(_random)),
          _chunkSelectionPolicy(
              std::make_unique<BalancerChunkSelectionPolicyImpl>(_clusterStats.get(), _random)) {}

    /**
     * Sets up mock network to expect a listDatabases command and returns a BSON response with
     * a dummy sizeOnDisk.
     */
    void expectListDatabasesCommand() {
        BSONObjBuilder resultBuilder;
        CommandHelpers::appendCommandStatusNoThrow(resultBuilder, Status::OK());

        onCommand([&resultBuilder](const RemoteCommandRequest& request) {
            ASSERT(request.cmdObj["listDatabases"]);
            vector<BSONObj> dbInfos;
            BSONObjBuilder b;
            b.append("name", kDbName);
            b.append("sizeOnDisk", kSizeOnDisk);
            b.append("empty", kSizeOnDisk > 0);
            resultBuilder.append("databases", dbInfos);
            resultBuilder.append("totalSize", kSizeOnDisk);
            return resultBuilder.obj();
        });
    }

    /**
     * Sets up mock network to expect a serverStatus command and returns a BSON response with
     * a dummy version.
     */
    void expectServerStatusCommand() {
        BSONObjBuilder resultBuilder;
        CommandHelpers::appendCommandStatusNoThrow(resultBuilder, Status::OK());

        onCommand([&resultBuilder](const RemoteCommandRequest& request) {
            ASSERT(request.cmdObj["serverStatus"]);
            resultBuilder.append("version", "MONGO_VERSION");
            return resultBuilder.obj();
        });
    }

    /**
     * Sets up mock network for all the shards to expect the commands executed for computing cluster
     * stats, which include listDatabase and serverStatus.
     */
    void expectGetStatsCommands(int numShards) {
        for (int i = 0; i < numShards; i++) {
            expectListDatabasesCommand();
            expectServerStatusCommand();
        }
    }

    /**
     * Returns a new BSON object with the tags appended.
     */
    BSONObj appendTags(const BSONObj shardBSON, std::vector<std::string> tags) {
        BSONObjBuilder appendedShardBSON(shardBSON);
        BSONArrayBuilder tagsBuilder;
        for (auto& tag : tags) {
            tagsBuilder.append(tag);
        }
        tagsBuilder.done();
        appendedShardBSON.append("tags", tagsBuilder.arr());
        return appendedShardBSON.obj();
    }

    BalancerRandomSource _random;
    std::unique_ptr<ClusterStatistics> _clusterStats;
    std::unique_ptr<BalancerChunkSelectionPolicy> _chunkSelectionPolicy;
};

TEST_F(BalancerChunkSelectionTest, TagRangesOverlap) {
    // Set up two shards in the metadata.
    ASSERT_OK(catalogClient()->insertConfigDocument(
        operationContext(), ShardType::ConfigNS, kShard0, kMajorityWriteConcern));
    ASSERT_OK(catalogClient()->insertConfigDocument(
        operationContext(), ShardType::ConfigNS, kShard1, kMajorityWriteConcern));

    // Set up a database and a sharded collection in the metadata.
    ChunkVersion version(2, 0, OID::gen());
    setUpDatabase(kDbName, kShardId0);
    setUpCollection(kNamespace, version);

    // Set up one chunk for the collection in the metadata.
    ChunkType chunk = setUpChunk(
        kNamespace, kKeyPattern.globalMin(), kKeyPattern.globalMax(), kShardId0, version);

    auto assertRangeOverlapConflictWhenMoveChunk = [this, &chunk](const StringMap<ChunkRange>&
                                                                      tagChunkRanges) {
        // Set up two zones whose ranges overlap.
        setUpTags(kNamespace, tagChunkRanges);

        auto future = launchAsync([this, &chunk] {
            // Requesting chunks to be relocated requires running commands on each shard to get
            // shard statistics. Set up dummy hosts for the source shards.
            shardTargeterMock(operationContext(), kShardId0)->setFindHostReturnValue(kShardHost0);
            shardTargeterMock(operationContext(), kShardId1)->setFindHostReturnValue(kShardHost1);

            auto migrateInfoStatus =
                _chunkSelectionPolicy.get()->selectSpecificChunkToMove(operationContext(), chunk);
            ASSERT_EQUALS(ErrorCodes::RangeOverlapConflict, migrateInfoStatus.getStatus().code());
        });

        expectGetStatsCommands(2);
        future.default_timed_get();
        removeAllTags(kNamespace);
    };

    assertRangeOverlapConflictWhenMoveChunk(
        {{"A", {kKeyPattern.globalMin(), BSON(kPattern << -10)}},
         {"B", {BSON(kPattern << -15), kKeyPattern.globalMax()}}});
    assertRangeOverlapConflictWhenMoveChunk(
        {{"A", {kKeyPattern.globalMin(), BSON(kPattern << -5)}},
         {"B", {BSON(kPattern << -10), kKeyPattern.globalMax()}}});
    assertRangeOverlapConflictWhenMoveChunk(
        {{"A", {kKeyPattern.globalMin(), kKeyPattern.globalMax()}},
         {"B", {BSON(kPattern << -15), kKeyPattern.globalMax()}}});
}

TEST_F(BalancerChunkSelectionTest, TagRangeMaxNotAlignedWithChunkMax) {
    // Set up two shards in the metadata.
    ASSERT_OK(catalogClient()->insertConfigDocument(operationContext(),
                                                    ShardType::ConfigNS,
                                                    appendTags(kShard0, {"A"}),
                                                    kMajorityWriteConcern));
    ASSERT_OK(catalogClient()->insertConfigDocument(operationContext(),
                                                    ShardType::ConfigNS,
                                                    appendTags(kShard1, {"A"}),
                                                    kMajorityWriteConcern));

    // Set up a database and a sharded collection in the metadata.
    ChunkVersion version(2, 0, OID::gen());
    setUpDatabase(kDbName, kShardId0);
    setUpCollection(kNamespace, version);

    // Set up the zone.
    setUpTags(kNamespace, {{"A", {kKeyPattern.globalMin(), BSON(kPattern << -10)}}});

    auto assertErrorWhenMoveChunk = [this, &version](const std::vector<ChunkRange>& chunkRanges) {
        // Give shard0 all the chunks so the cluster is imbalanced.
        for (const auto& chunkRange : chunkRanges) {
            setUpChunk(kNamespace, chunkRange.getMin(), chunkRange.getMax(), kShardId0, version);
            version.incMinor();
        }

        auto future = launchAsync([this] {
            // Requests chunks to be relocated requires running commands on each shard to
            // get shard statistics. Set up dummy hosts for the source shards.
            shardTargeterMock(operationContext(), kShardId0)->setFindHostReturnValue(kShardHost0);
            shardTargeterMock(operationContext(), kShardId1)->setFindHostReturnValue(kShardHost1);

            auto candidateChunksStatus =
                _chunkSelectionPolicy.get()->selectChunksToMove(operationContext());
            ASSERT_OK(candidateChunksStatus.getStatus());

            // The balancer does not bubble up the IllegalOperation error, but it is expected
            // to postpone the balancing work for the zones with the error until the chunks
            // are split appropriately.
            ASSERT_EQUALS(0U, candidateChunksStatus.getValue().size());
        });

        expectGetStatsCommands(2);
        future.default_timed_get();
        removeAllChunks(kNamespace);
    };

    assertErrorWhenMoveChunk({{kKeyPattern.globalMin(), BSON(kPattern << -5)},
                              {BSON(kPattern << -5), kKeyPattern.globalMax()}});
    assertErrorWhenMoveChunk({{kKeyPattern.globalMin(), BSON(kPattern << -15)},
                              {BSON(kPattern << -15), kKeyPattern.globalMax()}});
}

}  // namespace
}  // namespace mongo