summaryrefslogtreecommitdiff
path: root/jstests/replsets/unconditional_step_down.js
blob: 4d5e37821db9a649009fb48284062c0235d95b18 (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
/**
 * Tests that unconditional step down terminates writes, but not reads. And, doesn't disconnect
 * the connections if primary is stepping down to secondary.
 * @tags: [requires_document_locking]
 */
(function() {
"use strict";

load("jstests/libs/curop_helpers.js");  // for waitForCurOpByFailPoint().

const testName = "txnsDuringStepDown";
const dbName = testName;
const collName = "testcoll";
const collNss = dbName + '.' + collName;

const rst = new ReplSetTest({nodes: [{}, {rsConfig: {priority: 0}}, {arbiter: true}]});
rst.startSet();
rst.initiate();

let primary;
let secondary;
let primaryDB;

function refreshConnection() {
    primary = rst.getPrimary();
    primaryDB = primary.getDB(dbName);
    secondary = rst.getSecondary();
}

refreshConnection();

jsTestLog("Writing data to collection.");
assert.commandWorked(primaryDB.runCommand({insert: collName, documents: [{_id: 'readOp'}]}));
rst.awaitReplication();

const readFailPoint = "waitInFindBeforeMakingBatch";
const writeFailPoint = "hangWithLockDuringBatchInsert";

TestData.dbName = dbName;
TestData.collName = collName;
TestData.readFailPoint = readFailPoint;
TestData.skipRetryOnNetworkError = true;

function runStepDownTest({testMsg, stepDownFn, toRemovedState}) {
    jsTestLog(`Testing step down due to ${testMsg}`);

    // 'toRemovedState' determines whether to tag the connections not to close when
    // primary changes its state to removed.
    toRemovedState = toRemovedState || false;

    // Clears the log before running the test.
    assert.commandWorked(primary.adminCommand({clearLog: 'global'}));

    jsTestLog("Enable fail point for namespace '" + collNss + "'");
    // Find command.
    assert.commandWorked(primary.adminCommand({
        configureFailPoint: readFailPoint,
        data: {nss: collNss, shouldCheckForInterrupt: true},
        mode: "alwaysOn"
    }));
    // Insert command.
    assert.commandWorked(primary.adminCommand({
        configureFailPoint: writeFailPoint,
        data: {nss: collNss, shouldCheckForInterrupt: true},
        mode: "alwaysOn"
    }));

    var startSafeParallelShell = (func, port) => {
        TestData.func = func;
        var safeFunc = (toRemovedState) ? () => {
            assert.commandWorked(db.adminCommand({isMaster: 1, hangUpOnStepDown: false}));
            TestData.func();
        } : func;
        return startParallelShell(safeFunc, port);
    };

    const joinReadThread = startSafeParallelShell(() => {
        jsTestLog("Start blocking find cmd before step down");
        var findRes = assert.commandWorked(
            db.getSiblingDB(TestData.dbName).runCommand({"find": TestData.collName}));
        assert.eq(findRes.cursor.firstBatch.length, 1);
    }, primary.port);

    const joinWriteThread = startSafeParallelShell(() => {
        jsTestLog("Start blocking insert cmd before step down");
        assert.commandFailedWithCode(
            db.getSiblingDB(TestData.dbName)[TestData.collName].insert([{val: 'writeOp1'}]),
            ErrorCodes.InterruptedDueToReplStateChange);
    }, primary.port);

    const joinUnblockStepDown = startSafeParallelShell(() => {
        load("jstests/libs/check_log.js");

        jsTestLog("Wait for step down to start killing operations");
        checkLog.contains(db, "Starting to kill user operations");

        jsTestLog("Unblock step down");
        // Turn off fail point on find cmd to allow step down to continue.
        assert.commandWorked(
            db.adminCommand({configureFailPoint: TestData.readFailPoint, mode: "off"}));
    }, primary.port);

    jsTestLog("Wait for find cmd to reach the fail point");
    waitForCurOpByFailPoint(primaryDB, collNss, readFailPoint);

    jsTestLog("Wait for write cmd to reach the fail point");
    waitForCurOpByFailPoint(primaryDB, collNss, writeFailPoint);

    let res = assert.commandWorked(primary.adminCommand({replSetGetStatus: 1}));
    assert(res.electionCandidateMetrics,
           () => "Response should have an 'electionCandidateMetrics' field: " + tojson(res));

    jsTestLog("Trigger step down");
    var oldConfig = stepDownFn();

    // Waits for all threads to join.
    joinUnblockStepDown();
    joinReadThread();
    joinWriteThread();

    // Wait till the primary stepped down to primary.
    waitForState(primary,
                 (toRemovedState) ? ReplSetTest.State.REMOVED : ReplSetTest.State.SECONDARY);

    assert.commandWorked(primary.adminCommand({configureFailPoint: writeFailPoint, mode: "off"}));

    // Check that the 'electionCandidateMetrics' section of the replSetGetStatus response has been
    // cleared, since the node is no longer primary.
    if (!toRemovedState) {
        res = assert.commandWorked(primary.adminCommand({replSetGetStatus: 1}));
        assert(
            !res.electionCandidateMetrics,
            () => "Response should not have an 'electionCandidateMetrics' field: " + tojson(res));
    }

    // Get the new primary.
    refreshConnection();
}

function runStepsDowntoRemoved(params) {
    var oldConfigBeforeTest = rst.getReplSetConfigFromNode();

    // Run the test.
    params["toRemovedState"] = true;
    runStepDownTest(params);
    oldConfigBeforeTest.version = ++(rst.getReplSetConfigFromNode().version);

    // On exit, add the removed node back to replica set.
    assert.commandWorked(primary.adminCommand({replSetReconfig: oldConfigBeforeTest, force: true}));
    refreshConnection();
}

runStepDownTest({
    testMsg: "reconfig command",
    stepDownFn: () => {
        load("./jstests/replsets/rslib.js");
        var newConfig = rst.getReplSetConfigFromNode();

        var oldMasterId = rst.getNodeId(primary);
        var newMasterId = rst.getNodeId(secondary);

        newConfig.members[oldMasterId].priority = 0;
        newConfig.members[newMasterId].priority = 1;
        newConfig.version++;

        // Run it on primary
        assert.commandWorked(primary.adminCommand({replSetReconfig: newConfig, force: true}));
    }
});

runStepDownTest({
    testMsg: "reconfig via heartbeat",
    stepDownFn: () => {
        load("./jstests/replsets/rslib.js");
        var newConfig = rst.getReplSetConfigFromNode();

        var oldMasterId = rst.getNodeId(primary);
        var newMasterId = rst.getNodeId(secondary);

        newConfig.members[oldMasterId].priority = 0;
        newConfig.members[newMasterId].priority = 1;
        newConfig.version++;

        // Run it on secondary
        assert.commandWorked(secondary.adminCommand({replSetReconfig: newConfig, force: true}));
    }
});

runStepsDowntoRemoved({
    testMsg: "reconfig via heartbeat - primary to removed",
    stepDownFn: () => {
        load("./jstests/replsets/rslib.js");
        var newConfig = rst.getReplSetConfigFromNode();

        var oldMasterId = rst.getNodeId(primary);
        var newMasterId = rst.getNodeId(secondary);

        newConfig.members[newMasterId].priority = 1;
        // Remove the current primary from the config
        newConfig.members.splice(oldMasterId, 1);
        newConfig.version++;

        // Run it on secondary
        assert.commandWorked(secondary.adminCommand({replSetReconfig: newConfig, force: true}));
    }
});

runStepDownTest({
    testMsg: "stepdown via heartbeat",
    stepDownFn: () => {
        load("./jstests/replsets/rslib.js");
        var newConfig = rst.getReplSetConfigFromNode();

        var newMasterId = rst.getNodeId(secondary);

        newConfig.members[newMasterId].priority = 2;
        newConfig.version++;

        // Run it on primary
        assert.commandWorked(primary.adminCommand({replSetReconfig: newConfig, force: false}));

        // Now, step up the secondary which will make the current primary to step down.
        rst.stepUp(secondary);
    }
});

rst.stopSet();
})();