summaryrefslogtreecommitdiff
path: root/jstests/replsets/tenant_migration_external_keys_ttl.js
blob: 91af232c2ea761f4f3cc82a29b8c76ae4ae8a8ed (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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
/**
 * Tests that tenant migrations correctly set the TTL values for keys in the
 * config.external_validation_keys collection.
 *
 * @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 {
    forgetMigrationAsync,
    getExternalKeys,
    isShardMergeEnabled,
    kExternalKeysNs,
    makeX509OptionsForTest
} from "jstests/replsets/libs/tenant_migration_util.js";

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

const kExternalKeysTTLIndexName = "ExternalKeysTTLIndex";
const ttlMonitorOptions = {
    ttlMonitorSleepSecs: 1
};

let makeTenantId = function() {
    return ObjectId().str;
};

function waitForExternalKeysTTLIndex(conn) {
    assert.soon(() => {
        const indexSpecs = conn.getCollection(kExternalKeysNs).getIndexSpecs();
        const hasIndex = indexSpecs.some(indexSpec => {
            return indexSpec.name === kExternalKeysTTLIndexName &&
                indexSpec.key.ttlExpiresAt === 1 && indexSpec.expireAfterSeconds === 0;
        });

        if (hasIndex) {
            return true;
        }
        jsTestLog("Waiting for external keys index to be created, current indexes: " +
                  tojson(indexSpecs));
    });
}

function waitForExternalKeysToBeDeleted(conn, migrationId) {
    assert.soonNoExcept(() => {
        const externalKeys = getExternalKeys(conn, migrationId);
        assert.eq(0, externalKeys.length, tojson(externalKeys));
        return true;
    });
}

function verifyExternalKeys(conn, {migrationId, expectTTLValue}) {
    const externalKeys = conn.getCollection(kExternalKeysNs).find({migrationId}).toArray();
    assert.gt(externalKeys.length, 0);

    externalKeys.forEach(key => {
        assert.eq(expectTTLValue, key.hasOwnProperty("ttlExpiresAt"), tojson(key));
    });
}

function setTenantMigrationExpirationParams(conn, stateDocParam, externalKeysParam) {
    const origStateDocParam = assert.commandWorked(
        conn.adminCommand({getParameter: 1, tenantMigrationGarbageCollectionDelayMS: 1}));
    const origExternalKeysParam = assert.commandWorked(
        conn.adminCommand({getParameter: 1, tenantMigrationExternalKeysRemovalBufferSecs: 1}));

    assert.commandWorked(conn.adminCommand(
        {setParameter: 1, tenantMigrationGarbageCollectionDelayMS: stateDocParam}));
    assert.commandWorked(conn.adminCommand(
        {setParameter: 1, tenantMigrationExternalKeysRemovalBufferSecs: externalKeysParam}));

    return [
        origStateDocParam.tenantMigrationGarbageCollectionDelayMS,
        origExternalKeysParam.tenantMigrationExternalKeysRemovalBufferSecs
    ];
}

function makeTestParams() {
    const tenantId = makeTenantId();
    const migrationId = UUID();
    const migrationOpts = {
        migrationIdString: extractUUIDFromObject(migrationId),
        tenantId: tenantId,
    };
    return [tenantId, migrationId, migrationOpts];
}

//
// Tests with no failovers.
//

(() => {
    function setup() {
        const tmt = new TenantMigrationTest(
            {name: jsTestName(), sharedOptions: {setParameter: ttlMonitorOptions}});

        // Verify the external keys TTL index is created on both replica sets on stepup.
        waitForExternalKeysTTLIndex(tmt.getDonorPrimary());
        waitForExternalKeysTTLIndex(tmt.getRecipientPrimary());

        return {
            tmt,
            teardown: function() {
                tmt.stop();
            },
        };
    }

    (() => {
        jsTestLog("Basic case with multiple migrations");
        const {tmt, teardown} = setup();
        if (isShardMergeEnabled(tmt.getDonorPrimary().getDB("admin"))) {
            // This test runs multiple concurrent migrations, which shard merge can't handle.
            jsTestLog(
                "Skip: featureFlagShardMerge is enabled and this test runs multiple concurrent migrations, which shard merge can't handle.");
            teardown();
            return;
        }
        const [tenantId, migrationId, migrationOpts] = makeTestParams();

        TenantMigrationTest.assertCommitted(
            tmt.runMigration(migrationOpts, {automaticForgetMigration: false}));

        // The keys should have been created without a TTL deadline.
        verifyExternalKeys(tmt.getDonorPrimary(), {migrationId, expectTTLValue: false});
        verifyExternalKeys(tmt.getRecipientPrimary(), {migrationId, expectTTLValue: false});

        // Run another migration to verify key expiration is only set for a specific migration's
        // keys.
        const otherMigrationId = UUID();
        const otherMigrationOpts = {
            migrationIdString: extractUUIDFromObject(otherMigrationId),
            tenantId: makeTenantId(),
        };

        TenantMigrationTest.assertCommitted(
            tmt.runMigration(otherMigrationOpts, {automaticForgetMigration: false}));

        // The keys should have been created without a TTL deadline.
        verifyExternalKeys(tmt.getDonorPrimary(),
                           {migrationId: otherMigrationId, expectTTLValue: false});
        verifyExternalKeys(tmt.getRecipientPrimary(),
                           {migrationId: otherMigrationId, expectTTLValue: false});

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

        // After running donorForgetMigration, the TTL value should be updated. The default TTL
        // buffer is 1 day so the keys will not have been deleted.
        verifyExternalKeys(tmt.getDonorPrimary(), {migrationId, expectTTLValue: true});
        verifyExternalKeys(tmt.getRecipientPrimary(), {migrationId, expectTTLValue: true});

        // The keys for the other migration should not have been affected.
        verifyExternalKeys(tmt.getDonorPrimary(),
                           {migrationId: otherMigrationId, expectTTLValue: false});
        verifyExternalKeys(tmt.getRecipientPrimary(),
                           {migrationId: otherMigrationId, expectTTLValue: false});
        teardown();
    })();

    jsTestLog("Verify the TTL value is respected and keys are eventually reaped");
    {
        const {tmt, teardown} = setup();
        const [tenantId, migrationId, migrationOpts] = makeTestParams();

        const lowerExternalKeysBufferSecs = 5;
        const lowerStateDocExpirationMS = 500;
        const [origDonorStateDocExpirationParam, origDonorKeysExpirationParam] =
            setTenantMigrationExpirationParams(
                tmt.getDonorPrimary(), lowerStateDocExpirationMS, lowerExternalKeysBufferSecs);
        const [origRecipientStateDocExpirationParam, origRecipientKeysExpirationParam] =
            setTenantMigrationExpirationParams(
                tmt.getRecipientPrimary(), lowerStateDocExpirationMS, lowerExternalKeysBufferSecs);

        // Verify the default value of the buffer.
        assert.eq(origDonorKeysExpirationParam, 60 * 60 * 24);      // 1 day.
        assert.eq(origRecipientKeysExpirationParam, 60 * 60 * 24);  // 1 day.

        TenantMigrationTest.assertCommitted(
            tmt.runMigration(migrationOpts, {automaticForgetMigration: false}));

        // The keys should have been created without a TTL deadline.
        verifyExternalKeys(tmt.getDonorPrimary(), {migrationId, expectTTLValue: false});
        verifyExternalKeys(tmt.getRecipientPrimary(), {migrationId, expectTTLValue: false});

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

        // The keys won't be deleted until the buffer expires, so sleep to avoid wasted work.
        sleep((lowerExternalKeysBufferSecs * 1000) + lowerStateDocExpirationMS + 500);

        // Wait for the keys to be deleted on both replica sets.
        waitForExternalKeysToBeDeleted(tmt.getDonorPrimary(), migrationId);
        waitForExternalKeysToBeDeleted(tmt.getRecipientPrimary(), migrationId);

        // Restore the original timeouts
        setTenantMigrationExpirationParams(
            tmt.getDonorPrimary(), origDonorStateDocExpirationParam, origDonorKeysExpirationParam);
        setTenantMigrationExpirationParams(tmt.getRecipientPrimary(),
                                           origRecipientStateDocExpirationParam,
                                           origRecipientKeysExpirationParam);
        teardown();
    }
})();

//
// Tests with failovers
//

(() => {
    function setup() {
        const migrationX509Options = makeX509OptionsForTest();
        const donorRst = new ReplSetTest({
            nodes: 3,
            name: "donorRst",
            serverless: true,
            nodeOptions:
                Object.assign(migrationX509Options.donor, {setParameter: ttlMonitorOptions})
        });
        donorRst.startSet();
        donorRst.initiate();

        const recipientRst = new ReplSetTest({
            nodes: 3,
            name: "recipientRst",
            serverless: true,
            nodeOptions:
                Object.assign(migrationX509Options.recipient, {setParameter: ttlMonitorOptions})
        });
        recipientRst.startSet();
        recipientRst.initiate();

        const tmt = new TenantMigrationTest({name: jsTestName(), donorRst, recipientRst});

        return {
            tmt,
            donorRst,
            recipientRst,
            teardown: function() {
                donorRst.stopSet();
                recipientRst.stopSet();
                tmt.stop();
            },
        };
    }

    jsTestLog("Donor failover before receiving forgetMigration");
    {
        const {tmt, teardown} = setup();
        const [tenantId, migrationId, migrationOpts] = makeTestParams();
        const donorPrimary = tmt.getDonorPrimary();
        const fp =
            configureFailPoint(donorPrimary, "pauseTenantMigrationBeforeLeavingBlockingState");

        assert.commandWorked(tmt.startMigration(migrationOpts));
        fp.wait();

        assert.commandWorked(
            donorPrimary.adminCommand({replSetStepDown: ReplSetTest.kForeverSecs, force: true}));
        assert.commandWorked(donorPrimary.adminCommand({replSetFreeze: 0}));
        fp.off();

        TenantMigrationTest.assertCommitted(
            tmt.waitForMigrationToComplete(migrationOpts, true /* retryOnRetryableErrors */));

        // The keys should have been created without a TTL deadline.
        verifyExternalKeys(tmt.getDonorPrimary(), {migrationId, expectTTLValue: false});
        verifyExternalKeys(tmt.getRecipientPrimary(), {migrationId, expectTTLValue: false});

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

        // After running donorForgetMigration, the TTL value should be updated. The default TTL
        // buffer is 1 day so the keys will not have been deleted.
        verifyExternalKeys(tmt.getDonorPrimary(), {migrationId, expectTTLValue: true});
        verifyExternalKeys(tmt.getRecipientPrimary(), {migrationId, expectTTLValue: true});
        teardown();
    }

    // TODO SERVER-76128: Tenant Migrations are not robust to recipient failover.
    // jsTestLog("Recipient failover before receiving forgetMigration");
    // (() => {
    //     const {tmt, teardown} = setup();
    //     const [tenantId, migrationId, migrationOpts] = makeTestParams();
    //     const recipientPrimary = tmt.getRecipientPrimary();
    //     const fp = configureFailPoint(recipientPrimary,
    //                                   "fpAfterConnectingTenantMigrationRecipientInstance",
    //                                   {action: "hang"});

    //     if (isShardMergeEnabled(tmt.getDonorPrimary().getDB("admin"))) {
    //         jsTestLog(
    //             "Skip: featureFlagShardMerge is enabled and shard merge is not resilient to
    //             recipient failovers.");
    //         teardown();
    //         return;
    //     }

    //     assert.commandWorked(tmt.startMigration(migrationOpts));
    //     fp.wait();

    //     assert.commandWorked(recipientPrimary.adminCommand(
    //         {replSetStepDown: ReplSetTest.kForeverSecs, force: true}));
    //     assert.commandWorked(recipientPrimary.adminCommand({replSetFreeze: 0}));

    //     fp.off();

    //     TenantMigrationTest.assertCommitted(
    //         tmt.waitForMigrationToComplete(migrationOpts, true /* retryOnRetryableErrors */));

    //     // The keys should have been created without a TTL deadline.
    //     verifyExternalKeys(tmt.getDonorPrimary(), {migrationId, expectTTLValue: false});
    //     verifyExternalKeys(tmt.getRecipientPrimary(), {migrationId, expectTTLValue: false});

    //     assert.commandWorked(tmt.forgetMigration(migrationOpts.migrationIdString));

    //     // After running donorForgetMigration, the TTL value should be updated. The default TTL
    //     // buffer is 1 day so the keys will not have been deleted.
    //     verifyExternalKeys(tmt.getDonorPrimary(), {migrationId, expectTTLValue: true});
    //     verifyExternalKeys(tmt.getRecipientPrimary(), {migrationId, expectTTLValue: true});
    //     teardown();
    // })();

    jsTestLog(
        "Donor failover after receiving forgetMigration before marking keys garbage collectable");
    {
        const {tmt, donorRst, teardown} = setup();
        const [tenantId, migrationId, migrationOpts] = makeTestParams();
        const donorPrimary = tmt.getDonorPrimary();

        assert.commandWorked(tmt.startMigration(migrationOpts));
        TenantMigrationTest.assertCommitted(
            tmt.waitForMigrationToComplete(migrationOpts, true /* retryOnRetryableErrors */));

        // The keys should have been created without a TTL deadline.
        verifyExternalKeys(tmt.getDonorPrimary(), {migrationId, expectTTLValue: false});
        verifyExternalKeys(tmt.getRecipientPrimary(), {migrationId, expectTTLValue: false});

        const fp = configureFailPoint(
            donorPrimary, "pauseTenantMigrationBeforeMarkingExternalKeysGarbageCollectable");
        const forgetMigrationThread = new Thread(
            forgetMigrationAsync, migrationOpts.migrationIdString, createRstArgs(donorRst), true);
        forgetMigrationThread.start();
        fp.wait();

        assert.commandWorked(
            donorPrimary.adminCommand({replSetStepDown: ReplSetTest.kForeverSecs, force: true}));
        assert.commandWorked(donorPrimary.adminCommand({replSetFreeze: 0}));
        fp.off();

        assert.commandWorked(forgetMigrationThread.returnData());

        // After running donorForgetMigration, the TTL value should be updated. The default TTL
        // buffer is 1 day so the keys will not have been deleted.
        verifyExternalKeys(tmt.getDonorPrimary(), {migrationId, expectTTLValue: true});
        verifyExternalKeys(tmt.getRecipientPrimary(), {migrationId, expectTTLValue: true});
        teardown();
    }

    // TODO SERVER-76128: Tenant Migrations are not robust to recipient failover.
    // jsTestLog(
    //     "Recipient failover after receiving forgetMigration before marking keys garbage
    //     collectable");
    // {
    //     const {tmt, donorRst, teardown} = setup();
    //     const [tenantId, migrationId, migrationOpts] = makeTestParams();
    //     const recipientPrimary = tmt.getRecipientPrimary();

    //     assert.commandWorked(tmt.startMigration(migrationOpts));
    //     TenantMigrationTest.assertCommitted(
    //         tmt.waitForMigrationToComplete(migrationOpts, true /* retryOnRetryableErrors */));

    //     // The keys should have been created without a TTL deadline.
    //     verifyExternalKeys(tmt.getDonorPrimary(), {migrationId, expectTTLValue: false});
    //     verifyExternalKeys(tmt.getRecipientPrimary(), {migrationId, expectTTLValue: false});

    //     const fp = configureFailPoint(
    //         recipientPrimary, "pauseTenantMigrationBeforeMarkingExternalKeysGarbageCollectable");
    //     const forgetMigrationThread = new Thread(
    //         forgetMigrationAsync, migrationOpts.migrationIdString, createRstArgs(donorRst),
    //         true);
    //     forgetMigrationThread.start();
    //     fp.wait();

    //     assert.commandWorked(recipientPrimary.adminCommand(
    //         {replSetStepDown: ReplSetTest.kForeverSecs, force: true}));
    //     assert.commandWorked(recipientPrimary.adminCommand({replSetFreeze: 0}));
    //     fp.off();

    //     assert.commandWorked(forgetMigrationThread.returnData());

    //     verifyExternalKeys(tmt.getDonorPrimary(), {migrationId, expectTTLValue: true});
    //     verifyExternalKeys(tmt.getRecipientPrimary(), {migrationId, expectTTLValue: true});
    //     teardown();
    // }

    jsTestLog("Donor failover after receiving forgetMigration after updating keys.");
    {
        const {tmt, donorRst, recipientRst, teardown} = setup();
        // this test expects the external keys to expire, so lower the expiration timeouts.
        const lowerExternalKeysBufferSecs = 5;
        const lowerStateDocExpirationMS = 500;
        for (let conn of [...donorRst.nodes, ...recipientRst.nodes]) {
            setTenantMigrationExpirationParams(
                conn, lowerStateDocExpirationMS, lowerExternalKeysBufferSecs);
        }
        const [tenantId, migrationId, migrationOpts] = makeTestParams();
        const donorPrimary = tmt.getDonorPrimary();

        assert.commandWorked(tmt.startMigration(migrationOpts));
        TenantMigrationTest.assertCommitted(
            tmt.waitForMigrationToComplete(migrationOpts, true /* retryOnRetryableErrors */));

        // The keys should have been created without a TTL deadline.
        verifyExternalKeys(tmt.getDonorPrimary(), {migrationId, expectTTLValue: false});
        verifyExternalKeys(tmt.getRecipientPrimary(), {migrationId, expectTTLValue: false});

        const fp = configureFailPoint(
            donorPrimary, "pauseTenantMigrationDonorBeforeMarkingStateGarbageCollectable");
        const forgetMigrationThread = new Thread(
            forgetMigrationAsync, migrationOpts.migrationIdString, createRstArgs(donorRst), true);
        forgetMigrationThread.start();
        fp.wait();

        // Let the keys expire on the donor before the state document is deleted to verify retrying
        // recipientForgetMigration can handle this case. The keys won't be deleted until the buffer
        // expires, so sleep to avoid wasted work.
        sleep((lowerExternalKeysBufferSecs * 1000) + lowerStateDocExpirationMS + 500);
        waitForExternalKeysToBeDeleted(tmt.getDonorPrimary(), migrationId);
        waitForExternalKeysToBeDeleted(tmt.getRecipientPrimary(), migrationId);

        assert.commandWorked(
            donorPrimary.adminCommand({replSetStepDown: ReplSetTest.kForeverSecs, force: true}));
        assert.commandWorked(donorPrimary.adminCommand({replSetFreeze: 0}));
        fp.off();

        assert.commandWorked(forgetMigrationThread.returnData());
        teardown();
    }

    // TODO SERVER-76128: Tenant Migrations are not robust to recipient failover.
    // jsTestLog("Recipient failover after receiving forgetMigration after updating keys.");
    // (() => {
    //     const {tmt, donorRst, recipientRst, teardown} = setup();
    //     // this test expects the external keys to expire, so lower the expiration timeouts.
    //     const lowerExternalKeysBufferSecs = 5;
    //     const lowerStateDocExpirationMS = 500;
    //     for (let conn of [...donorRst.nodes, ...recipientRst.nodes]) {
    //         setTenantMigrationExpirationParams(
    //             conn, lowerStateDocExpirationMS, lowerExternalKeysBufferSecs);
    //     }
    //     const [tenantId, migrationId, migrationOpts] = makeTestParams();
    //     const recipientPrimary = tmt.getRecipientPrimary();

    //     if (isShardMergeEnabled(tmt.getDonorPrimary().getDB("admin"))) {
    //         jsTestLog(
    //             "Skip: featureFlagShardMerge is enabled. Shard merge deletes keys after marking
    //             the recipient state document as 'aborted'.");
    //         teardown();
    //         return;
    //     }

    //     assert.commandWorked(tmt.startMigration(migrationOpts));
    //     TenantMigrationTest.assertCommitted(
    //         tmt.waitForMigrationToComplete(migrationOpts, true /* retryOnRetryableErrors */));

    //     // The keys should have been created without a TTL deadline.
    //     verifyExternalKeys(tmt.getDonorPrimary(), {migrationId, expectTTLValue: false});
    //     verifyExternalKeys(tmt.getRecipientPrimary(), {migrationId, expectTTLValue: false});

    //     let fp;
    //     if (isShardMergeEnabled(tmt.getDonorPrimary().getDB("admin"))) {
    //         fp = configureFailPoint(
    //             recipientPrimary, "fpBeforeMarkingStateDocAsGarbageCollectable", {action:
    //             "hang"});
    //     } else {
    //         fp = configureFailPoint(
    //             recipientPrimary, "fpAfterReceivingRecipientForgetMigration", {action: "hang"});
    //     }
    //     const forgetMigrationThread = new Thread(
    //         forgetMigrationAsync, migrationOpts.migrationIdString, createRstArgs(donorRst),
    //         true);
    //     forgetMigrationThread.start();
    //     fp.wait();

    //     // Let the keys expire on the recipient before the state document is deleted to verify
    //     // retrying recipientForgetMigration can handle this case. The keys won't be deleted
    //     until
    //     // the buffer expires, so sleep to avoid wasted work.
    //     sleep((lowerExternalKeysBufferSecs * 1000) + lowerStateDocExpirationMS + 500);
    //     waitForExternalKeysToBeDeleted(tmt.getRecipientPrimary(), migrationId);

    //     assert.commandWorked(recipientPrimary.adminCommand(
    //         {replSetStepDown: ReplSetTest.kForeverSecs, force: true}));
    //     assert.commandWorked(recipientPrimary.adminCommand({replSetFreeze: 0}));
    //     fp.off();

    //     assert.commandWorked(forgetMigrationThread.returnData());

    //     // Eventually the donor's keys should be deleted too.
    //     waitForExternalKeysToBeDeleted(tmt.getDonorPrimary(), migrationId);
    //     teardown();
    // })();
})();