-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
Copy pathquery_settings_utils.js
389 lines (339 loc) · 15 KB
/
query_settings_utils.js
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
/**
* Utility class for testing query settings.
*/
import {getCommandName, getExplainCommand} from "jstests/libs/cmd_object_utils.js";
import {
getAggPlanStages,
getEngine,
getPlanStages,
getQueryPlanners,
getWinningPlanFromExplain
} from "jstests/libs/query/analyze_plan.js";
export class QuerySettingsUtils {
/**
* Create a query settings utility class.
*/
constructor(db, collName) {
this._db = db;
this._adminDB = this._db.getSiblingDB("admin");
this._collName = collName;
}
/**
* Returns 'true' if the given command name is supported by query settings.
*/
static isSupportedCommand(commandName) {
return ["find", "aggregate", "distinct"].includes(commandName);
}
/**
* Makes an query instance for the given command if supported.
*/
makeQueryInstance(cmdObj) {
const commandName = getCommandName(cmdObj);
switch (commandName) {
case "find":
return this.makeFindQueryInstance(cmdObj);
case "aggregate":
return this.makeAggregateQueryInstance(cmdObj);
case "distinct":
return this.makeDistinctQueryInstance(cmdObj);
default:
assert(false, "Cannot create query instance for command with name " + commandName);
}
}
/**
* Makes an query instance of the find command.
*/
makeFindQueryInstance(findObj) {
return {find: this._collName, $db: this._db.getName(), ...findObj};
}
/**
* Makes a query instance of the distinct command.
*/
makeDistinctQueryInstance(distinctObj) {
return {distinct: this._collName, $db: this._db.getName(), ...distinctObj};
}
/**
* Makes a query instance of the aggregate command with an optional pipeline clause.
*/
makeAggregateQueryInstance(aggregateObj, collectionless = false) {
return {
aggregate: collectionless ? 1 : this._collName,
$db: this._db.getName(),
cursor: {},
...aggregateObj
};
}
/**
* Makes a QueryShapeConfiguration object without the QueryShapeHash.
*/
makeQueryShapeConfiguration(settings, representativeQuery) {
return {settings, representativeQuery};
}
makeSetQuerySettingsCommand({settings, representativeQuery}) {
return {setQuerySettings: representativeQuery, settings};
}
makeRemoveQuerySettingsCommand(representativeQuery) {
return {removeQuerySettings: representativeQuery};
}
/**
* Return query settings for the current tenant without query shape hashes.
*/
getQuerySettings({showDebugQueryShape = false,
showQueryShapeHash = false,
filter = undefined} = {}) {
const pipeline = [{$querySettings: showDebugQueryShape ? {showDebugQueryShape} : {}}];
if (filter) {
pipeline.push({$match: filter});
}
if (!showQueryShapeHash) {
pipeline.push({$project: {queryShapeHash: 0}});
}
pipeline.push({$sort: {representativeQuery: 1}});
return this._adminDB.aggregate(pipeline).toArray();
}
/**
* Return 'queryShapeHash' for a given query from 'querySettings'.
*/
getQueryShapeHashFromQuerySettings(representativeQuery) {
const settings =
this.getQuerySettings({showQueryShapeHash: true, filter: {representativeQuery}});
assert.lte(
settings.length,
1,
`query ${tojson(representativeQuery)} is expected to have 0 or 1 settings, but got ${
tojson(settings)}`);
return settings.length === 0 ? undefined : settings[0].queryShapeHash;
}
/**
* Return the query settings section of the server status.
*/
getQuerySettingsServerStatus() {
return assert.commandWorked(this._db.runCommand({serverStatus: 1})).querySettings;
}
/**
* Helper function to assert equality of QueryShapeConfigurations. In order to ease the
* assertion logic, 'queryShapeHash' field is removed from the QueryShapeConfiguration prior
* to assertion.
*
* Since in sharded clusters the query settings may arrive with a delay to the mongos, the
* assertion is done via 'assert.soon'.
*
* The settings list is not expected to be in any particular order.
*/
assertQueryShapeConfiguration(expectedQueryShapeConfigurations, shouldRunExplain = true) {
const rewrittenExpectedQueryShapeConfigurations =
expectedQueryShapeConfigurations.map(config => {
return {...config, settings: this.wrapIndexHintsIntoArrayIfNeeded(config.settings)};
});
assert.soon(
() => {
let currentQueryShapeConfigurationWo = this.getQuerySettings();
currentQueryShapeConfigurationWo.sort(bsonWoCompare);
rewrittenExpectedQueryShapeConfigurations.sort(bsonWoCompare);
return bsonWoCompare(currentQueryShapeConfigurationWo,
rewrittenExpectedQueryShapeConfigurations) == 0;
},
"current query settings = " + tojson(this.getQuerySettings()) +
", expected query settings = " + tojson(rewrittenExpectedQueryShapeConfigurations));
if (shouldRunExplain) {
const settingsArray = this.getQuerySettings({showQueryShapeHash: true});
for (const {representativeQuery, settings, queryShapeHash} of settingsArray) {
this.assertExplainQuerySettings(representativeQuery, settings, queryShapeHash);
}
}
}
/**
* Asserts that the explain output for 'query' contains 'expectedQuerySettings' and
* 'expectedQueryShapeHash'.
*/
assertExplainQuerySettings(query, expectedQuerySettings, expectedQueryShapeHash = undefined) {
// Pass query without the $db field to explain command, because it injects the $db field
// inside the query before processing.
const explainCmd = getExplainCommand(this.withoutDollarDB(query));
const explain = assert.commandWorked(this._db.runCommand(explainCmd));
if (explain) {
getQueryPlanners(explain).forEach(queryPlanner => {
this.assertEqualSettings(
expectedQuerySettings, queryPlanner.querySettings, queryPlanner);
});
if (expectedQueryShapeHash) {
const {queryShapeHash} = explain;
assert.eq(queryShapeHash, expectedQueryShapeHash);
}
}
}
/**
* Remove all query settings for the current tenant.
*/
removeAllQuerySettings() {
let settingsArray = this.getQuerySettings({showQueryShapeHash: true});
while (settingsArray.length > 0) {
const setting = settingsArray.pop();
assert.commandWorked(
this._adminDB.runCommand({removeQuerySettings: setting.queryShapeHash}));
}
// Check that all setting have indeed been removed.
this.assertQueryShapeConfiguration([]);
}
/**
* Helper method for setting & removing query settings for testing purposes. Accepts a
* 'runTest' anonymous function which will be executed once the provided query settings have
* been propagated throughout the cluster.
*/
withQuerySettings(representativeQuery, settings, runTest) {
let queryShapeHash = undefined;
try {
const setQuerySettingsCmd = {setQuerySettings: representativeQuery, settings: settings};
queryShapeHash =
assert.commandWorked(this._db.adminCommand(setQuerySettingsCmd)).queryShapeHash;
assert.soon(() => (this.getQuerySettings({filter: {queryShapeHash}}).length === 1));
return runTest();
} finally {
if (queryShapeHash) {
const removeQuerySettingsCmd = {removeQuerySettings: representativeQuery};
assert.commandWorked(this._db.adminCommand(removeQuerySettingsCmd));
assert.soon(() => (this.getQuerySettings({filter: {queryShapeHash}}).length === 0));
}
}
}
withoutDollarDB(cmd) {
const {$db: _, ...rest} = cmd;
return rest;
}
/**
* 'indexHints' as part of query settings may be passed as object or as array. On the server the
* indexHints will always be transformed into an array. For correct comparison, wrap
* 'indexHints' into array if they are not array already.
*/
wrapIndexHintsIntoArrayIfNeeded(settings) {
if (!settings) {
return settings;
}
let result = Object.assign({}, settings);
if (result.indexHints && !Array.isArray(result.indexHints)) {
result.indexHints = [result.indexHints];
}
return result;
}
/**
* Asserts query settings by using wrapIndexHintsIntoArrayIfNeeded() helper method to ensure
* that the settings are in the same format as seen by the server.
*/
assertEqualSettings(lhs, rhs, message) {
assert.docEq(this.wrapIndexHintsIntoArrayIfNeeded(lhs),
this.wrapIndexHintsIntoArrayIfNeeded(rhs),
message);
}
/**
* Asserts that the expected engine is run on the input query and settings.
*/
assertQueryFramework({query, settings, expectedEngine}) {
// Ensure that query settings cluster parameter is empty.
this.assertQueryShapeConfiguration([]);
// Apply the provided settings for the query.
if (settings) {
assert.commandWorked(
this._db.adminCommand({setQuerySettings: query, settings: settings}));
// Wait until the settings have taken effect.
const expectedConfiguration = [this.makeQueryShapeConfiguration(settings, query)];
this.assertQueryShapeConfiguration(expectedConfiguration);
}
const withoutDollarDB = query.aggregate ? {...this.withoutDollarDB(query), cursor: {}}
: this.withoutDollarDB(query);
const explain = assert.commandWorked(this._db.runCommand({explain: withoutDollarDB}));
const engine = getEngine(explain);
assert.eq(
engine, expectedEngine, `Expected engine to be ${expectedEngine} but found ${engine}`);
// Ensure that no $cursor stage exists, which means the whole query got pushed down to find,
// if 'expectedEngine' is SBE.
if (query.aggregate) {
const cursorStages = getAggPlanStages(explain, "$cursor");
if (expectedEngine === "sbe") {
assert.eq(cursorStages.length, 0, cursorStages);
} else {
assert.gte(cursorStages.length, 0, cursorStages);
}
}
// If a hinted index exists, assert it was used.
if (query.hint) {
const winningPlan = getWinningPlanFromExplain(explain);
const ixscanStage = getPlanStages(winningPlan, "IXSCAN")[0];
assert.eq(query.hint, ixscanStage.keyPattern, winningPlan);
}
this.removeAllQuerySettings();
}
/**
* Tests that setting `reject` fails the expected query `query`, and a query with the same
* shape, `queryPrime`, and does _not_ fail a query of differing shape, `unrelatedQuery`.
*/
assertRejection({query, queryPrime, unrelatedQuery}) {
// Confirm there's no pre-existing settings.
this.assertQueryShapeConfiguration([]);
const type = Object.keys(query)[0];
const getRejectCount = () =>
db.runCommand({serverStatus: 1}).metrics.commands[type].rejected;
const rejectBaseline = getRejectCount();
const assertRejectedDelta = (delta) => {
let actual;
assert.soon(() => (actual = getRejectCount()) == delta + rejectBaseline,
() => tojson({
expected: delta + rejectBaseline,
actual: actual,
cmdType: type,
cmdMetrics: db.runCommand({serverStatus: 1}).metrics.commands[type],
metrics: db.runCommand({serverStatus: 1}).metrics,
}));
};
const getFailedCount = () => db.runCommand({serverStatus: 1}).metrics.commands[type].failed;
query = this.withoutDollarDB(query);
queryPrime = this.withoutDollarDB(queryPrime);
unrelatedQuery = this.withoutDollarDB(unrelatedQuery);
for (const q of [query, queryPrime, unrelatedQuery]) {
// With no settings, all queries should succeed.
assert.commandWorked(db.runCommand(q));
// And so should explaining those queries.
assert.commandWorked(db.runCommand({explain: q}));
}
// Still nothing has been rejected.
assertRejectedDelta(0);
// Set reject flag for query under test.
assert.commandWorked(db.adminCommand(
{setQuerySettings: {...query, $db: db.getName()}, settings: {reject: true}}));
// Confirm settings updated.
this.assertQueryShapeConfiguration(
[this.makeQueryShapeConfiguration({reject: true}, {...query, $db: db.getName()})],
/* shouldRunExplain */ true);
// Just setting the reject flag should not alter the rejected cmd counter.
assertRejectedDelta(0);
// Verify other query with same shape has those settings applied too.
this.assertExplainQuerySettings({...queryPrime, $db: db.getName()}, {reject: true});
// Explain should not alter the rejected cmd counter.
assertRejectedDelta(0);
const failedBaseline = getFailedCount();
// The queries with the same shape should both _fail_.
assert.commandFailedWithCode(db.runCommand(query), ErrorCodes.QueryRejectedBySettings);
assertRejectedDelta(1);
assert.commandFailedWithCode(db.runCommand(queryPrime), ErrorCodes.QueryRejectedBySettings);
assertRejectedDelta(2);
// Despite some rejections occurring, there should not have been any failures.
assert.eq(failedBaseline, getFailedCount());
// Unrelated query should succeed.
assert.commandWorked(db.runCommand(unrelatedQuery));
for (const q of [query, queryPrime, unrelatedQuery]) {
// All explains should still succeed.
assert.commandWorked(db.runCommand({explain: q}));
}
// Explains still should not alter the cmd rejected counter.
assertRejectedDelta(2);
// Remove the setting.
this.removeAllQuerySettings();
this.assertQueryShapeConfiguration([]);
// Once again, all queries should succeed.
for (const q of [query, queryPrime, unrelatedQuery]) {
assert.commandWorked(db.runCommand(q));
assert.commandWorked(db.runCommand({explain: q}));
}
// Successful, non-rejected queries should not alter the rejected cmd counter.
assertRejectedDelta(2);
}
}