summaryrefslogtreecommitdiff
path: root/jstests/sharding/libs/defragmentation_util.js
blob: 8fcc8a35d998c7580ef5bf0d3035f9f310a5cf7d (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
var defragmentationUtil = (function() {
    load("jstests/libs/feature_flag_util.js");
    load("jstests/sharding/libs/find_chunks_util.js");

    let createFragmentedCollection = function(mongos,
                                              ns,
                                              numChunks,
                                              maxChunkFillMB,
                                              numZones,
                                              docSizeBytes,
                                              chunkSpacing,
                                              disableCollectionBalancing) {
        jsTest.log("Creating fragmented collection " + ns + " with parameters: numChunks = " +
                   numChunks + ", numZones = " + numZones + ", docSizeBytes = " + docSizeBytes +
                   ", maxChunkFillMB = " + maxChunkFillMB + ", chunkSpacing = " + chunkSpacing);
        assert.commandWorked(mongos.adminCommand({shardCollection: ns, key: {key: 1}}));
        // Turn off balancer for this collection
        if (disableCollectionBalancing) {
            assert.commandWorked(
                mongos.getDB('config').collections.update({_id: ns}, {$set: {"noBalance": true}}));
        }

        createAndDistributeChunks(mongos, ns, numChunks, chunkSpacing);
        createRandomZones(mongos, ns, numZones, chunkSpacing);
        fillChunksToRandomSize(mongos, ns, docSizeBytes, maxChunkFillMB);

        const beginningNumberChunks = findChunksUtil.countChunksForNs(mongos.getDB('config'), ns);
        const beginningNumberZones = mongos.getDB('config').tags.countDocuments({ns: ns});
        jsTest.log("Collection " + ns + " created with " + beginningNumberChunks + " chunks and " +
                   beginningNumberZones + " zones.");
    };

    let createAndDistributeChunks = function(mongos, ns, numChunks, chunkSpacing) {
        const shards = mongos.getCollection('config.shards').find().toArray();
        const existingNumChunks = findChunksUtil.countChunksForNs(mongos.getDB('config'), ns);
        let numChunksToCreate = numChunks - existingNumChunks;
        if (numChunksToCreate <= 0) {
            return;
        }
        for (let i = -Math.floor(numChunksToCreate / 2); i < Math.ceil(numChunksToCreate / 2);
             i++) {
            assert.commandWorked(mongos.adminCommand({split: ns, middle: {key: i * chunkSpacing}}));
            assert.soon(() => {
                let toShard = Random.randInt(shards.length);
                let res = mongos.adminCommand(
                    {moveChunk: ns, find: {key: i * chunkSpacing}, to: shards[toShard]._id});
                return res.ok;
            });
        }
    };

    let createRandomZones = function(mongos, ns, numZones, chunkSpacing) {
        for (let i = -Math.floor(numZones / 2); i < Math.ceil(numZones / 2); i++) {
            let zoneName = "Zone" + i;
            let shardForZone =
                findChunksUtil
                    .findOneChunkByNs(mongos.getDB('config'), ns, {min: {key: i * chunkSpacing}})
                    .shard;
            assert.commandWorked(
                mongos.adminCommand({addShardToZone: shardForZone, zone: zoneName}));
            assert.commandWorked(mongos.adminCommand({
                updateZoneKeyRange: ns,
                min: {key: i * chunkSpacing},
                max: {key: i * chunkSpacing + chunkSpacing},
                zone: zoneName
            }));
        }
    };

    let fillChunksToRandomSize = function(mongos, ns, docSizeBytes, maxChunkFillMB) {
        const chunks = findChunksUtil.findChunksByNs(mongos.getDB('config'), ns).toArray();
        const bigString = "X".repeat(docSizeBytes);
        const coll = mongos.getCollection(ns);
        let bulk = coll.initializeUnorderedBulkOp();
        chunks.forEach((chunk) => {
            let chunkSize = Random.randInt(maxChunkFillMB);
            let docsPerChunk = (chunkSize * 1024 * 1024) / docSizeBytes;
            if (docsPerChunk === 0) {
                return;
            }
            let minKey = chunk["min"]["key"];
            if (minKey === MinKey)
                minKey = Number.MIN_SAFE_INTEGER;
            let maxKey = chunk["max"]["key"];
            if (maxKey === MaxKey)
                maxKey = Number.MAX_SAFE_INTEGER;
            let currKey = minKey;
            const gap = ((maxKey - minKey) / docsPerChunk);
            for (let i = 0; i < docsPerChunk; i++) {
                bulk.insert({key: currKey, longString: bigString});
                currKey += gap;
            }
        });
        assert.commandWorked(bulk.execute());
    };

    let checkForOversizedChunk = function(
        coll, chunk, shardKey, avgObjSize, oversizedChunkThreshold) {
        let chunkSize = coll.countDocuments(
                            {[shardKey]: {$gte: chunk.min[shardKey], $lt: chunk.max[shardKey]}}) *
            avgObjSize;
        assert.lte(
            chunkSize,
            oversizedChunkThreshold,
            `Chunk ${tojson(chunk)} has size ${chunkSize} which is greater than max chunk size of ${
                oversizedChunkThreshold}`);
    };

    let checkForMergeableChunkSiblings = function(
        coll, leftChunk, rightChunk, shardKey, avgObjSize, oversizedChunkThreshold) {
        let combinedDataSize =
            coll.countDocuments(
                {[shardKey]: {$gte: leftChunk.min[shardKey], $lt: rightChunk.max[shardKey]}}) *
            avgObjSize;
        // The autosplitter should not split chunks whose combined size is < 133% of
        // maxChunkSize but this threshold may be off by a few documents depending on
        // rounding of avgObjSize.
        const autosplitRoundingTolerance = 3 * avgObjSize;
        assert.gte(combinedDataSize,
                   oversizedChunkThreshold - autosplitRoundingTolerance,
                   `Chunks ${tojson(leftChunk)} and ${
                       tojson(rightChunk)} are mergeable with combined size ${combinedDataSize}`);
    };

    let checkPostDefragmentationState = function(mongos, ns, maxChunkSizeMB, shardKey) {
        const withAutoSplitActive =
            !FeatureFlagUtil.isEnabled(mongos.getDB('admin'), 'NoMoreAutoSplitter');
        const oversizedChunkThreshold = maxChunkSizeMB * 1024 * 1024 * 4 / 3;
        const chunks = findChunksUtil.findChunksByNs(mongos.getDB('config'), ns)
                           .sort({[shardKey]: 1})
                           .toArray();
        const coll = mongos.getCollection(ns);
        const pipeline = [
            {'$collStats': {'storageStats': {}}},
            {'$project': {'shard': true, 'storageStats': {'avgObjSize': true}}}
        ];
        const storageStats = coll.aggregate(pipeline).toArray();
        let avgObjSizeByShard = {};
        storageStats.forEach((storageStat) => {
            avgObjSizeByShard[storageStat['shard']] =
                typeof (storageStat['storageStats']['avgObjSize']) === "undefined"
                ? 0
                : storageStat['storageStats']['avgObjSize'];
        });
        for (let i = 1; i < chunks.length; i++) {
            let leftChunk = chunks[i - 1];
            let rightChunk = chunks[i];
            // Check for mergeable chunks with combined size less than maxChunkSize
            if (leftChunk["shard"] === rightChunk["shard"] &&
                bsonWoCompare(leftChunk["max"], rightChunk["min"]) === 0) {
                let leftChunkZone = getZoneForRange(mongos, ns, leftChunk.min, leftChunk.max);
                let rightChunkZone = getZoneForRange(mongos, ns, rightChunk.min, rightChunk.max);
                if (bsonWoCompare(leftChunkZone, rightChunkZone) === 0) {
                    if (withAutoSplitActive) {
                        checkForMergeableChunkSiblings(coll,
                                                       leftChunk,
                                                       rightChunk,
                                                       shardKey,
                                                       avgObjSizeByShard[leftChunk['shard']],
                                                       oversizedChunkThreshold);
                    } else {
                        assert(false,
                               `Chunks ${leftChunk} and ${rightChunk} should have been merged`);
                    }
                }
            }
            if (withAutoSplitActive) {
                checkForOversizedChunk(coll,
                                       leftChunk,
                                       shardKey,
                                       avgObjSizeByShard[leftChunk['shard']],
                                       oversizedChunkThreshold);
            }
        }

        if (withAutoSplitActive) {
            const lastChunk = chunks[chunks.length - 1];
            checkForOversizedChunk(coll,
                                   lastChunk,
                                   shardKey,
                                   avgObjSizeByShard[lastChunk['shard']],
                                   oversizedChunkThreshold);
        }
    };

    let getZoneForRange = function(mongos, ns, minKey, maxKey) {
        const tags = mongos.getDB('config')
                         .tags.find({ns: ns, min: {$lte: minKey}, max: {$gte: maxKey}})
                         .toArray();
        assert.lte(tags.length, 1);
        if (tags.length === 1) {
            return tags[0].tag;
        }
        return null;
    };

    let waitForEndOfDefragmentation = function(mongos, ns) {
        jsTest.log("Waiting end of defragmentation for " + ns);
        assert.soon(function() {
            let balancerStatus =
                assert.commandWorked(mongos.adminCommand({balancerCollectionStatus: ns}));
            return balancerStatus.balancerCompliant ||
                balancerStatus.firstComplianceViolation !== 'defragmentingChunks';
        });
        jsTest.log("Defragmentation completed for " + ns);
    };

    return {
        createFragmentedCollection,
        checkPostDefragmentationState,
        getZoneForRange,
        waitForEndOfDefragmentation,
    };
})();