summaryrefslogtreecommitdiff
path: root/jstests/slow1/terminate_during_shutdown_checkpoint.js
blob: bee868b43a84a56044ea82ece0878820ec52dd3b (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
/**
 * Terminates mongod during a clean shutdown.
 *
 * As part of a clean shutdown, WiredTiger takes a final checkpoint. Terminating mongod during this
 * process results in an unclean shutdown. During startup recovery, WiredTiger will use the last
 * successful checkpoint taken and replay any journal files. Replication recovery will replay any
 * operations beyond the stable timestamp from the oplog.
 *
 * This test is verifying that startup recovery works as designed following an unclean shutdown
 * during the closing checkpoint.
 *
 * @tags: [requires_wiredtiger, requires_persistence, requires_replication]
 */
(function() {
"use strict";

// This test triggers an unclean shutdown, which may cause inaccurate fast counts.
TestData.skipEnforceFastCountOnValidate = true;

load("jstests/libs/parallel_shell_helpers.js");  // For startParallelShell
load('jstests/libs/parallelTester.js');          // For Thread

const kSeparator = "/";
const copyDataFiles = function(src, dest) {
    ls(src).forEach((file) => {
        if (file.endsWith(kSeparator)) {
            return;
        }

        let fileName = file.substring(file.lastIndexOf(kSeparator) + 1);
        copyFile(file, dest + kSeparator + fileName);
    });

    ls(src + kSeparator + "journal").forEach((file) => {
        let fileName = file.substring(file.lastIndexOf(kSeparator) + 1);
        copyFile(file, dest + kSeparator + "journal" + kSeparator + fileName);
    });
};

// Multi-document prepared transaction workload executed by the client threads.
const threadWorkload = function(host, threadId, start, end) {
    load("jstests/core/txns/libs/prepare_helpers.js");

    try {
        const conn = new Mongo(host);

        let session;
        let sessionDB;
        let sessionColl;

        for (let i = start; i < end; i++) {
            if (session == undefined) {
                session = conn.startSession({causalConsistency: false});
                sessionDB = session.getDatabase("test");
                sessionColl = sessionDB.getCollection("foo");

                jsTestLog("ThreadId: " + threadId + ", starting transaction");
                session.startTransaction();
            }

            const docId = Math.floor(Math.random() * (end - start + 1)) + start;

            jsTestLog("ThreadId: " + threadId + ", inserting document with _id " +
                      docId.toString());
            const insertRes = sessionColl.insert({
                _id: docId,
                a: docId,
                b: docId,
                c: docId,
                d: docId,
                e: docId,
            });

            if (insertRes.nInserted == 0) {
                // DuplicateKey error using the generated docId for _id. Start a new transaction.
                session = undefined;
                continue;
            }

            if (i % 2 == 0) {
                assert.commandWorked(sessionColl.update({_id: docId}, {$unset: {a: 1}}));
                assert.commandWorked(sessionColl.update({_id: docId}, {$set: {a: i}}));
                assert.commandWorked(sessionColl.update({_id: docId}, {$inc: {b: 1}}));
                assert.commandWorked(sessionColl.update({_id: docId}, {$inc: {c: 2}}));
                assert.commandWorked(sessionColl.update({_id: docId}, {$inc: {d: 3}}));
                assert.commandWorked(sessionColl.update({_id: docId}, {$set: {e: i * i}}));
            }

            if (i % 4 == 0) {
                assert.commandWorked(sessionColl.deleteOne({_id: docId}));
            }

            if (i % 25 == 0) {
                jsTestLog("ThreadId: " + threadId + ", preparing transaction");
                let prepareTimestamp = PrepareHelpers.prepareTransaction(session);
                if (i % 50 == 0) {
                    // Only commit half of the prepared transactions.
                    jsTestLog("ThreadId: " + threadId + ", committing prepared transaction");
                    PrepareHelpers.commitTransaction(session, prepareTimestamp);
                } else {
                    jsTestLog("ThreadId: " + threadId +
                              ", leaving prepared transaction uncommitted");
                }
                session = undefined;
            }

            if (i % 1000 == 0) {
                jsTestLog("ThreadId: " + threadId + ", Progress: " + (i - start) + "/" +
                          (end - start));
            }
        }
    } catch (e) {
        // The shell may throw after mongod was terminated.
    }
};

const rst = new ReplSetTest({
    nodes: 1,
    nodeOptions: {
        syncdelay: 10,  // Fast checkpoint intervals.
        slowms: 30000,  // Don't log slow queries.
        setParameter:
            {logComponentVerbosity: tojsononeline({storage: {recovery: 2, wt: {wtCheckpoint: 1}}})},
        wiredTigerEngineConfigString:
            "debug_mode=(slow_checkpoint=true,table_logging=true),verbose=[checkpoint_cleanup,checkpoint_progress]"
    }
});
rst.startSet();
rst.initiate();

let primary = rst.getPrimary();

const dbName = "test";
const collName = "foo";

let db = primary.getDB(dbName);
assert.commandWorked(db.createCollection(collName));
let coll = db.getCollection(collName);

// Create many indexes to have more table files.
assert.commandWorked(coll.createIndexes([{a: 1}, {b: 1}, {c: 1}, {d: 1}, {e: 1}]));

const kNumUncleanShutdowns = 5;
let numUncleanShutdowns = 0;
while (numUncleanShutdowns < kNumUncleanShutdowns) {
    jsTestLog("Execution #" + numUncleanShutdowns);

    const kOpsPerThread = 1000000;
    const kNumThreads = 10;
    let threads = [];
    for (let i = 0; i < kNumThreads; i++) {
        let thread = new Thread(threadWorkload,
                                primary.host,
                                i,
                                i * kOpsPerThread,
                                kOpsPerThread + (i * kOpsPerThread));
        threads.push(thread);
        thread.start();
    }

    // Wait between 30 to 60 seconds before shutting down mongod.
    const secsToWait = Math.floor(Math.random() * 30) + 30;
    jsTestLog("Waiting " + secsToWait + " seconds before shutting down");
    sleep(secsToWait * 1000);

    // Start a clean shutdown.
    clearRawMongoProgramOutput();
    const awaitShutdown = startParallelShell(() => {
        db.adminCommand({shutdown: 1});
    }, primary.port);

    assert.soon(() => {
        const logContents = rawMongoProgramOutput();
        return logContents.indexOf("close_ckpt") > 0;
    });

    // During the shutdown checkpoint, kill the process.
    const pid = primary.pid;
    const kSIGKILL = 9;
    jsTestLog("Killing pid: " + pid);
    stopMongoProgramByPid(pid, kSIGKILL);
    jsTestLog("Killed pid: " + pid);

    const exitCode = awaitShutdown({checkExitSuccess: false});
    assert.neq(0, exitCode, 'Expected shell to exit abnormally due to shutdown');

    numUncleanShutdowns++;

    threads.forEach(function(thread) {
        thread.join();
    });

    // Make a copy of the data files after terminating the shutdown. This is helpful for
    // investigations when there is a failure.
    const copyPath = primary.dbpath + kSeparator + "exec" + numUncleanShutdowns.toString();
    resetDbpath(copyPath);
    mkdir(copyPath + kSeparator + "journal");
    copyDataFiles(primary.dbpath, copyPath);

    rst.restart(primary);

    primary = rst.getPrimary();
    db = primary.getDB(dbName);
    coll = db.getCollection(collName);
}

rst.stopSet();
}());