summaryrefslogtreecommitdiff
path: root/src/mongo/db/session_catalog_test.cpp
blob: 9d9e532abadea357760803bd9cc591a4b5292403 (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

/**
 *    Copyright (C) 2018-present MongoDB, Inc.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the Server Side Public License, version 1,
 *    as published by MongoDB, Inc.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    Server Side Public License for more details.
 *
 *    You should have received a copy of the Server Side Public License
 *    along with this program. If not, see
 *    <http://www.mongodb.com/licensing/server-side-public-license>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the Server Side Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#include "mongo/platform/basic.h"

#include "mongo/db/service_context_test_fixture.h"
#include "mongo/db/session_catalog.h"
#include "mongo/stdx/future.h"
#include "mongo/stdx/memory.h"
#include "mongo/unittest/barrier.h"
#include "mongo/unittest/death_test.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/scopeguard.h"

namespace mongo {
namespace {

class SessionCatalogTest : public ServiceContextTest {
protected:
    SessionCatalog* catalog() {
        return SessionCatalog::get(getServiceContext());
    }
};

class SessionCatalogTestWithDefaultOpCtx : public SessionCatalogTest {
protected:
    const ServiceContext::UniqueOperationContext _uniqueOpCtx = makeOperationContext();
    OperationContext* const _opCtx = _uniqueOpCtx.get();
};

// When this class is in scope, makes the system behave as if we're in a DBDirectClient
class DirectClientSetter {
public:
    explicit DirectClientSetter(OperationContext* opCtx)
        : _opCtx(opCtx), _wasInDirectClient(_opCtx->getClient()->isInDirectClient()) {
        _opCtx->getClient()->setInDirectClient(true);
    }

    ~DirectClientSetter() {
        _opCtx->getClient()->setInDirectClient(_wasInDirectClient);
    }

private:
    const OperationContext* _opCtx;
    const bool _wasInDirectClient;
};

TEST_F(SessionCatalogTestWithDefaultOpCtx, CheckoutAndReleaseSession) {
    _opCtx->setLogicalSessionId(makeLogicalSessionIdForTest());

    auto scopedSession = catalog()->checkOutSession(_opCtx);

    ASSERT(scopedSession.get());
    ASSERT_EQ(*_opCtx->getLogicalSessionId(), scopedSession->getSessionId());
}

TEST_F(SessionCatalogTestWithDefaultOpCtx, OperationContextCheckedOutSession) {
    _opCtx->setLogicalSessionId(makeLogicalSessionIdForTest());
    const TxnNumber txnNum = 20;
    _opCtx->setTxnNumber(txnNum);

    OperationContextSession ocs(_opCtx);
    auto session = OperationContextSession::get(_opCtx);
    ASSERT(session);
    ASSERT_EQ(*_opCtx->getLogicalSessionId(), session->getSessionId());
}

TEST_F(SessionCatalogTestWithDefaultOpCtx, NestedOperationContextSession) {
    _opCtx->setLogicalSessionId(makeLogicalSessionIdForTest());

    {
        OperationContextSession outerScopedSession(_opCtx);

        {
            DirectClientSetter inDirectClient(_opCtx);
            OperationContextSession innerScopedSession(_opCtx);

            auto session = OperationContextSession::get(_opCtx);
            ASSERT(session);
            ASSERT_EQ(*_opCtx->getLogicalSessionId(), session->getSessionId());
        }

        {
            DirectClientSetter inDirectClient(_opCtx);
            auto session = OperationContextSession::get(_opCtx);
            ASSERT(session);
            ASSERT_EQ(*_opCtx->getLogicalSessionId(), session->getSessionId());
        }
    }

    ASSERT(!OperationContextSession::get(_opCtx));
}

TEST_F(SessionCatalogTestWithDefaultOpCtx, ScanSessions) {
    std::vector<LogicalSessionId> lsidsFound;
    const auto workerFn = [&lsidsFound](WithLock, Session* session) {
        lsidsFound.push_back(session->getSessionId());
    };

    // Scan over zero Sessions.
    SessionKiller::Matcher matcherAllSessions(
        KillAllSessionsByPatternSet{makeKillAllSessionsByPattern(_opCtx)});
    catalog()->scanSessions(matcherAllSessions, workerFn);
    ASSERT(lsidsFound.empty());
    lsidsFound.clear();

    // Create three sessions in the catalog.
    const std::vector<LogicalSessionId> lsids{makeLogicalSessionIdForTest(),
                                              makeLogicalSessionIdForTest(),
                                              makeLogicalSessionIdForTest()};
    for (const auto& lsid : lsids) {
        stdx::async(stdx::launch::async, [this, lsid] {
            ThreadClient tc(getServiceContext());
            auto opCtx = makeOperationContext();
            const auto unusedSession(catalog()->checkOutSession(opCtx.get(), lsid));
        }).get();
    }

    // Scan over all Sessions.
    catalog()->scanSessions(matcherAllSessions, workerFn);
    ASSERT_EQ(3U, lsidsFound.size());
    lsidsFound.clear();

    // Scan over all Sessions, visiting a particular Session.
    SessionKiller::Matcher matcherLSID2(
        KillAllSessionsByPatternSet{makeKillAllSessionsByPattern(_opCtx, lsids[2])});
    catalog()->scanSessions(matcherLSID2, workerFn);
    ASSERT_EQ(1U, lsidsFound.size());
    ASSERT_EQ(lsids[2], lsidsFound.front());
    lsidsFound.clear();
}

TEST_F(SessionCatalogTest, KillSessionWhenSessionIsNotCheckedOut) {
    const auto lsid = makeLogicalSessionIdForTest();

    // Create the session so there is something to kill
    {
        auto opCtx = makeOperationContext();
        const auto unusedSession(catalog()->checkOutSession(opCtx.get(), lsid));
    }

    auto killToken = catalog()->killSession(lsid);

    // Make sure that regular session check-out will fail because the session is marked as killed
    {
        auto opCtx = makeOperationContext();
        opCtx->setLogicalSessionId(lsid);
        opCtx->setDeadlineAfterNowBy(Milliseconds(10), ErrorCodes::MaxTimeMSExpired);
        ASSERT_THROWS_CODE(
            OperationContextSession(opCtx.get()), AssertionException, ErrorCodes::MaxTimeMSExpired);
    }

    // Schedule a separate "regular operation" thread, which will block on checking-out the session,
    // which we will use to confirm that session kill completion actually unblocks check-out
    auto future = stdx::async(stdx::launch::async, [this, lsid] {
        ThreadClient tc(getServiceContext());
        auto sideOpCtx = Client::getCurrent()->makeOperationContext();
        const auto unusedSession(catalog()->checkOutSession(sideOpCtx.get(), lsid));
    });
    ASSERT(stdx::future_status::ready != future.wait_for(Milliseconds(10).toSystemDuration()));

    // Make sure that "for kill" session check-out succeeds
    {
        auto opCtx = makeOperationContext();
        auto scopedSession = catalog()->checkOutSessionForKill(opCtx.get(), std::move(killToken));
        ASSERT_EQ(opCtx.get(), scopedSession->currentOperation());
    }

    // Make sure that session check-out after kill succeeds again
    {
        auto opCtx = makeOperationContext();
        const auto unusedSession(catalog()->checkOutSession(opCtx.get(), lsid));
    }

    // Make sure the "regular operation" eventually is able to proceed and use the just killed
    // session
    future.get();
}

TEST_F(SessionCatalogTest, KillSessionWhenSessionIsCheckedOut) {
    const auto lsid = makeLogicalSessionIdForTest();

    auto killToken = [this, &lsid] {
        // Create the session so there is something to kill
        auto opCtx = makeOperationContext();
        opCtx->setLogicalSessionId(lsid);
        OperationContextSession operationContextSession(opCtx.get());

        auto killToken = catalog()->killSession(lsid);

        // Make sure the owning operation context is interrupted
        ASSERT_THROWS_CODE(opCtx->checkForInterrupt(), AssertionException, ErrorCodes::Interrupted);

        // Make sure that the checkOutForKill call will wait for the owning operation context to
        // check the session back in
        auto future = stdx::async(stdx::launch::async, [this, lsid] {
            ThreadClient tc(getServiceContext());
            auto sideOpCtx = Client::getCurrent()->makeOperationContext();
            sideOpCtx->setLogicalSessionId(lsid);
            sideOpCtx->setDeadlineAfterNowBy(Milliseconds(10), ErrorCodes::MaxTimeMSExpired);

            const auto unusedSession(catalog()->checkOutSession(sideOpCtx.get(), lsid));
        });

        ASSERT_THROWS_CODE(future.get(), AssertionException, ErrorCodes::MaxTimeMSExpired);

        return killToken;
    }();

    // Make sure that regular session check-out will fail because the session is marked as killed
    {
        auto opCtx = makeOperationContext();
        opCtx->setLogicalSessionId(lsid);
        opCtx->setDeadlineAfterNowBy(Milliseconds(10), ErrorCodes::MaxTimeMSExpired);
        ASSERT_THROWS_CODE(
            OperationContextSession(opCtx.get()), AssertionException, ErrorCodes::MaxTimeMSExpired);
    }

    // Schedule a separate "regular operation" thread, which will block on checking-out the session,
    // which we will use to confirm that session kill completion actually unblocks check-out
    auto future = stdx::async(stdx::launch::async, [this, lsid] {
        ThreadClient tc(getServiceContext());
        auto sideOpCtx = Client::getCurrent()->makeOperationContext();
        const auto unusedSession(catalog()->checkOutSession(sideOpCtx.get(), lsid));
    });
    ASSERT(stdx::future_status::ready != future.wait_for(Milliseconds(10).toSystemDuration()));

    // Make sure that "for kill" session check-out succeeds
    {
        auto opCtx = makeOperationContext();
        auto scopedSession = catalog()->checkOutSessionForKill(opCtx.get(), std::move(killToken));
        ASSERT_EQ(opCtx.get(), scopedSession->currentOperation());
    }

    // Make sure that session check-out after kill succeeds again
    {
        auto opCtx = makeOperationContext();
        const auto unusedSession(catalog()->checkOutSession(opCtx.get(), lsid));
    }

    // Make sure the "regular operation" eventually is able to proceed and use the just killed
    // session
    future.get();
}

TEST_F(SessionCatalogTest, MarkSessionAsKilledCanBeCalledMoreThanOnce) {
    const auto lsid = makeLogicalSessionIdForTest();

    // Create the session so there is something to kill
    {
        auto opCtx = makeOperationContext();
        const auto unusedSession(catalog()->checkOutSession(opCtx.get(), lsid));
    }

    auto killToken1 = catalog()->killSession(lsid);
    auto killToken2 = catalog()->killSession(lsid);

    // Make sure that regular session check-out will fail because there are two killers on the
    // session
    {
        auto opCtx = makeOperationContext();
        opCtx->setLogicalSessionId(lsid);
        opCtx->setDeadlineAfterNowBy(Milliseconds(10), ErrorCodes::MaxTimeMSExpired);
        ASSERT_THROWS_CODE(
            OperationContextSession(opCtx.get()), AssertionException, ErrorCodes::MaxTimeMSExpired);
    }

    boost::optional<Session::KillToken> killTokenWhileSessionIsCheckedOutForKill;

    // Finish the first killer of the session
    {
        auto opCtx = makeOperationContext();
        auto scopedSession = catalog()->checkOutSessionForKill(opCtx.get(), std::move(killToken1));
        ASSERT_EQ(opCtx.get(), scopedSession->currentOperation());

        // Killing a session while checked out for kill should not affect the killers
        killTokenWhileSessionIsCheckedOutForKill.emplace(catalog()->killSession(lsid));
    }

    // Regular session check-out should still fail because there are now still two killers on the
    // session
    {
        auto opCtx = makeOperationContext();
        opCtx->setLogicalSessionId(lsid);
        opCtx->setDeadlineAfterNowBy(Milliseconds(10), ErrorCodes::MaxTimeMSExpired);
        ASSERT_THROWS_CODE(
            OperationContextSession(opCtx.get()), AssertionException, ErrorCodes::MaxTimeMSExpired);
    }
    {
        auto opCtx = makeOperationContext();
        auto scopedSession = catalog()->checkOutSessionForKill(opCtx.get(), std::move(killToken2));
        ASSERT_EQ(opCtx.get(), scopedSession->currentOperation());
    }
    {
        auto opCtx = makeOperationContext();
        auto scopedSession = catalog()->checkOutSessionForKill(
            opCtx.get(), std::move(*killTokenWhileSessionIsCheckedOutForKill));
        ASSERT_EQ(opCtx.get(), scopedSession->currentOperation());
    }
}

TEST_F(SessionCatalogTest, MarkSessionsAsKilledWhenSessionDoesNotExist) {
    const auto nonExistentLsid = makeLogicalSessionIdForTest();
    ASSERT_THROWS_CODE(
        catalog()->killSession(nonExistentLsid), AssertionException, ErrorCodes::NoSuchSession);
}

TEST_F(SessionCatalogTestWithDefaultOpCtx, SessionDiscarOperationContextAfterCheckIn) {
    _opCtx->setLogicalSessionId(makeLogicalSessionIdForTest());

    {
        OperationContextSession ocs(_opCtx);
        ASSERT(OperationContextSession::get(_opCtx));

        OperationContextSession::checkIn(_opCtx);
        ASSERT(!OperationContextSession::get(_opCtx));
    }

    ASSERT(!OperationContextSession::get(_opCtx));
}

TEST_F(SessionCatalogTestWithDefaultOpCtx, SessionDiscarOperationContextAfterCheckInCheckOut) {
    _opCtx->setLogicalSessionId(makeLogicalSessionIdForTest());

    {
        OperationContextSession ocs(_opCtx);
        ASSERT(OperationContextSession::get(_opCtx));

        OperationContextSession::checkIn(_opCtx);
        ASSERT(!OperationContextSession::get(_opCtx));

        OperationContextSession::checkOut(_opCtx);
        ASSERT(OperationContextSession::get(_opCtx));
    }

    ASSERT(!OperationContextSession::get(_opCtx));
}

TEST_F(SessionCatalogTestWithDefaultOpCtx, KillSessionsThroughScanSessions) {
    // Create three sessions
    const std::vector<LogicalSessionId> lsids{makeLogicalSessionIdForTest(),
                                              makeLogicalSessionIdForTest(),
                                              makeLogicalSessionIdForTest()};

    std::vector<stdx::future<void>> futures;
    unittest::Barrier firstUseOfTheSessionReachedBarrier(lsids.size() + 1);

    for (const auto& lsid : lsids) {
        futures.emplace_back(
            stdx::async(stdx::launch::async, [this, lsid, &firstUseOfTheSessionReachedBarrier] {
                ThreadClient tc(getServiceContext());

                {
                    auto sideOpCtx = Client::getCurrent()->makeOperationContext();
                    const auto unusedSession(catalog()->checkOutSession(sideOpCtx.get(), lsid));

                    firstUseOfTheSessionReachedBarrier.countDownAndWait();

                    ASSERT_THROWS_CODE(sideOpCtx->sleepFor(Hours{6}),
                                       AssertionException,
                                       ErrorCodes::ExceededTimeLimit);
                }

                {
                    auto sideOpCtx = Client::getCurrent()->makeOperationContext();
                    sideOpCtx->setLogicalSessionId(lsid);

                    const auto unusedSession(catalog()->checkOutSession(sideOpCtx.get(), lsid));
                }
            }));
    }

    // Make sure all spawned threads have created the session
    firstUseOfTheSessionReachedBarrier.countDownAndWait();

    // Kill the first and the third sessions
    {
        std::vector<Session::KillToken> firstAndThirdTokens;
        catalog()->scanSessions(
            SessionKiller::Matcher(
                KillAllSessionsByPatternSet{makeKillAllSessionsByPattern(_opCtx)}),
            [&lsids, &firstAndThirdTokens](WithLock sessionCatalogLock, Session* session) {
                if (session->getSessionId() == lsids[0] || session->getSessionId() == lsids[2])
                    firstAndThirdTokens.emplace_back(
                        session->kill(sessionCatalogLock, ErrorCodes::ExceededTimeLimit));
            });
        ASSERT_EQ(2U, firstAndThirdTokens.size());
        for (auto& killToken : firstAndThirdTokens) {
            auto unusedSheckedOutSessionForKill(
                catalog()->checkOutSessionForKill(_opCtx, std::move(killToken)));
        }
        futures[0].get();
        futures[2].get();
    }

    // Kill the second session
    {
        std::vector<Session::KillToken> secondToken;
        catalog()->scanSessions(
            SessionKiller::Matcher(
                KillAllSessionsByPatternSet{makeKillAllSessionsByPattern(_opCtx)}),
            [&lsids, &secondToken](WithLock sessionCatalogLock, Session* session) {
                if (session->getSessionId() == lsids[1])
                    secondToken.emplace_back(
                        session->kill(sessionCatalogLock, ErrorCodes::ExceededTimeLimit));
            });
        ASSERT_EQ(1U, secondToken.size());
        for (auto& killToken : secondToken) {
            auto unusedSheckedOutSessionForKill(
                catalog()->checkOutSessionForKill(_opCtx, std::move(killToken)));
        }
        futures[1].get();
    }
}

// Test that session kill will block normal sesion chechout and will be signaled correctly.
// Even if the implementaion has a bug, the test may not always fail depending on thread
// scheduling, however, this test case still gives us a good coverage.
TEST_F(SessionCatalogTestWithDefaultOpCtx, ConcurrentCheckOutAndKill) {
    auto lsid = makeLogicalSessionIdForTest();
    _opCtx->setLogicalSessionId(lsid);

    stdx::future<void> normalCheckOutFinish, killCheckOutFinish;

    // This variable is protected by the session check-out.
    std::string lastSessionCheckOut = "first session";
    {
        // Check out the session to block both normal check-out and checkOutForKill.
        OperationContextSession firstCheckOut(_opCtx);

        // Normal check out should start after kill.
        normalCheckOutFinish = stdx::async(stdx::launch::async, [&] {
            ThreadClient tc(getGlobalServiceContext());
            auto sideOpCtx = Client::getCurrent()->makeOperationContext();
            sideOpCtx->setLogicalSessionId(lsid);
            OperationContextSession normalCheckOut(sideOpCtx.get());
            ASSERT_EQ("session kill", lastSessionCheckOut);
            lastSessionCheckOut = "session checkout";
        });

        // Kill will short-cut the queue and be the next one to check out.
        killCheckOutFinish = stdx::async(stdx::launch::async, [&] {
            ThreadClient tc(getGlobalServiceContext());
            auto sideOpCtx = Client::getCurrent()->makeOperationContext();
            sideOpCtx->setLogicalSessionId(lsid);

            // Kill the session
            std::vector<Session::KillToken> killTokens;
            catalog()->scanSessions(SessionKiller::Matcher(KillAllSessionsByPatternSet{
                                        makeKillAllSessionsByPattern(sideOpCtx.get())}),
                                    [&killTokens](WithLock sessionCatalogLock, Session* session) {
                                        killTokens.emplace_back(session->kill(
                                            sessionCatalogLock, ErrorCodes::InternalError));
                                    });
            ASSERT_EQ(1U, killTokens.size());
            auto checkOutSessionForKill(
                catalog()->checkOutSessionForKill(sideOpCtx.get(), std::move(killTokens[0])));
            ASSERT_EQ("first session", lastSessionCheckOut);
            lastSessionCheckOut = "session kill";
        });

        // The main thread won't check in the session until it's killed.
        {
            stdx::mutex m;
            stdx::condition_variable cond;
            stdx::unique_lock<stdx::mutex> lock(m);
            ASSERT_EQ(ErrorCodes::InternalError,
                      _opCtx->waitForConditionOrInterruptNoAssert(cond, lock));
        }
    }
    normalCheckOutFinish.get();
    killCheckOutFinish.get();
    ASSERT_EQ("session checkout", lastSessionCheckOut);
}

}  // namespace
}  // namespace mongo