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

/**
 * invalidated_cursors.js
 *
 * This workload was designed to stress creating, pinning, and invalidating cursors through the
 * cursor manager. Threads perform find, getMore and explain commands while the database,
 * collection, or an index is dropped.
 *
 * @tags: [uses_curop_agg_stage, state_functions_share_cursor]
 */

load('jstests/concurrency/fsm_workload_helpers/server_types.js');  // for isMongos
load("jstests/concurrency/fsm_workload_helpers/assert_handle_fail_in_transaction.js");

var $config = (function() {
    let data = {
        chooseRandomlyFrom: function chooseRandomlyFrom(arr) {
            if (!Array.isArray(arr)) {
                throw new Error('Expected array for first argument, but got: ' + tojson(arr));
            }
            return arr[Random.randInt(arr.length)];
        },

        involvedCollections: ['coll0', 'coll1', 'coll2'],
        indexSpecs: [{a: 1, b: 1}, {c: 1}],

        numDocs: 100,
        batchSize: 2,

        /**
         * Inserts 'this.numDocs' new documents into the specified collection and ensures that the
         * indexes 'this.indexSpecs' exist on the collection. Note that means it is safe for
         * multiple threads to perform this function simultaneously.
         */
        populateDataAndIndexes: function populateDataAndIndexes(db, collName) {
            let bulk = db[collName].initializeUnorderedBulkOp();
            for (let i = 0; i < this.numDocs; ++i) {
                bulk.insert({});
            }
            let res = bulk.execute();
            assertAlways.commandWorked(res);
            assertAlways.eq(this.numDocs, res.nInserted, tojson(res));

            this.indexSpecs.forEach(indexSpec => {
                let res = db[collName].createIndex(indexSpec);
                assertWorkedHandleTxnErrors(res, ErrorCodes.IndexBuildAlreadyInProgress);
            });
        },

        /**
         * Calls 'killFn' on a random getMore that's currently running.
         */
        killRandomGetMore: function killRandomGetMore(someDB, killFn) {
            const admin = someDB.getSiblingDB("admin");
            const getMores = admin
                                 .aggregate([
                                     // idleConnections true so we can also kill cursors which are
                                     // not currently active.
                                     // localOps true so that currentOp reports the mongos
                                     // operations when run on a sharded cluster, instead of the
                                     // shard's operations.
                                     {$currentOp: {idleConnections: true, localOps: true}},
                                     // We only about getMores.
                                     {$match: {"command.getMore": {$exists: true}}},
                                     // Only find getMores running on the database for this test.
                                     {$match: {"ns": {$regex: this.uniqueDBName + "\."}}}
                                 ])
                                 .toArray();

            if (getMores.length === 0) {
                return;
            }

            const toKill = this.chooseRandomlyFrom(getMores);
            return killFn(toKill);
        }
    };

    let states = {
        /**
         * This is a no-op, used only as a transition state.
         */
        init: function init(db, collName) {},

        /**
         * Runs a query on the collection with a small enough batchSize to leave the cursor open.
         * If the command was successful, stores the resulting cursor in 'this.cursor'.
         */
        query: function query(unusedDB, unusedCollName) {
            let myDB = unusedDB.getSiblingDB(this.uniqueDBName);
            let res = myDB.runCommand({
                find: this.chooseRandomlyFrom(this.involvedCollections),
                filter: {},
                batchSize: this.batchSize
            });

            if (res.ok) {
                this.cursor = new DBCommandCursor(myDB, res, this.batchSize);
            }
        },

        /**
         * Explains a find on a collection.
         */
        explain: function explain(unusedDB, unusedCollName) {
            let myDB = unusedDB.getSiblingDB(this.uniqueDBName);
            let res = myDB.runCommand({
                explain: {find: this.chooseRandomlyFrom(this.involvedCollections), filter: {}},
                verbosity: "executionStats"
            });
            assertAlways.commandWorked(res);
        },

        /**
         * This is just a transition state that serves as a placeholder to delegate to one of the
         * specific kill types like 'killOp' or 'killCursors'.
         */
        kill: function kill(unusedDB, unusedCollName) {},

        /**
         * Choose a random cursor that's open and kill it.
         */
        killCursor: function killCursor(unusedDB, unusedCollName) {
            const myDB = unusedDB.getSiblingDB(this.uniqueDBName);

            // Not checking the return value, since the cursor may be closed on its own
            // before this has a chance to run.
            this.killRandomGetMore(myDB, function(toKill) {
                const res = myDB.runCommand(
                    {killCursors: toKill.command.collection, cursors: [toKill.command.getMore]});
                assertAlways.commandWorked(res);
            });
        },

        killOp: function killOp(unusedDB, unusedCollName) {
            const myDB = unusedDB.getSiblingDB(this.uniqueDBName);
            // Not checking return value since the operation may end on its own before we have
            // a chance to kill it.
            this.killRandomGetMore(myDB, function(toKill) {
                assertAlways.commandWorked(myDB.killOp(toKill.opid));
            });
        },

        /**
         * Requests enough results from 'this.cursor' to ensure that another batch is needed, and
         * thus ensures that a getMore request is sent for 'this.cursor'.
         */
        getMore: function getMore(unusedDB, unusedCollName) {
            if (!this.hasOwnProperty('cursor')) {
                return;
            }

            for (let i = 0; i <= this.batchSize; ++i) {
                try {
                    if (!this.cursor.hasNext()) {
                        break;
                    }
                    this.cursor.next();
                } catch (e) {
                    // The getMore request can fail if the database, a collection, or an index was
                    // dropped. It can also fail if another thread kills it through killCursor or
                    // killOp.
                    assertAlways.contains(e.code,
                                          [
                                              ErrorCodes.OperationFailed,
                                              ErrorCodes.QueryPlanKilled,
                                              ErrorCodes.CursorNotFound,
                                              ErrorCodes.CursorKilled,
                                              ErrorCodes.Interrupted,
                                          ],
                                          'unexpected error code: ' + e.code + ': ' + e.message);
                }
            }
        },

        /**
         * Drops the database being used by this workload and then re-creates each of
         * 'this.involvedCollections' by repopulating them with data and indexes.
         */
        dropDatabase: function dropDatabase(unusedDB, unusedCollName) {
            if (isMongos(unusedDB)) {
                // This workload can sometimes triggers an 'unable to target write op for
                // collection ... caused by ... database not found' error. Further investigation
                // still needs to be done, but these failures may be due to SERVER-17397 'drops in
                // a sharded cluster may not fully succeed' because it drops and reuses the same
                // namespaces. For now, we avoid dropping the database on a sharded cluster.
                return;
            }

            let myDB = unusedDB.getSiblingDB(this.uniqueDBName);
            myDB.dropDatabase();

            // Re-create all of the collections and indexes that were dropped.
            this.involvedCollections.forEach(collName => {
                this.populateDataAndIndexes(myDB, collName);
            });
        },

        /**
         * Randomly selects a collection from 'this.involvedCollections' and drops it. The
         * collection is then re-created with data and indexes.
         */
        dropCollection: function dropCollection(unusedDB, unusedCollName) {
            if (isMongos(unusedDB)) {
                // This workload can sometimes triggers an 'unable to target write op for
                // collection ... caused by ... database not found' error. Further investigation
                // still needs to be done, but these failures may be due to SERVER-17397 'drops in
                // a sharded cluster may not fully succeed' because it drops and reuses the same
                // namespaces. For now, we avoid dropping the collection on a sharded cluster.
                return;
            }

            let myDB = unusedDB.getSiblingDB(this.uniqueDBName);
            let targetColl = this.chooseRandomlyFrom(this.involvedCollections);

            myDB[targetColl].drop();

            // Re-create the collection that was dropped.
            this.populateDataAndIndexes(myDB, targetColl);
        },

        /**
         * Randomly selects a collection from 'this.involvedCollections' and an index from
         * 'this.indexSpecs' and drops that particular index from the collection. The index is then
         * re-created.
         */
        dropIndex: function dropIndex(unusedDB, unusedCollName) {
            let myDB = unusedDB.getSiblingDB(this.uniqueDBName);
            let targetColl = this.chooseRandomlyFrom(this.involvedCollections);
            let indexSpec = this.chooseRandomlyFrom(this.indexSpecs);

            // We don't assert that the command succeeded when dropping an index because it's
            // possible another thread has already dropped this index.
            myDB[targetColl].dropIndex(indexSpec);

            // Re-create the index that was dropped.
            assertAlways.commandWorked(myDB[targetColl].createIndex(indexSpec));
        }
    };

    let transitions = {
        init: {
            query: 0.6,
            explain: 0.1,
            dropDatabase: 0.1,
            dropCollection: 0.1,
            dropIndex: 0.1,
        },

        query: {kill: 0.1, getMore: 0.9},
        explain: {explain: 0.1, init: 0.9},
        kill: {killOp: 0.5, killCursor: 0.5},
        killOp: {init: 1},
        killCursor: {init: 1},
        getMore: {kill: 0.2, getMore: 0.6, init: 0.2},
        dropDatabase: {init: 1},
        dropCollection: {init: 1},
        dropIndex: {init: 1}
    };

    function setup(unusedDB, unusedCollName, cluster) {
        // Use the workload name as part of the database name, since the workload name is assumed to
        // be unique.
        this.uniqueDBName = unusedDB.getName() + 'invalidated_cursors';

        let myDB = unusedDB.getSiblingDB(this.uniqueDBName);
        this.involvedCollections.forEach(collName => {
            this.populateDataAndIndexes(myDB, collName);
            assertAlways.eq(this.numDocs, myDB[collName].find({}).itcount());
        });
    }

    return {
        threadCount: 10,
        iterations: 200,
        states: states,
        startState: 'init',
        transitions: transitions,
        data: data,
        setup: setup,
    };
})();