summaryrefslogtreecommitdiff
path: root/jstests/replsets/tenant_migration_multi_writes.js
blob: c825c29a26458257c53ad6072230352eafac9bf3 (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
/**
 * Stress test verifies that non-idempotent multi updates made during tenant migration
 * were not retried on migration abort, which would create duplicate updates. Partially
 * updated collection where each update is applied no more than once is still an expected result.
 *
 * @tags: [
 *   incompatible_with_eft,
 *   incompatible_with_macos,
 *   incompatible_with_windows_tls,
 *   requires_majority_read_concern,
 *   requires_persistence,
 *   serverless,
 * ]
 */

(function() {
"use strict";

load("jstests/libs/fail_point_util.js");
load("jstests/libs/parallelTester.js");
load("jstests/libs/uuid_util.js");
load("jstests/replsets/libs/tenant_migration_test.js");
load("jstests/replsets/libs/tenant_migration_util.js");

const donorRst = new ReplSetTest({
    nodes: [{}, {rsConfig: {priority: 0}}, {rsConfig: {priority: 0}}],
    name: "TenantMigrationTest_donor",
    nodeOptions: Object.assign(TenantMigrationUtil.makeX509OptionsForTest().donor, {
        setParameter: {
            // Set the delay before a donor state doc is garbage collected to be short to speed up
            // the test.
            tenantMigrationGarbageCollectionDelayMS: 3 * 1000,

            // Set the TTL monitor to run at a smaller interval to speed up the test.
            ttlMonitorSleepSecs: 1,
        }
    })
});
const oplogMinRetentionHours = 2;  // Set to standard Evergreen task timeout time
donorRst.startSet({oplogMinRetentionHours});
donorRst.initiateWithHighElectionTimeout();
const tenantMigrationTest = new TenantMigrationTest({name: jsTestName(), donorRst: donorRst});

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

const kTenantIdPrefix = "testTenantId";
const kCollName = "testColl";
const kTenantDefinedDbName = "0";
const kTenantId = `${kTenantIdPrefix}-multiWrites`;
const kDbName = tenantMigrationTest.tenantDB(kTenantId, kTenantDefinedDbName);

const kRecords = 2000;
const kUpdateCycles = 600;

function prepareDatabase(dbName) {
    let db = donorPrimary.getDB(dbName);
    try {
        db.dropDatabase();
    } catch (err) {
        // First time the DB doesn't exist.
    }
    assert.commandWorked(db.runCommand({create: kCollName}));
    let bulk = db[kCollName].initializeUnorderedBulkOp();
    for (let i = 0; i < kRecords; ++i) {
        bulk.insert({_id: i, x: 0, a: 1});
    }
    assert.commandWorked(bulk.execute());
}

function doMultiUpdate(
    primaryHost, dbName, collName, records, updateCycles, readConcern, writeConcern) {
    const donorPrimary = new Mongo(primaryHost);
    let db = donorPrimary.getDB(dbName);
    let completedCycles;

    for (completedCycles = 0; completedCycles < updateCycles; ++completedCycles) {
        try {
            let bulk = db[collName].initializeUnorderedBulkOp();
            bulk.find({a: 1}).update({$inc: {x: 1}});
            bulk.execute({w: writeConcern});
        } catch (err) {
            jsTestLog(`Received error ${err}`);
            assert.commandFailedWithCode(err, ErrorCodes.Interrupted);
            let findResult = assert.commandWorked(
                db.runCommand({find: collName, readConcern: {level: readConcern}}));
            var cursor = new DBCommandCursor(db, findResult);
            cursor.forEach(doc => {
                assert(doc.x == completedCycles || doc.x == completedCycles + 1,
                       "expected each doc to be updated at most once");
            });
            break;
        }
    }

    jsTestLog(`All updates completed without consistency error, in ${completedCycles} cycles`);
}

function testMultiWritesWhileInBlockingState(readConcern, writeConcern) {
    prepareDatabase(kDbName);

    let writesThread = new Thread(
        // Start non-idempotent writes in a thread.
        doMultiUpdate,
        donorPrimary.host,
        kDbName,
        kCollName,
        kRecords,
        kUpdateCycles,
        readConcern,
        writeConcern);
    writesThread.start();

    for (let i = 0; i < 10; ++i) {
        const migrationId = UUID();
        const migrationOpts = {
            migrationIdString: extractUUIDFromObject(migrationId),
            tenantId: kTenantId,
            recipientConnString: tenantMigrationTest.getRecipientConnString(),
        };
        let abortFp =
            configureFailPoint(donorPrimary, "abortTenantMigrationBeforeLeavingBlockingState", {
                blockTimeMS: Math.floor(Math.random() * 10),
            });
        assert.commandWorked(tenantMigrationTest.startMigration(migrationOpts));

        TenantMigrationTest.assertAborted(tenantMigrationTest.waitForMigrationToComplete(
            migrationOpts, false /* retryOnRetryableErrors */));

        abortFp.wait();
        abortFp.off();

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

        jsTest.log('Drop DB and wait for garbage collection after test cycle.');
        assert.commandWorked(recipientRst.getPrimary().getDB(kDbName).dropDatabase());
    }

    writesThread.join();
}

let readWriteConcerns = [];
readWriteConcerns.push({writeConcern: 1, readConcern: 'local'});
readWriteConcerns.push({writeConcern: 'majority', readConcern: 'majority'});

readWriteConcerns.forEach(concerns => {
    jsTest.log(`Test sending multi write while in migration blocking state with ${concerns}`);
    testMultiWritesWhileInBlockingState(concerns.readConcern, concerns.writeConcern);
});

tenantMigrationTest.stop();
donorRst.stopSet();
})();