summaryrefslogtreecommitdiff
path: root/jstests/noPassthrough/index_build_operation_metrics.js
blob: 88b549e246707336acbabf0ef759761c64490b11 (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
/**
 * Tests resource consumption metrics for index builds.
 * @tags: [
 *   requires_replication,
 *   requires_wiredtiger,
 * ]
 */
(function() {
'use strict';

load('jstests/noPassthrough/libs/index_build.js');  // For IndexBuildTest

var rst = new ReplSetTest({
    nodes: 2,
    nodeOptions: {
        setParameter: {
            "measureOperationResourceConsumption": true,
            "aggregateOperationResourceConsumptionMetrics": true
        }
    }
});
rst.startSet();
rst.initiate();

const dbName = 'test';
const collName = 'test';
const primary = rst.getPrimary();
const secondary = rst.getSecondary();
const primaryDB = primary.getDB(dbName);
const secondaryDB = secondary.getDB(dbName);

const nDocs = 100;

const clearMetrics = (db) => {
    db.aggregate([{$operationMetrics: {clearMetrics: true}}]);
};

// Get aggregated metrics keyed by database name.
const getMetrics = (conn) => {
    const cursor = conn.getDB('admin').aggregate([{$operationMetrics: {}}]);

    let allMetrics = {};
    while (cursor.hasNext()) {
        let doc = cursor.next();
        allMetrics[doc.db] = doc;
    }
    return allMetrics;
};

const assertMetrics = (conn, assertFn) => {
    let metrics = getMetrics(conn);
    try {
        assertFn(metrics);
    } catch (e) {
        print("caught exception while checking metrics on " + tojson(conn) +
              ", metrics: " + tojson(metrics));
        throw e;
    }
};

assert.commandWorked(primaryDB.createCollection(collName));

/**
 * Load documents into the collection. Expect that metrics are reasonable and only reported on the
 * primary node.
 */
(function loadCollection() {
    clearMetrics(primaryDB);

    let bulk = primaryDB[collName].initializeUnorderedBulkOp();
    for (let i = 0; i < nDocs; i++) {
        bulk.insert({_id: i, a: i});
    }
    assert.commandWorked(bulk.execute());

    assertMetrics(primary, (metrics) => {
        // Each document is 29 bytes and we do not count oplog writes.
        assert.eq(metrics[dbName].docBytesWritten, 29 * nDocs);
        assert.eq(metrics[dbName].docUnitsWritten, nDocs);

        // The inserted keys will vary in size from 2 to 4 bytes depending on their value. Assert
        // that the number of bytes fall within that range.
        assert.gt(metrics[dbName].idxEntryBytesWritten, 2 * nDocs);
        assert.lt(metrics[dbName].idxEntryBytesWritten, 4 * nDocs);
        assert.eq(metrics[dbName].idxEntryUnitsWritten, 1 * nDocs);
    });

    // The secondary should not collect metrics for replicated index builds.
    rst.awaitReplication();

    assertMetrics(secondary, (metrics) => {
        assert.eq(undefined, metrics[dbName]);
    });
})();

/**
 * Build an index. Expect that metrics are reasonable and only reported on the primary node.
 */
(function buildIndex() {
    clearMetrics(primaryDB);
    assert.commandWorked(primaryDB[collName].createIndex({a: 1}));

    assertMetrics(primary, (metrics) => {
        // Each document is 29 bytes. Assert that we read at least as many document bytes as there
        // are in the collection. Some additional data is read from the catalog, but it has
        // randomized fields, so we don't make any exact assertions.
        assert.gt(metrics[dbName].primaryMetrics.docBytesRead, 29 * nDocs);
        assert.gt(metrics[dbName].primaryMetrics.docUnitsRead, 1 * nDocs);

        // Some bytes are written to the catalog and config.system.indexBuilds collection.
        assert.gt(metrics[dbName].docBytesWritten, 0);
        assert.gt(metrics[dbName].docUnitsWritten, 0);

        // The inserted keys will vary in size from 4 to 7 bytes depending on their value. Assert
        // that the number of bytes fall within that range.
        assert.gt(metrics[dbName].idxEntryBytesWritten, 4 * nDocs);
        assert.lt(metrics[dbName].idxEntryBytesWritten, 7 * nDocs);

        // Some index entries are written to the config.system.indexBuilds collection, but we should
        // read at least as many units as there are documents in the collection.
        assert.gte(metrics[dbName].idxEntryUnitsWritten, 1 * nDocs);
    });

    // The secondary should not collect metrics for replicated index builds.
    rst.awaitReplication();
    assertMetrics(secondary, (metrics) => {
        assert.eq(undefined, metrics[dbName]);
    });
})();

assert.commandWorked(primaryDB[collName].dropIndex({a: 1}));

/**
 * Build an index. Expect that metrics are reasonable and only reported on the primary node.
 */
(function buildUniqueIndex() {
    clearMetrics(primaryDB);
    assert.commandWorked(primaryDB[collName].createIndex({a: 1}, {unique: true}));

    assertMetrics(primary, (metrics) => {
        // Each document is 29 bytes. Assert that we read at least as many document bytes as there
        // are in the collection. Some additional data is read from the catalog, but it has
        // randomized fields, so we don't make any exact assertions.
        assert.gt(metrics[dbName].primaryMetrics.docBytesRead, 29 * nDocs);
        assert.gt(metrics[dbName].primaryMetrics.docUnitsRead, 1 * nDocs);

        // Some bytes are written to the catalog and config.system.indexBuilds collection.
        assert.gt(metrics[dbName].docBytesWritten, 0);
        assert.gt(metrics[dbName].docUnitsWritten, 0);

        // The inserted keys will vary in size from 4 to 7 bytes depending on their value. Assert
        // that the number of bytes fall within that range.
        assert.gt(metrics[dbName].idxEntryBytesWritten, 4 * nDocs);
        assert.lt(metrics[dbName].idxEntryBytesWritten, 7 * nDocs);

        // Some index entries are written to the config.system.indexBuilds collection, but we should
        // read at least as many units as there are documents in the collection.
        assert.gte(metrics[dbName].idxEntryUnitsWritten, 1 * nDocs);
    });

    // The secondary should not collect metrics for replicated index builds.
    rst.awaitReplication();
    assertMetrics(secondary, (metrics) => {
        assert.eq(undefined, metrics[dbName]);
    });
})();

assert.commandWorked(primaryDB[collName].dropIndex({a: 1}));

/**
 * Build a unique index that fails. Expect that metrics are reasonable and only reported on the
 * primary node.
 */
(function buildFailedUniqueIndex() {
    // Insert a document at the end that makes the index non-unique.
    assert.commandWorked(primaryDB[collName].insert({a: (nDocs - 1)}));

    clearMetrics(primaryDB);
    assert.commandFailedWithCode(primaryDB[collName].createIndex({a: 1}, {unique: true}),
                                 ErrorCodes.DuplicateKey);

    assertMetrics(primary, (metrics) => {
        // Each document is 29 bytes. Assert that we read at least as many document bytes as there
        // are in the collection. Some additional data is read from the catalog, but it has
        // randomized fields, so we don't make any exact assertions.
        assert.gt(metrics[dbName].primaryMetrics.docBytesRead, 29 * nDocs);
        assert.gt(metrics[dbName].primaryMetrics.docUnitsRead, 1 * nDocs);

        // Some bytes are written to the catalog and config.system.indexBuilds collection.
        assert.gt(metrics[dbName].docBytesWritten, 0);
        assert.gt(metrics[dbName].docUnitsWritten, 0);

        // The inserted keys will vary in size from 4 to 7 bytes depending on their value. Assert
        // that the number of bytes fall within that range.
        assert.gt(metrics[dbName].idxEntryBytesWritten, 4 * nDocs);
        assert.lt(metrics[dbName].idxEntryBytesWritten, 7 * nDocs);

        // Some index entries are written to the config.system.indexBuilds collection, but we should
        // read at least as many units as there are documents in the collection.
        assert.gte(metrics[dbName].idxEntryUnitsWritten, 1 * nDocs);
    });

    // The secondary should not collect metrics for replicated index builds.
    rst.awaitReplication();
    assertMetrics(secondary, (metrics) => {
        assert.eq(undefined, metrics[dbName]);
    });
})();

/**
 * Start an index build on one node and commit it on a different node. Expect that the primary node
 * that commits the index build collects and reports read metrics attributed to the primary state.
 * The the stepped-down node should not collect anything.
 */
(function buildIndexWithStepDown() {
    clearMetrics(primaryDB);

    // Hang the index build after kicking off the build on the secondary, but before scanning the
    // collection.
    IndexBuildTest.pauseIndexBuilds(primary);
    const awaitIndex = IndexBuildTest.startIndexBuild(primary,
                                                      primaryDB[collName].getFullName(),
                                                      {a: 1},
                                                      {},
                                                      [ErrorCodes.InterruptedDueToReplStateChange]);
    IndexBuildTest.waitForIndexBuildToStart(secondaryDB);

    // Step down the primary node. The command will return an error but the index build will
    // continue running.
    assert.commandWorked(primary.adminCommand({replSetStepDown: 60, force: true}));
    awaitIndex();

    // Allow the secondary to take over. Note that it needs a quorum (by default a majority) and
    // will wait for the old primary to complete.
    rst.stepUp(secondary);

    // Allow the index build to resume and wait for it to commit.
    IndexBuildTest.resumeIndexBuilds(primary);
    IndexBuildTest.waitForIndexBuildToStop(secondaryDB);
    rst.awaitReplication();

    // Get the metrics from what is now the new primary.
    assertMetrics(secondary, (metrics) => {
        // Each document is 29 bytes. Assert that we read at least as many document bytes as there
        // are in the collection. Some additional data is read from the catalog, but it has
        // randomized fields, so we don't make any exact assertions.
        assert.gt(metrics[dbName].primaryMetrics.docBytesRead, 29 * nDocs);
        assert.gt(metrics[dbName].primaryMetrics.docUnitsRead, 1 * nDocs);
        assert.eq(metrics[dbName].secondaryMetrics.docBytesRead, 0);
        assert.eq(metrics[dbName].secondaryMetrics.docUnitsRead, 0);

        // Some bytes are written to the catalog and config.system.indexBuilds collection.
        assert.gt(metrics[dbName].docBytesWritten, 0);
        assert.gt(metrics[dbName].docUnitsWritten, 0);

        // The inserted keys will vary in size from 4 to 7 bytes depending on their value. Assert
        // that the number of bytes fall within that range.
        assert.gt(metrics[dbName].idxEntryBytesWritten, 4 * nDocs);
        assert.lt(metrics[dbName].idxEntryBytesWritten, 7 * nDocs);

        // Some index entries are written to the config.system.indexBuilds collection, but we should
        // read at least as many units as there are documents in the collection.
        assert.gte(metrics[dbName].idxEntryUnitsWritten, 1 * nDocs);
    });

    // No significant metrics should be collected on the old primary.
    assertMetrics(primary, (metrics) => {
        // The old primary may have read document bytes on the catalog and config.system.indexBuilds
        // when setting up, but ensure that it does not read an entire collection's worth of data.
        // The reads are attributed to the secondary state because the node is no longer primary
        // when it aggregates its metrics after getting interrupted by the stepdown.
        assert.gte(metrics[dbName].primaryMetrics.docBytesRead, 0);
        assert.lt(metrics[dbName].primaryMetrics.docBytesRead, 29 * nDocs);
        assert.lt(metrics[dbName].secondaryMetrics.docBytesRead, 29 * nDocs);
        assert.eq(metrics[dbName].docBytesWritten, 0);
        assert.eq(metrics[dbName].docUnitsWritten, 0);
        assert.eq(metrics[dbName].idxEntryBytesWritten, 0);
        assert.eq(metrics[dbName].idxEntryBytesWritten, 0);
        assert.eq(metrics[dbName].idxEntryUnitsWritten, 0);
    });

    // Ensure the index was actually built. Do this after checking metrics because the helper calls
    // listIndexes which contributes to metrics.
    IndexBuildTest.assertIndexes(primaryDB[collName], 2, ['_id_', 'a_1']);
    IndexBuildTest.assertIndexes(secondaryDB[collName], 2, ['_id_', 'a_1']);
})();

rst.stopSet();
}());