summaryrefslogtreecommitdiff
path: root/jstests/sharding/timeseries_multiple_mongos.js
blob: de23cb94fa5b1c3da513611e923aba87667a9898 (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
/**
 * Test various commands on time-series collection in the presence of multiple mongos and collection
 * changing from unsharded to sharded and vice versa.
 *
 * @tags: [
 *   requires_fcv_51,
 * ]
 */

(function() {
"use strict";

load("jstests/core/timeseries/libs/timeseries.js");  // For 'TimeseriesTest' helpers.
load('jstests/sharding/libs/shard_versioning_util.js');

Random.setRandomSeed();

const dbName = 'testDB';
const collName = 'testColl';
const bucketsCollName = 'system.buckets.' + collName;
const timeField = 'time';
const metaField = 'hostid';

// Connections.
const st = new ShardingTest({mongos: 2, shards: 2, rs: {nodes: 2}});
const mongos0 = st.s0.getDB(dbName);
const mongos1 = st.s1.getDB(dbName);
const shard0DB = st.shard0.getDB(dbName);
const shard1DB = st.shard1.getDB(dbName);

if (!TimeseriesTest.shardedtimeseriesCollectionsEnabled(st.shard0)) {
    jsTestLog("Skipping test because the sharded time-series collection feature flag is disabled");
    st.stop();
    return;
}

// Databases and collections.
assert.commandWorked(mongos0.adminCommand({enableSharding: dbName}));

// Helpers.
let currentId = 0;
function generateId() {
    return currentId++;
}

function generateBatch(size) {
    return TimeseriesTest.generateHosts(size).map((host, index) => Object.assign(host, {
        _id: generateId(),
        [metaField]: index,
        [timeField]: ISODate(`20${index}0-01-01`),
    }));
}

/**
 * The test runs drop, create and shardCollection commands using mongos0, then validates the given
 * command by running against mongos1 with stale config.
 */
function runTest({shardKey, cmdObj, numProfilerEntries}) {
    const isDelete = cmdObj["delete"] !== undefined;
    const isUpdate = cmdObj["update"] !== undefined;
    const isCollMod = cmdObj["collMod"] !== undefined;
    const isDropIndex = cmdObj["dropIndexes"] !== undefined;
    const cmdCollName = cmdObj[Object.keys(cmdObj)[0]];
    const shardKeyHasMetaField = shardKey[metaField] !== undefined;

    // Insert some dummy data using 'mongos1' as the router, so that the cache is initialized on the
    // mongos while the collection is unsharded.
    assert.commandWorked(mongos1.getCollection(collName).insert({[timeField]: ISODate()}));

    // Drop and shard the collection with 'mongos0' as the router.
    assert(mongos0.getCollection(collName).drop());
    assert.commandWorked(mongos0.createCollection(
        collName, {timeseries: {timeField: timeField, metaField: metaField}}));
    assert.commandWorked(st.s0.adminCommand({
        shardCollection: `${dbName}.${collName}`,
        key: shardKey,
    }));

    // Move one of the chunks into the second shard. Note that we can only do this if the meta field
    // is part of the shard key.
    const middle = shardKeyHasMetaField ? {meta: 1} : {"meta.a": 1};
    assert.commandWorked(mongos0.adminCommand({split: `${dbName}.${bucketsCollName}`, middle}));

    const primaryShard = st.getPrimaryShard(dbName);
    const otherShard = st.getOther(primaryShard);
    assert.commandWorked(mongos0.adminCommand({
        movechunk: `${dbName}.${bucketsCollName}`,
        find: middle,
        to: otherShard.name,
        _waitForDelete: true
    }));

    // Validate the command by running against 'mongos1' as the router.
    function validateCommand(cmdCollName, numEntries, unVersioned) {
        // Restart profiler.
        for (let shardDB of [shard0DB, shard1DB]) {
            shardDB.setProfilingLevel(0);
            shardDB.system.profile.drop();
            shardDB.setProfilingLevel(2);
        }

        const res = mongos1.runCommand(cmdObj);
        if (numEntries > 0) {
            assert.commandWorked(res);
        } else {
            assert.commandFailed(res);
        }

        const queryField = `command.${Object.keys(cmdObj)[0]}`;
        let filter = {
            [queryField]: cmdCollName,
            "$or": [
                {
                    "$and": [
                        {"command.shardVersion.0": {"$exists": true}},
                        {
                            "command.shardVersion.0":
                                {$ne: ShardVersioningUtil.kIgnoredShardVersion.v}
                        },
                    ]
                },
                {
                    "$and": [
                        {"command.shardVersion.v": {"$exists": true}},
                        {
                            "command.shardVersion.v":
                                {$ne: ShardVersioningUtil.kIgnoredShardVersion.v}
                        },
                    ]
                },
            ]
        };

        // We currently do not log 'shardVersion' for updates. See SERVER-60354 for details.
        if (isUpdate) {
            filter = {"op": "update", "ns": `${dbName}.${cmdCollName}`, "ok": {$ne: 0}};
        } else if (isDelete) {
            filter = {"op": "remove", "ns": `${dbName}.${cmdCollName}`, "ok": {$ne: 0}};
        } else if (isCollMod) {
            const command = unVersioned ? "_shardsvrCollMod" : "_shardsvrCollModParticipant";
            filter = {[`command.${command}`]: cmdCollName, "ok": {$ne: 0}};
        } else if (unVersioned && !isCollMod) {
            filter = {
                [queryField]: cmdCollName,
                "$or": [
                    {"command.shardVersion.0": ShardVersioningUtil.kIgnoredShardVersion.v},
                    {"command.shardVersion.v": ShardVersioningUtil.kIgnoredShardVersion.v},
                ]
            };
        }

        // Filter out the profiler entries with $indexStats pipeline stage, as the
        // PeriodicShardedIndexConsistencyChecker can issue an aggregate command with
        // '[$indexStats: {}]' pipeline periodically. We don't want these entries to be accounted
        // here.
        filter["command.pipeline.0.$indexStats"] = {$exists: false};

        const shard0Entries = shard0DB.system.profile.find(filter).toArray();
        const shard1Entries = shard1DB.system.profile.find(filter).toArray();
        assert.eq(shard0Entries.length + shard1Entries.length,
                  numEntries,
                  {shard0Entries: shard0Entries, shard1Entries: shard1Entries});
    }

    // The update command is always logged as being on the user-provided namespace.
    validateCommand((isUpdate || isDelete || isCollMod) ? cmdCollName : bucketsCollName,
                    numProfilerEntries.sharded);

    // Insert dummy data so that the 'mongos1' sees the collection as sharded.
    assert.commandWorked(mongos1.getCollection(collName).insert({[timeField]: ISODate()}));

    // Drop and recreate an unsharded collection with 'mongos0' as the router.
    assert(mongos0.getCollection(collName).drop());
    assert.commandWorked(mongos0.createCollection(
        collName, {timeseries: {timeField: timeField, metaField: metaField}}));

    // When unsharded, the command should be run against the user requested namespace, except for
    // dropIndex.
    validateCommand(
        isDropIndex ? bucketsCollName : cmdCollName, numProfilerEntries.unsharded, true);
}

/**
 * Commands on the view namespace.
 */
runTest({
    shardKey: {[metaField]: 1},
    cmdObj: {
        createIndexes: collName,
        indexes: [{key: {[timeField]: 1}, name: "index_on_time"}],
    },
    numProfilerEntries: {sharded: 2, unsharded: 1}
});

runTest({
    shardKey: {[metaField]: 1},
    cmdObj: {listIndexes: collName},
    numProfilerEntries: {sharded: 1, unsharded: 1}
});

runTest({
    shardKey: {[metaField]: 1},
    cmdObj: {
        dropIndexes: collName,
        index: "*",
    },
    numProfilerEntries: {sharded: 2, unsharded: 1}
});

runTest({
    shardKey: {[metaField]: 1},
    cmdObj: {collMod: collName, expireAfterSeconds: 3600},
    numProfilerEntries: {sharded: 2, unsharded: 1}
});

runTest({
    shardKey: {[metaField]: 1},
    cmdObj: {insert: collName, documents: [{[timeField]: ISODate()}]},
    numProfilerEntries: {sharded: 1, unsharded: 1}
});

runTest({
    shardKey: {[metaField]: 1},
    cmdObj: {insert: collName, documents: [{[timeField]: ISODate()}]},
    numProfilerEntries: {sharded: 1, unsharded: 1}
});

runTest({
    shardKey: {[metaField]: 1},
    cmdObj: {aggregate: collName, pipeline: [], cursor: {}},
    numProfilerEntries: {sharded: 2, unsharded: 1}
});

runTest({
    shardKey: {[metaField]: 1},
    cmdObj: {collStats: collName},
    numProfilerEntries: {sharded: 2, unsharded: 1}
});

/**
 * On system.buckets namespace
 */
runTest({
    shardKey: {[metaField]: 1},
    cmdObj: {
        createIndexes: bucketsCollName,
        indexes: [{key: {[timeField]: 1}, name: "index_on_time"}],
    },
    numProfilerEntries: {sharded: 2, unsharded: 1},
});

runTest({
    shardKey: {[metaField]: 1},
    cmdObj: {listIndexes: bucketsCollName},
    numProfilerEntries: {sharded: 1, unsharded: 1},
});

runTest({
    shardKey: {[metaField]: 1},
    cmdObj: {
        dropIndexes: bucketsCollName,
        index: "*",
    },
    numProfilerEntries: {sharded: 2, unsharded: 1},
});

runTest({
    shardKey: {[metaField]: 1},
    cmdObj: {collMod: bucketsCollName, expireAfterSeconds: 3600},
    numProfilerEntries: {sharded: 2, unsharded: 1},
});

runTest({
    shardKey: {[metaField]: 1},
    cmdObj: {aggregate: bucketsCollName, pipeline: [], cursor: {}},
    numProfilerEntries: {sharded: 2, unsharded: 1},
});

runTest({
    shardKey: {[metaField]: 1},
    cmdObj: {
        insert: bucketsCollName,
        documents: [{
            _id: ObjectId(),
            control: {min: {time: ISODate()}, max: {time: ISODate()}, version: 1},
            data: {}
        }]
    },
    numProfilerEntries: {sharded: 1, unsharded: 1},
});

if (TimeseriesTest.shardedTimeseriesUpdatesAndDeletesEnabled(st.shard0)) {
    // Tests for updates.
    runTest({
        shardKey: {[metaField + ".a"]: 1},
        cmdObj: {
            update: collName,
            updates: [{
                q: {},
                u: {$inc: {[metaField + ".b"]: 1}},
                multi: true,
            }]
        },
        numProfilerEntries: {sharded: 2, unsharded: 1},
    });

    runTest({
        shardKey: {[metaField + ".a"]: 1},
        cmdObj: {
            update: collName,
            updates: [{
                q: {[metaField + ".a"]: 1},
                u: {$inc: {[metaField + ".b"]: -1}},
                multi: true,
            }]
        },
        numProfilerEntries: {sharded: 1, unsharded: 1},
    });

    runTest({
        shardKey: {[metaField + ".a"]: 1},
        cmdObj: {
            update: bucketsCollName,
            updates: [{
                q: {},
                u: {$inc: {["meta.b"]: 1}},
                multi: true,
            }]
        },
        numProfilerEntries: {sharded: 2, unsharded: 1},
    });

    runTest({
        shardKey: {[metaField + ".a"]: 1},
        cmdObj: {
            update: bucketsCollName,
            updates: [{
                q: {["meta.a"]: 1},
                u: {$inc: {["meta.b"]: -1}},
                multi: true,
            }]
        },
        numProfilerEntries: {sharded: 1, unsharded: 1},
    });

    // Tests for deletes.
    runTest({
        shardKey: {[metaField]: 1},
        cmdObj: {
            delete: collName,
            deletes: [{
                q: {},
                limit: 0,
            }],
        },
        numProfilerEntries: {sharded: 2, unsharded: 1},
    });

    runTest({
        shardKey: {[metaField]: 1},
        cmdObj: {
            delete: collName,
            deletes: [{
                q: {[metaField]: 0},
                limit: 0,
            }],
        },
        numProfilerEntries: {sharded: 1, unsharded: 1},
    });

    runTest({
        shardKey: {[metaField]: 1},
        cmdObj: {
            delete: bucketsCollName,
            deletes: [{
                q: {},
                limit: 0,
            }],
        },
        numProfilerEntries: {sharded: 2, unsharded: 1},
    });

    runTest({
        shardKey: {[metaField]: 1},
        cmdObj: {
            delete: bucketsCollName,
            deletes: [{
                q: {meta: 0},
                limit: 0,
            }],
        },
        numProfilerEntries: {sharded: 1, unsharded: 1},
    });
}

st.stop();
})();