summaryrefslogtreecommitdiff
path: root/jstests/replsets/apply_ops_idempotency.js
blob: 16761c27bee09d09512a7cf6f9d85b47d2ebba60 (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
(function() {
'use strict';
const debug = 0;

let rst = new ReplSetTest({name: "applyOpsIdempotency", nodes: 1});
rst.startSet();
rst.initiate();

/**
 * Returns true if this database contains any drop-pending collections.
 */
function containsDropPendingCollection(mydb) {
    const res =
        assert.commandWorked(mydb.runCommand("listCollections", {includePendingDrops: true}));
    const collectionInfos = res.cursor.firstBatch;
    const collectionNames = collectionInfos.map(c => c.name);
    return Boolean(collectionNames.find(c => c.indexOf('system.drop.') == 0));
}

/**
 *  Apply ops on mydb, asserting success.
 */
function assertApplyOpsWorks(testdbs, ops) {
    // Remaining operations in ops must still be applied
    while (ops.length) {
        let cmd = {applyOps: ops};
        let res = testdbs[0].adminCommand(cmd);
        if (debug) {
            printjson({applyOps: ops, res});
        }

        // Wait for any drop-pending collections to be removed by the reaper before proceeding.
        assert.soon(function() {
            return !testdbs.find(mydb => containsDropPendingCollection(mydb));
        });

        // If the entire operation succeeded, we're done.
        if (res.ok == 1)
            return res;

        // Skip any operations that succeeded.
        while (res.applied-- && res.results.shift())
            ops.shift();

        // These errors are expected when replaying operations and should be ignored.
        if (res.code == ErrorCodes.NamespaceNotFound || res.code == ErrorCodes.DuplicateKey) {
            ops.shift();
            continue;
        }

        // Generate the appropriate error message.
        assert.commandWorked(res, tojson(cmd));
    }
}

/**
 *  Run the dbHash command on mydb, assert it worked and return the md5.
 */
function dbHash(mydb) {
    let cmd = {dbHash: 1};
    let res = mydb.runCommand(cmd);
    assert.commandWorked(res, tojson(cmd));
    return res.md5;
}

/**
 *  Gather collection info and dbHash results of each of the passed databases.
 */
function dbInfo(dbs) {
    return dbs.map((db) => {
        return {name: db.getName(), info: db.getCollectionInfos(), md5: dbHash(db)};
    });
}

var getCollections = (mydb, prefixes) => prefixes.map((prefix) => mydb[prefix]);

/**
 *  Test functions to run and test using replay of oplog.
 */
var tests = {
    crud: (mydb) => {
        let [x, y, z] = getCollections(mydb, ['x', 'y', 'z']);
        assert.writeOK(x.insert({_id: 1}));
        assert.writeOK(x.update({_id: 1}, {$set: {x: 1}}));
        assert.writeOK(x.remove({_id: 1}));

        assert.writeOK(y.update({_id: 1}, {y: 1}));
        assert.writeOK(y.insert({_id: 2, y: false, z: false}));
        assert.writeOK(y.update({_id: 2}, {y: 2}));

        assert.writeOK(z.insert({_id: 1, z: 1}));
        assert.writeOK(z.remove({_id: 1}));
        assert.writeOK(z.insert({_id: 1}));
        assert.writeOK(z.insert({_id: 2, z: 2}));
    },
    renameCollectionWithinDatabase: (mydb) => {
        let [x, y, z] = getCollections(mydb, ['x', 'y', 'z']);
        assert.writeOK(x.insert({_id: 1, x: 1}));
        assert.writeOK(y.insert({_id: 1, y: 1}));

        assert.commandWorked(x.renameCollection(z.getName()));
        assert.writeOK(z.insert({_id: 2, x: 2}));
        assert.writeOK(x.insert({_id: 2, x: false}));
        assert.writeOK(y.insert({y: 2}));

        assert.commandWorked(y.renameCollection(x.getName(), true));
        assert.commandWorked(z.renameCollection(y.getName()));
    },
    renameCollectionWithinDatabaseDroppingTargetByUUID: (mydb) => {
        assert.commandWorked(mydb.createCollection("x"));
        assert.commandWorked(mydb.createCollection("y"));
        assert.commandWorked(mydb.createCollection("z"));

        assert.commandWorked(mydb.x.renameCollection('xx'));
        // When replayed on a up-to-date db, this oplog entry may drop
        // collection z rather than collection x if the dropTarget is not
        // specified by UUID. (See SERVER-33087)
        assert.commandWorked(mydb.y.renameCollection('xx', true));
        assert.commandWorked(mydb.xx.renameCollection('yy'));
        assert.commandWorked(mydb.z.renameCollection('xx'));
    },
    renameCollectionWithinDatabaseDropTargetEvenWhenSourceIsEmpty: (mydb) => {
        assert.commandWorked(mydb.createCollection("x"));
        assert.commandWorked(mydb.createCollection("y"));
        assert.commandWorked(mydb.x.renameCollection('y', true));
        assert(mydb.y.drop());
    },
    renameCollectionAcrossDatabases: (mydb) => {
        let otherdb = mydb.getSiblingDB(mydb + '_');
        let [x, y] = getCollections(mydb, ['x', 'y']);
        let [z] = getCollections(otherdb, ['z']);
        assert.writeOK(x.insert({_id: 1, x: 1}));
        assert.writeOK(y.insert({_id: 1, y: 1}));

        assert.commandWorked(
            mydb.adminCommand({renameCollection: x.getFullName(), to: z.getFullName()}));
        assert.writeOK(z.insert({_id: 2, x: 2}));
        assert.writeOK(x.insert({_id: 2, x: false}));
        assert.writeOK(y.insert({y: 2}));

        assert.commandWorked(mydb.adminCommand(
            {renameCollection: y.getFullName(), to: x.getFullName(), dropTarget: true}));
        assert.commandWorked(
            mydb.adminCommand({renameCollection: z.getFullName(), to: y.getFullName()}));
        return [mydb, otherdb];
    },
    renameCollectionAcrossDatabasesWithDropAndConvertToCapped: (db1) => {
        let db2 = db1.getSiblingDB(db1 + '_');
        assert.commandWorked(db1.createCollection("a"));
        assert.commandWorked(db1.createCollection("b"));
        assert.commandWorked(db2.createCollection("c"));
        assert.commandWorked(db2.createCollection("d"));
        let [a, b] = getCollections(db1, ['a', 'b']);
        let [c, d] = getCollections(db2, ['c', 'd']);

        assert.commandWorked(db1.adminCommand(
            {renameCollection: a.getFullName(), to: c.getFullName(), dropTarget: true}));

        assert(d.drop());

        assert.commandWorked(db1.adminCommand(
            {renameCollection: c.getFullName(), to: d.getFullName(), dropTarget: false}));

        assert.commandWorked(db1.adminCommand(
            {renameCollection: b.getFullName(), to: c.getFullName(), dropTarget: false}));
        assert.commandWorked(db2.runCommand({convertToCapped: "d", size: 1000}));

        return [db1, db2];
    },
    createIndex: (mydb) => {
        let [x, y] = getCollections(mydb, ['x', 'y']);
        assert.commandWorked(x.createIndex({x: 1}));
        assert.writeOK(x.insert({_id: 1, x: 1}));
        assert.writeOK(y.insert({_id: 1, y: 1}));
        assert.commandWorked(y.createIndex({y: 1}));
        assert.writeOK(y.insert({_id: 2, y: 2}));
    },
};

/**
 *  Create a new uniquely named database, execute testFun and compute the dbHash. Then replay
 *  all different suffixes of the oplog and check for the correct hash. If testFun creates
 *  additional databases, it should return an array with all databases to check.
 */
function testIdempotency(primary, testFun, testName) {
    // Create a new database name, so it's easier to filter out our oplog records later.
    let dbname = (new Date()).toISOString().match(/[-0-9T]/g).join('');  // 2017-05-30T155055713
    let mydb = primary.getDB(dbname);

    // Allow testFun to return the array of databases to check (default is mydb).
    let testdbs = testFun(mydb) || [mydb];
    let expectedInfo = dbInfo(testdbs);

    let oplog = mydb.getSiblingDB('local').oplog.rs;
    let ops =
        oplog
            .find({op: {$ne: 'n'}, ns: new RegExp('^' + mydb.getName())}, {ts: 0, t: 0, h: 0, v: 0})
            .toArray();
    assert.gt(ops.length, 0, 'Could not find any matching ops in the oplog');
    testdbs.forEach((db) => assert.commandWorked(db.dropDatabase()));

    if (debug) {
        print(testName + ': replaying suffixes of ' + ops.length + ' operations');
        printjson(ops);
    }

    for (let j = 0; j < ops.length; j++) {
        let replayOps = ops.slice(j);
        assertApplyOpsWorks(testdbs, replayOps);
        let actualInfo = dbInfo(testdbs);
        assert.eq(actualInfo,
                  expectedInfo,
                  'unexpected differences between databases after replaying final ' +
                      replayOps.length + ' ops in test ' + testName + ": " + tojson(replayOps));
    }
}

for (let f in tests)
    testIdempotency(rst.getPrimary(), tests[f], f);

rst.stopSet();
})();