summaryrefslogtreecommitdiff
path: root/jstests/concurrency/fsm_workloads/collection_defragmentation.js
blob: 8595d8cdadc7c2b98140edb526766bb251661a0e (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
'use strict';

/**
 * collection_defragmentation.js
 *
 * Runs defragmentation on collections with concurrent operations.
 *
 * @tags: [requires_sharding, assumes_balancer_on, antithesis_incompatible]
 */

const dbPrefix = jsTestName() + '_DB_';
const dbCount = 2;
const collPrefix = 'sharded_coll_';
const collCount = 2;
const maxChunkSizeMB = 10;

load('jstests/sharding/libs/defragmentation_util.js');
load('jstests/sharding/libs/find_chunks_util.js');
load('jstests/concurrency/fsm_workload_helpers/chunks.js');

function getRandomDb(db) {
    return db.getSiblingDB(dbPrefix + Random.randInt(dbCount));
}

function getRandomCollection(db) {
    return db[collPrefix + Random.randInt(collCount)];
}

function getCollectionShardKey(configDB, ns) {
    const collection = configDB.collections.findOne({_id: ns});
    return collection.key;
}

function getExtendedCollectionShardKey(configDB, ns) {
    const currentShardKey = getCollectionShardKey(configDB, ns);
    const newCount = Object.keys(currentShardKey).length;
    currentShardKey["key" + newCount] = 1;
    return currentShardKey;
}

function getAllChunks(configDB, ns, keyPattern) {
    let chunksCursor = findChunksUtil.findChunksByNs(configDB, ns).sort(keyPattern);
    let chunkArray = [];
    while (!chunksCursor.isExhausted()) {
        while (chunksCursor.objsLeftInBatch()) {
            chunkArray.push(chunksCursor.next());
        }
        chunksCursor =
            findChunksUtil.findChunksByNs(configDB, ns).sort(keyPattern).skip(chunkArray.length);
    }
    return chunkArray;
}

var $config = (function() {
    var states = {
        init: function init(db, collName, connCache) {
            // Initialize defragmentation
            for (let i = 0; i < dbCount; i++) {
                const dbName = dbPrefix + i;
                for (let j = 0; j < collCount; j++) {
                    const fullNs = dbName + "." + collPrefix + j;
                    assertWhenOwnColl.commandWorked(connCache.mongos[0].adminCommand({
                        configureCollectionBalancing: fullNs,
                        defragmentCollection: true,
                        chunkSize: maxChunkSizeMB,
                    }));
                }
            }
        },

        moveChunk: function moveChunk(db, collName, connCache) {
            const randomDB = getRandomDb(db);
            const randomColl = getRandomCollection(randomDB);
            const configDB = randomDB.getSiblingDB('config');
            const chunksJoinClause =
                findChunksUtil.getChunksJoinClause(configDB, randomColl.getFullName());
            const randomChunk =
                configDB.chunks.aggregate([{$match: chunksJoinClause}, {$sample: {size: 1}}])
                    .next();
            const fromShard = randomChunk.shard;
            const bounds = [randomChunk.min, randomChunk.max];
            const zoneForChunk = defragmentationUtil.getZoneForRange(
                connCache.mongos[0], randomColl.getFullName(), randomChunk.min, randomChunk.max);

            // Pick a shard at random to move it to. If the chunk is in a zone, look for a shard
            // with that zone.
            let shardFilter = {_id: {$ne: fromShard}};
            if (zoneForChunk !== null) {
                shardFilter['tag'] = zoneForChunk;
            }
            const shardCursor =
                configDB.shards.aggregate([{$match: shardFilter}, {$sample: {size: 1}}]);
            if (!shardCursor.hasNext()) {
                return;
            }
            const toShard = shardCursor.next();

            // Issue a moveChunk command.
            try {
                ChunkHelper.moveChunk(randomDB, randomColl.getName(), bounds, toShard['_id'], true);
                jsTest.log("Manual move chunk of chunk " + tojson(randomChunk) + " to shard " +
                           toShard['_id']);
            } catch (e) {
                jsTest.log("Ignoring manual move chunk error: " + tojson(e));
            }
        },

        mergeChunks: function mergeChunks(db, collName, connCache) {
            const randomDB = getRandomDb(db);
            const randomColl = getRandomCollection(randomDB);
            const configDB = randomDB.getSiblingDB('config');
            const keyPattern = getCollectionShardKey(configDB, randomColl.getFullName());

            // Get all the chunks without using getMore so the test can run with stepdowns.
            const chunks = getAllChunks(configDB, randomColl.getFullName(), keyPattern);

            // No possible merges if there are less than 2 chunks.
            if (chunks.length < 2) {
                return;
            }

            // Choose a random starting point to look for mergeable chunks to make it less likely
            // that each thread tries to move the same chunk.
            let index = Random.randInt(chunks.length);
            for (let i = 0; i < chunks.length; i++) {
                if (index === chunks.length - 1) {
                    index = 0;
                }
                if (chunks[index].shard === chunks[index + 1].shard &&
                    defragmentationUtil.getZoneForRange(connCache.mongos[0],
                                                        randomColl.getFullName(),
                                                        chunks[index].min,
                                                        chunks[index].max) ===
                        defragmentationUtil.getZoneForRange(connCache.mongos[0],
                                                            randomColl.getFullName(),
                                                            chunks[index + 1].min,
                                                            chunks[index + 1].max)) {
                    const bounds = [chunks[index].min, chunks[index + 1].max];
                    try {
                        ChunkHelper.mergeChunks(randomDB, randomColl.getName(), bounds);
                        jsTest.log("Manual merge chunks of chunks " + tojson(chunks[index]) +
                                   " and " + tojson(chunks[index + 1]));
                    } catch (e) {
                        jsTest.log("Ignoring manual merge chunks error: " + tojson(e));
                    }
                    return;
                }
            }
        },

        splitChunks: function splitChunks(db, collName, connCache) {
            const randomDB = getRandomDb(db);
            const randomColl = getRandomCollection(randomDB);
            const configDB = randomDB.getSiblingDB('config');
            const chunksJoinClause =
                findChunksUtil.getChunksJoinClause(configDB, randomColl.getFullName());
            const randomChunk =
                configDB.chunks.aggregate([{$match: chunksJoinClause}, {$sample: {size: 1}}])
                    .toArray()[0];
            try {
                assertAlways.commandWorked(
                    db.adminCommand({split: randomColl.getFullName(), find: randomChunk.min}));
                jsTest.log("Manual split chunk of chunk " + tojson(randomChunk));
            } catch (e) {
                jsTest.log("Ignoring manual split chunk error: " + tojson(e));
            }
        },

        refineShardKey: function refineShardKey(db, collName, connCache) {
            const randomDB = getRandomDb(db);
            const randomColl = getRandomCollection(randomDB);
            const configDB = randomDB.getSiblingDB('config');
            const extendedShardKey =
                getExtendedCollectionShardKey(configDB, randomColl.getFullName());
            try {
                assertWhenOwnColl.commandWorked(randomColl.createIndex(extendedShardKey));
                assertWhenOwnColl.commandWorked(randomDB.adminCommand(
                    {refineCollectionShardKey: randomColl.getFullName(), key: extendedShardKey}));
                jsTest.log("Manual refine shard key for collection " + randomColl.getFullName() +
                           " to " + tojson(extendedShardKey));
            } catch (e) {
                jsTest.log("Ignoring manual refine shard key error: " + tojson(e));
            }
        }
    };

    var transitions = {
        init: {moveChunk: 0.25, mergeChunks: 0.25, splitChunks: 0.25, refineShardKey: 0.25},
        moveChunk: {mergeChunks: 0.33, splitChunks: 0.33, refineShardKey: 0.33},
        mergeChunks: {moveChunk: 0.33, splitChunks: 0.33, refineShardKey: 0.33},
        splitChunks: {moveChunk: 0.33, mergeChunks: 0.33, refineShardKey: 0.33},
        refineShardKey: {moveChunk: 0.33, mergeChunks: 0.33, splitChunks: 0.33},
    };

    let defaultChunkDefragmentationThrottlingMS;

    function setup(db, collName, cluster) {
        const mongos = cluster.getDB('config').getMongo();
        // Create all fragmented collections
        for (let i = 0; i < dbCount; i++) {
            const dbName = dbPrefix + i;
            const newDb = db.getSiblingDB(dbName);
            assertAlways.commandWorked(newDb.adminCommand({enablesharding: dbName}));
            for (let j = 0; j < collCount; j++) {
                const fullNs = dbName + "." + collPrefix + j;
                const numChunks = Random.randInt(30);
                const numZones = Random.randInt(numChunks / 2);
                const docSizeBytes = Random.randInt(1024 * 1024) + 50;
                defragmentationUtil.createFragmentedCollection(
                    mongos,
                    fullNs,
                    numChunks,
                    5 /* maxChunkFillMB */,
                    numZones,
                    docSizeBytes,
                    1000 /* chunkSpacing */,
                    true /* disableCollectionBalancing*/);
            }
        }
        // Remove throttling to speed up test execution
        cluster.executeOnConfigNodes((db) => {
            const res = db.adminCommand({setParameter: 1, chunkDefragmentationThrottlingMS: 0});
            assert.commandWorked(res);
            defaultChunkDefragmentationThrottlingMS = res.was;
        });
    }

    function teardown(db, collName, cluster) {
        const mongos = cluster.getDB('config').getMongo();

        cluster.executeOnConfigNodes((db) => {
            assert.commandWorked(db.adminCommand({
                configureFailPoint: 'overrideBalanceRoundInterval',
                mode: 'alwaysOn',
                data: {intervalMs: 100}
            }));
        });

        for (let i = 0; i < dbCount; i++) {
            const dbName = dbPrefix + i;
            for (let j = 0; j < collCount; j++) {
                const fullNs = dbName + "." + collPrefix + j;
                // Wait for defragmentation to complete
                defragmentationUtil.waitForEndOfDefragmentation(mongos, fullNs);
                // Enable balancing and wait for balanced
                assertAlways.commandWorked(mongos.getDB('config').collections.update(
                    {_id: fullNs}, {$set: {"noBalance": false}}));
                sh.awaitCollectionBalance(mongos.getCollection(fullNs));
                // Begin defragmentation again
                assertAlways.commandWorked(mongos.adminCommand({
                    configureCollectionBalancing: fullNs,
                    defragmentCollection: true,
                    chunkSize: maxChunkSizeMB,
                }));
                // Wait for defragmentation to complete and check final state
                defragmentationUtil.waitForEndOfDefragmentation(mongos, fullNs);
                defragmentationUtil.checkPostDefragmentationState(
                    cluster.getConfigPrimaryNode(), mongos, fullNs, maxChunkSizeMB, "key");
                // Resume original throttling value
                cluster.executeOnConfigNodes((db) => {
                    assert.commandWorked(db.adminCommand({
                        setParameter: 1,
                        chunkDefragmentationThrottlingMS: defaultChunkDefragmentationThrottlingMS
                    }));
                });
            }
        }
    }

    return {
        threadCount: 5,
        iterations: 10,
        states: states,
        transitions: transitions,
        setup: setup,
        teardown: teardown,
        passConnectionCache: true
    };
})();