summaryrefslogtreecommitdiff
path: root/jstests/replsets/tenant_migration_concurrent_reads_on_recipient.js
blob: 21bcb2c55f9fd184d96f57a03e8deb4dbf6dbac7 (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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
/**
 * Tests that
 * - the recipient rejects all reads between when cloning is done and the rejectReadsBeforeTimestamp
 * - the recipient rejects only reads with atClusterTime <
 *   rejectReadsBeforeTimestamp after rejectReadsBeforeTimestamp is reached.
 * - if the migration aborts before the recipient sets a rejectReadsBeforeTimestamp, the recipient
 *   keeps rejecting all reads until the state doc is marked as garbage collectable.
 * - if the migration aborts after rejectReadsBeforeTimestamp is set, the recipient keeps rejecting
 *   reads with atClusterTime < rejectReadsBeforeTimestamp until the state doc is garbage collected.
 *
 * @tags: [
 *   incompatible_with_macos,
 *   incompatible_with_windows_tls,
 *   requires_majority_read_concern,
 *   requires_persistence,
 *   serverless,
 * ]
 */

import {TenantMigrationTest} from "jstests/replsets/libs/tenant_migration_test.js";
import {runMigrationAsync} from "jstests/replsets/libs/tenant_migration_util.js";

load("jstests/libs/fail_point_util.js");
load("jstests/libs/parallelTester.js");
load("jstests/libs/uuid_util.js");
load("jstests/replsets/rslib.js");  // 'createRstArgs'

const kCollName = "testColl";
const kTenantDefinedDbName = "0";

function runCommand(db, cmd, expectedError) {
    const res = db.runCommand(cmd);

    if (expectedError) {
        assert.commandFailedWithCode(res, expectedError, tojson(cmd));
        if (expectedError == ErrorCodes.SnapshotTooOld) {
            // Verify that SnapshotTooOld error is due to migration conflict not due to the read
            // timestamp being older than the oldest available timestamp.
            assert.eq(res.errmsg, "Tenant read is not allowed before migration completes");
        }
    } else {
        assert.commandWorked(res);
    }

    if (cmd.lsid) {
        const notRejectReadsFp = configureFailPoint(db, "tenantMigrationRecipientNotRejectReads");
        assert.commandWorked(db.runCommand({killSessions: [cmd.lsid]}));
        notRejectReadsFp.off();
    }
}

/**
 * Tests that the recipient starts rejecting all reads after cloning is done.
 */
function testRejectAllReadsAfterCloningDone({testCase, dbName, collName, tenantMigrationTest}) {
    const tenantId = dbName.split('_')[0];
    const migrationOpts = {
        migrationIdString: extractUUIDFromObject(UUID()),
        tenantId,
        recipientConnString: tenantMigrationTest.getRecipientConnString(),
    };

    const donorRst = tenantMigrationTest.getDonorRst();
    const recipientRst = tenantMigrationTest.getRecipientRst();
    const recipientPrimary = recipientRst.getPrimary();

    let beforeFetchingTransactionsFp = configureFailPoint(
        recipientPrimary, "fpBeforeFetchingCommittedTransactions", {action: "hang"});

    const donorRstArgs = createRstArgs(donorRst);
    const runMigrationThread = new Thread(runMigrationAsync, migrationOpts, donorRstArgs);
    runMigrationThread.start();
    beforeFetchingTransactionsFp.wait();

    // Wait for the write to mark cloning as done to be replicated to all nodes.
    recipientRst.awaitReplication();

    const nodes = testCase.isSupportedOnSecondaries ? recipientRst.nodes : [recipientPrimary];
    nodes.forEach(node => {
        const command = testCase.requiresReadTimestamp
            ? testCase.command(collName, getLastOpTime(node).ts)
            : testCase.command(collName);
        const db = node.getDB(dbName);
        runCommand(db, command, ErrorCodes.SnapshotTooOld);
    });

    beforeFetchingTransactionsFp.off();
    TenantMigrationTest.assertCommitted(runMigrationThread.returnData());
    assert.commandWorked(tenantMigrationTest.forgetMigration(migrationOpts.migrationIdString));
    tenantMigrationTest.waitForMigrationGarbageCollection(migrationOpts.migrationIdString);
}

/**
 * Tests that after the recipient has reached the rejectReadsBeforeTimestamp and
 * after the migration commits, it only rejects reads with atClusterTime <
 * rejectReadsBeforeTimestamp.
 */
function testRejectOnlyReadsWithAtClusterTimeLessThanRejectReadsBeforeTimestamp(
    {testCase, dbName, collName, tenantMigrationTest}) {
    const tenantId = dbName.split('_')[0];
    const migrationOpts = {
        migrationIdString: extractUUIDFromObject(UUID()),
        tenantId,
        recipientConnString: tenantMigrationTest.getRecipientConnString(),
    };

    const donorRst = tenantMigrationTest.getDonorRst();
    const donorPrimary = donorRst.getPrimary();
    const recipientRst = tenantMigrationTest.getRecipientRst();
    const recipientPrimary = recipientRst.getPrimary();

    // Select a read timestamp < rejectReadsBeforeTimestamp.
    const preMigrationTimestamp = getLastOpTime(donorPrimary).ts;

    let waitForRejectReadsBeforeTsFp = configureFailPoint(
        recipientPrimary, "fpAfterWaitForRejectReadsBeforeTimestamp", {action: "hang"});

    const donorRstArgs = createRstArgs(donorRst);
    const runMigrationThread = new Thread(runMigrationAsync, migrationOpts, donorRstArgs);
    runMigrationThread.start();
    waitForRejectReadsBeforeTsFp.wait();

    // Wait for the last oplog entry on the primary to be visible in the committed snapshot view of
    // the oplog on all the secondaries. This is to ensure that snapshot reads on secondaries with
    // unspecified atClusterTime have read timestamp >= rejectReadsBeforeTimestamp.
    recipientRst.awaitLastOpCommitted();

    const recipientDoc =
        recipientPrimary.getCollection(TenantMigrationTest.kConfigRecipientsNS).findOne({
            _id: UUID(migrationOpts.migrationIdString),
        });
    assert.lt(preMigrationTimestamp, recipientDoc.rejectReadsBeforeTimestamp);

    const nodes = testCase.isSupportedOnSecondaries ? recipientRst.nodes : [recipientPrimary];
    nodes.forEach(node => {
        const db = node.getDB(dbName);
        if (testCase.requiresReadTimestamp) {
            runCommand(
                db, testCase.command(collName, preMigrationTimestamp), ErrorCodes.SnapshotTooOld);
            runCommand(
                db, testCase.command(collName, recipientDoc.rejectReadsBeforeTimestamp), null);
        } else {
            // Untimestamped reads are not rejected after the recipient has applied data past the
            // rejectReadsBeforeTimestamp. Snapshot reads with unspecified atClusterTime should have
            // read timestamp >= rejectReadsBeforeTimestamp so are also not rejected.
            runCommand(db, testCase.command(collName), null);
        }
    });

    waitForRejectReadsBeforeTsFp.off();
    TenantMigrationTest.assertCommitted(runMigrationThread.returnData());

    nodes.forEach(node => {
        const db = node.getDB(dbName);
        if (testCase.requiresReadTimestamp) {
            runCommand(
                db, testCase.command(collName, preMigrationTimestamp), ErrorCodes.SnapshotTooOld);
            runCommand(
                db, testCase.command(collName, recipientDoc.rejectReadsBeforeTimestamp), null);
        } else {
            // Untimestamped reads are not rejected after the recipient has committed. Snapshot
            // reads with unspecified atClusterTime should have read timestamp >=
            // rejectReadsBeforeTimestamp so are also not rejected.
            runCommand(db, testCase.command(collName), null);
        }
    });

    assert.commandWorked(tenantMigrationTest.forgetMigration(migrationOpts.migrationIdString));
    tenantMigrationTest.waitForMigrationGarbageCollection(migrationOpts.migrationIdString);
}

/**
 * Tests that if the migration aborts before the recipient sets the rejectReadsBeforeTimestamp, the
 * recipient keeps rejecting all reads until the state doc is marked as garbage collectable.
 */
function testDoNotRejectReadsAfterMigrationAbortedBeforeReachingRejectReadsBeforeTimestamp(
    {testCase, dbName, collName, tenantMigrationTest}) {
    const tenantId = dbName.split('_')[0];
    const migrationOpts = {
        migrationIdString: extractUUIDFromObject(UUID()),
        tenantId,
    };

    const recipientRst = tenantMigrationTest.getRecipientRst();
    const recipientPrimary = recipientRst.getPrimary();

    // Force the recipient to abort the migration right before it responds to the first
    // recipientSyncData (i.e. before it receives returnAfterReachingTimestamp in the second
    // recipientSyncData).
    let abortFp = configureFailPoint(recipientPrimary,
                                     "fpBeforeFulfillingDataConsistentPromise",
                                     {action: "stop", stopErrorCode: ErrorCodes.InternalError});
    TenantMigrationTest.assertAborted(
        tenantMigrationTest.runMigration(migrationOpts, {automaticForgetMigration: false}));
    abortFp.off();

    const nodes = testCase.isSupportedOnSecondaries ? recipientRst.nodes : [recipientPrimary];
    nodes.forEach(node => {
        const db = node.getDB(dbName);
        if (testCase.requiresReadTimestamp) {
            runCommand(
                db, testCase.command(collName, getLastOpTime(node).ts), ErrorCodes.SnapshotTooOld);
        } else {
            runCommand(db, testCase.command(collName), ErrorCodes.SnapshotTooOld);
        }
    });

    assert.commandWorked(tenantMigrationTest.forgetMigration(migrationOpts.migrationIdString));

    // Wait for the write to mark the state doc as garbage collectable to be replicated to all
    // nodes.
    recipientRst.awaitReplication();

    nodes.forEach(node => {
        const db = node.getDB(dbName);
        if (testCase.requiresReadTimestamp) {
            runCommand(db, testCase.command(collName, getLastOpTime(node).ts), null);
        } else {
            runCommand(db, testCase.command(collName), null);
        }
    });
    tenantMigrationTest.waitForMigrationGarbageCollection(migrationOpts.migrationIdString);
}

/**
 * Tests if the migration aborts after rejectReadsBeforeTimestamp is set, the recipient keeps
 * rejecting reads with atClusterTime < rejectReadsBeforeTimestamp until the state doc is garbage
 * collected.
 */
function testDoNotRejectReadsAfterMigrationAbortedAfterReachingRejectReadsBeforeTimestamp(
    {testCase, dbName, collName, tenantMigrationTest}) {
    const tenantId = dbName.split('_')[0];
    const migrationId = UUID();
    const migrationOpts = {
        migrationIdString: extractUUIDFromObject(migrationId),
        tenantId,
    };

    const donorRst = tenantMigrationTest.getDonorRst();
    const donorPrimary = donorRst.getPrimary();
    const recipientRst = tenantMigrationTest.getRecipientRst();
    const recipientPrimary = recipientRst.getPrimary();

    const setParametersCmd = {
        setParameter: 1,
        // Set the delay before a state doc is garbage collected to be short to speed up the test.
        tenantMigrationGarbageCollectionDelayMS: 3 * 1000,
        ttlMonitorSleepSecs: 1,
    };
    donorRst.nodes.forEach(node => {
        assert.commandWorked(node.adminCommand(setParametersCmd));
    });
    recipientRst.nodes.forEach(node => {
        assert.commandWorked(node.adminCommand(setParametersCmd));
    });

    // Select a read timestamp < rejectReadsBeforeTimestamp.
    const preMigrationTimestamp = getLastOpTime(donorPrimary).ts;

    // Force the donor to abort the migration right after the recipient responds to the second
    // recipientSyncData (i.e. after it has reached the returnAfterReachingTimestamp).
    let abortFp =
        configureFailPoint(donorPrimary, "abortTenantMigrationBeforeLeavingBlockingState");
    TenantMigrationTest.assertAborted(
        tenantMigrationTest.runMigration(migrationOpts, {automaticForgetMigration: false}));
    abortFp.off();

    // Wait for the last oplog entry on the primary to be visible in the committed snapshot view of
    // the oplog on all the secondaries. This is to ensure that snapshot reads on secondaries with
    // unspecified atClusterTime have read timestamp >= rejectReadsBeforeTimestamp.
    recipientRst.awaitLastOpCommitted();

    const recipientDoc =
        recipientPrimary.getCollection(TenantMigrationTest.kConfigRecipientsNS).findOne({
            _id: UUID(migrationOpts.migrationIdString),
        });

    const nodes = testCase.isSupportedOnSecondaries ? recipientRst.nodes : [recipientPrimary];
    nodes.forEach(node => {
        const db = node.getDB(dbName);
        if (testCase.requiresReadTimestamp) {
            runCommand(
                db, testCase.command(collName, preMigrationTimestamp), ErrorCodes.SnapshotTooOld);
            runCommand(
                db, testCase.command(collName, recipientDoc.rejectReadsBeforeTimestamp), null);
        } else {
            // Untimestamped reads are not rejected after the recipient has applied data past the
            // rejectReadsBeforeTimestamp. Snapshot reads with unspecified atClusterTime should have
            // read timestamp >= rejectReadsBeforeTimestamp so are also not rejected.
            runCommand(db, testCase.command(collName), null);
        }
    });

    assert.commandWorked(tenantMigrationTest.forgetMigration(migrationOpts.migrationIdString));
    tenantMigrationTest.waitForMigrationGarbageCollection(migrationId, migrationOpts.tenantId);

    nodes.forEach(node => {
        const db = node.getDB(dbName);
        if (testCase.requiresReadTimestamp) {
            runCommand(db, testCase.command(collName, preMigrationTimestamp), null);
            runCommand(
                db, testCase.command(collName, recipientDoc.rejectReadsBeforeTimestamp), null);
        } else {
            runCommand(db, testCase.command(collName), null);
        }
    });
}

const testCases = {
    readWithReadConcernLocal: {
        isSupportedOnSecondaries: true,
        command: function(collName) {
            return {
                find: collName,
                readConcern: {
                    level: "local",
                }
            };
        },
    },
    readWithReadConcernAvailable: {
        isSupportedOnSecondaries: true,
        command: function(collName) {
            return {
                find: collName,
                readConcern: {
                    level: "available",
                }
            };
        },
    },
    readWithReadConcernMajority: {
        isSupportedOnSecondaries: true,
        command: function(collName) {
            return {
                find: collName,
                readConcern: {
                    level: "majority",
                }
            };
        },
    },
    linearizableRead: {
        isSupportedOnSecondaries: false,
        command: function(collName) {
            return {
                find: collName,
                readConcern: {level: "linearizable"},
            };
        }
    },
    snapshotReadWithAtClusterTime: {
        isSupportedOnSecondaries: true,
        requiresReadTimestamp: true,
        command: function(collName, readTimestamp) {
            return {
                find: collName,
                readConcern: {
                    level: "snapshot",
                    atClusterTime: readTimestamp,
                }
            };
        },
    },
    snapshotReadNoAtClusterTime: {
        isSupportedOnSecondaries: true,
        command: function(collName) {
            return {
                find: collName,
                readConcern: {
                    level: "snapshot",
                }
            };
        },
    },
    snapshotReadAtClusterTimeTxn: {
        isSupportedOnSecondaries: false,
        requiresReadTimestamp: true,
        command: function(collName, readTimestamp) {
            return {
                find: collName,
                lsid: {id: UUID()},
                txnNumber: NumberLong(0),
                startTransaction: true,
                autocommit: false,
                readConcern: {level: "snapshot", atClusterTime: readTimestamp}
            };
        }
    },
    snapshotReadNoAtClusterTimeTxn: {
        isSupportedOnSecondaries: false,
        command: function(collName) {
            return {
                find: collName,
                lsid: {id: UUID()},
                txnNumber: NumberLong(0),
                startTransaction: true,
                autocommit: false,
                readConcern: {level: "snapshot"}
            };
        }
    },
};

const testFuncs = {
    afterCloningDone: testRejectAllReadsAfterCloningDone,
    afterReachingBlockTs: testRejectOnlyReadsWithAtClusterTimeLessThanRejectReadsBeforeTimestamp,
    abortBeforeReachingBlockTs:
        testDoNotRejectReadsAfterMigrationAbortedBeforeReachingRejectReadsBeforeTimestamp,
    abortAfterReachingBlockTs:
        testDoNotRejectReadsAfterMigrationAbortedAfterReachingRejectReadsBeforeTimestamp
};

const tenantMigrationTest = new TenantMigrationTest({
    name: jsTestName(),
    quickGarbageCollection: true,
});
for (const [testName, testFunc] of Object.entries(testFuncs)) {
    for (const [testCaseName, testCase] of Object.entries(testCases)) {
        let tenantId = ObjectId().str;
        jsTest.log("Testing " + testName + " with testCase " + testCaseName + " with tenantId " +
                   tenantId);
        let migrationDb = `${tenantId}_test`;
        tenantMigrationTest.insertDonorDB(migrationDb, "test");
        let dbName = `${tenantId}_${kTenantDefinedDbName}`;

        // Force the recipient to preserve all snapshot history to ensure that snapshot reads do
        // not fail with SnapshotTooOld due to snapshot being unavailable.
        tenantMigrationTest.getRecipientRst().nodes.forEach(node => {
            configureFailPoint(node, "WTPreserveSnapshotHistoryIndefinitely");
        });

        testFunc({testCase, dbName, collName: kCollName, tenantMigrationTest});

        // ShardMerge is not robust to migrating the twice in quick succession. We drop the data
        // files to ensure a subsequent tenant migration will avoid trying to merge files from the
        // previous migration.
        assert.commandWorked(
            tenantMigrationTest.getDonorRst().getPrimary().getDB(migrationDb).dropDatabase());
        assert.commandWorked(
            tenantMigrationTest.getRecipientRst().getPrimary().getDB(migrationDb).dropDatabase());
    }
}
tenantMigrationTest.stop();