summaryrefslogtreecommitdiff
path: root/jstests/sharding/sharding_statistics_server_status.js
blob: 7e25f5465baad2b20aeccedc2133804d56f9d9d9 (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
//
// Tests that serverStatus includes sharding statistics by default and the sharding statistics are
// indeed the correct values. Does not test the catalog cache portion of sharding statistics.
//
// @tags: [uses_transactions]

(function() {
    'use strict';

    load("jstests/libs/chunk_manipulation_util.js");
    load("jstests/libs/parallelTester.js");

    function ShardStat() {
        this.countDonorMoveChunkStarted = 0;
        this.countRecipientMoveChunkStarted = 0;
        this.countDocsClonedOnRecipient = 0;
        this.countDocsClonedOnDonor = 0;
        this.countDocsDeletedOnDonor = 0;
    }

    function incrementStatsAndCheckServerShardStats(donor, recipient, numDocs) {
        ++donor.countDonorMoveChunkStarted;
        donor.countDocsClonedOnDonor += numDocs;
        ++recipient.countRecipientMoveChunkStarted;
        recipient.countDocsClonedOnRecipient += numDocs;
        donor.countDocsDeletedOnDonor += numDocs;
        const statsFromServerStatus = shardArr.map(function(shardVal) {
            return shardVal.getDB('admin').runCommand({serverStatus: 1}).shardingStatistics;
        });
        for (let i = 0; i < shardArr.length; ++i) {
            assert(statsFromServerStatus[i]);
            assert(statsFromServerStatus[i].countStaleConfigErrors);
            assert(statsFromServerStatus[i].totalCriticalSectionCommitTimeMillis);
            assert(statsFromServerStatus[i].totalCriticalSectionTimeMillis);
            assert(statsFromServerStatus[i].totalDonorChunkCloneTimeMillis);
            assert(statsFromServerStatus[i].countDonorMoveChunkLockTimeout);
            assert.eq(stats[i].countDonorMoveChunkStarted,
                      statsFromServerStatus[i].countDonorMoveChunkStarted);
            assert.eq(stats[i].countDocsClonedOnRecipient,
                      statsFromServerStatus[i].countDocsClonedOnRecipient);
            assert.eq(stats[i].countDocsClonedOnDonor,
                      statsFromServerStatus[i].countDocsClonedOnDonor);
            assert.eq(stats[i].countDocsDeletedOnDonor,
                      statsFromServerStatus[i].countDocsDeletedOnDonor);
            assert.eq(stats[i].countRecipientMoveChunkStarted,
                      statsFromServerStatus[i].countRecipientMoveChunkStarted);
        }
    }

    function checkServerStatusMigrationLockTimeoutCount(shardConn, count) {
        const shardStats =
            assert.commandWorked(shardConn.adminCommand({serverStatus: 1})).shardingStatistics;
        assert(shardStats.hasOwnProperty("countDonorMoveChunkLockTimeout"));
        assert.eq(count, shardStats.countDonorMoveChunkLockTimeout);
    }

    function runConcurrentMoveChunk(host, ns, toShard) {
        const mongos = new Mongo(host);
        return mongos.adminCommand({moveChunk: ns, find: {_id: 1}, to: toShard});
    }

    function runConcurrentRead(host, dbName, collName) {
        const mongos = new Mongo(host);
        return mongos.getDB(dbName)[collName].find({_id: 5}).comment("concurrent read").itcount();
    }

    const dbName = "db";
    const collName = "coll";

    const st = new ShardingTest({shards: 2, mongos: 1});
    const mongos = st.s0;
    const admin = mongos.getDB("admin");
    const coll = mongos.getCollection(dbName + "." + collName);
    const numDocsToInsert = 3;
    const shardArr = [st.shard0, st.shard1];
    const stats = [new ShardStat(), new ShardStat()];
    let numDocsInserted = 0;

    assert.commandWorked(admin.runCommand({enableSharding: coll.getDB() + ""}));
    st.ensurePrimaryShard(coll.getDB() + "", st.shard0.shardName);
    assert.commandWorked(admin.runCommand({shardCollection: coll + "", key: {_id: 1}}));
    assert.commandWorked(admin.runCommand({split: coll + "", middle: {_id: 0}}));

    // Move chunk from shard0 to shard1 without docs.
    assert.commandWorked(
        mongos.adminCommand({moveChunk: coll + '', find: {_id: 1}, to: st.shard1.shardName}));
    incrementStatsAndCheckServerShardStats(stats[0], stats[1], numDocsInserted);

    // Insert docs and then move chunk again from shard1 to shard0.
    for (let i = 0; i < numDocsToInsert; ++i) {
        assert.writeOK(coll.insert({_id: i}));
        ++numDocsInserted;
    }
    assert.commandWorked(mongos.adminCommand(
        {moveChunk: coll + '', find: {_id: 1}, to: st.shard0.shardName, _waitForDelete: true}));
    incrementStatsAndCheckServerShardStats(stats[1], stats[0], numDocsInserted);

    // Check that numbers are indeed cumulative. Move chunk from shard0 to shard1.
    assert.commandWorked(mongos.adminCommand(
        {moveChunk: coll + '', find: {_id: 1}, to: st.shard1.shardName, _waitForDelete: true}));
    incrementStatsAndCheckServerShardStats(stats[0], stats[1], numDocsInserted);

    // Move chunk from shard1 to shard0.
    assert.commandWorked(mongos.adminCommand(
        {moveChunk: coll + '', find: {_id: 1}, to: st.shard0.shardName, _waitForDelete: true}));
    incrementStatsAndCheckServerShardStats(stats[1], stats[0], numDocsInserted);

    //
    // Tests for the count of migrations aborting from lock timeouts.
    //

    // Lower migrationLockAcquisitionMaxWaitMS so migrations time out more quickly.
    const donorConn = st.rs0.getPrimary();
    const lockParameterRes = assert.commandWorked(
        donorConn.adminCommand({getParameter: 1, migrationLockAcquisitionMaxWaitMS: 1}));
    const originalMigrationLockTimeout = lockParameterRes.migrationLockAcquisitionMaxWaitMS;
    assert.commandWorked(
        donorConn.adminCommand({setParameter: 1, migrationLockAcquisitionMaxWaitMS: 2 * 1000}));

    // Counter starts at 0.
    checkServerStatusMigrationLockTimeoutCount(donorConn, 0);

    // Pause a migration before entering the critical section.
    pauseMoveChunkAtStep(donorConn, moveChunkStepNames.reachedSteadyState);
    let moveChunkThread = new ScopedThread(
        runConcurrentMoveChunk, st.s.host, dbName + "." + collName, st.shard1.shardName);
    moveChunkThread.start();
    waitForMoveChunkStep(donorConn, moveChunkStepNames.reachedSteadyState);

    // Start a transaction and insert to the migrating chunk to block entering the critical section.
    const session = mongos.startSession();
    session.startTransaction();
    assert.commandWorked(session.getDatabase(dbName)[collName].insert({_id: 5}));

    // Unpause the migration and it should time out entering the critical section.
    unpauseMoveChunkAtStep(donorConn, moveChunkStepNames.reachedSteadyState);
    moveChunkThread.join();
    assert.commandFailedWithCode(moveChunkThread.returnData(), ErrorCodes.LockTimeout);

    // Clean up the transaction and verify the counter was incremented in serverStatus.
    assert.commandWorked(session.abortTransaction_forTesting());

    checkServerStatusMigrationLockTimeoutCount(donorConn, 1);

    // Writes are blocked during the critical section, so insert a document into the chunk to be
    // moved before the migration begins that can be read later.
    assert.commandWorked(st.s.getDB(dbName)[collName].insert({_id: 5}));

    // Pause a migration after entering the critical section, but before entering the commit phase.
    pauseMoveChunkAtStep(donorConn, moveChunkStepNames.chunkDataCommitted);
    moveChunkThread = new ScopedThread(
        runConcurrentMoveChunk, st.s.host, dbName + "." + collName, st.shard1.shardName);
    moveChunkThread.start();
    waitForMoveChunkStep(donorConn, moveChunkStepNames.chunkDataCommitted);

    // Pause a read while it's holding locks so the migration can't commit.
    assert.commandWorked(donorConn.adminCommand(
        {configureFailPoint: "waitInFindBeforeMakingBatch", mode: "alwaysOn"}));
    const concurrentRead = new ScopedThread(runConcurrentRead, st.s.host, dbName, collName);
    concurrentRead.start();
    assert.soon(function() {
        const curOpResults = assert.commandWorked(donorConn.adminCommand({currentOp: 1}));
        return curOpResults.inprog.some(op => op["command"]["comment"] === "concurrent read");
    });

    // Unpause the migration and it should time out entering the commit phase.
    unpauseMoveChunkAtStep(donorConn, moveChunkStepNames.chunkDataCommitted);
    moveChunkThread.join();
    assert.commandFailedWithCode(moveChunkThread.returnData(), ErrorCodes.LockTimeout);

    // Let the read finish and verify the counter was incremented in serverStatus.
    assert.commandWorked(
        donorConn.adminCommand({configureFailPoint: "waitInFindBeforeMakingBatch", mode: "off"}));
    concurrentRead.join();
    assert.eq(1, concurrentRead.returnData());

    checkServerStatusMigrationLockTimeoutCount(donorConn, 2);

    assert.commandWorked(donorConn.adminCommand(
        {setParameter: 1, migrationLockAcquisitionMaxWaitMS: originalMigrationLockTimeout}));

    st.stop();
})();