summaryrefslogtreecommitdiff
path: root/src/mongo/db/logical_session_cache_test.cpp
blob: b4a301e6b92304d5898156b4dbb44d3e36953059 (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
/**
 *    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/logical_session_cache_impl.h"

#include <memory>

#include "mongo/bson/oid.h"
#include "mongo/db/auth/authorization_manager.h"
#include "mongo/db/auth/authorization_session_for_test.h"
#include "mongo/db/auth/authz_manager_external_state_mock.h"
#include "mongo/db/auth/authz_session_external_state_mock.h"
#include "mongo/db/auth/user_name.h"
#include "mongo/db/logical_session_cache.h"
#include "mongo/db/logical_session_id.h"
#include "mongo/db/logical_session_id_helpers.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/service_context.h"
#include "mongo/db/service_context_test_fixture.h"
#include "mongo/db/service_liaison_mock.h"
#include "mongo/db/sessions_collection_mock.h"
#include "mongo/stdx/future.h"
#include "mongo/unittest/ensure_fcv.h"
#include "mongo/unittest/unittest.h"

namespace mongo {
namespace {

const Milliseconds kSessionTimeout = duration_cast<Milliseconds>(kLogicalSessionDefaultTimeout);
const Milliseconds kForceRefresh{kLogicalSessionRefreshMillisDefault};

using SessionList = std::list<LogicalSessionId>;
using unittest::EnsureFCV;

/**
 * Test fixture that sets up a session cache attached to a mock service liaison
 * and mock sessions collection implementation.
 */
class LogicalSessionCacheTest : public ServiceContextTest {
public:
    LogicalSessionCacheTest()
        : _service(std::make_shared<MockServiceLiaisonImpl>()),
          _sessions(std::make_shared<MockSessionsCollectionImpl>()) {

        AuthorizationManager::set(getServiceContext(), AuthorizationManager::create());

        // Re-initialize the client after setting the AuthorizationManager to get an
        // AuthorizationSession.
        Client::releaseCurrent();
        Client::initThread(getThreadName());
        _opCtx = makeOperationContext();

        auto mockService = std::make_unique<MockServiceLiaison>(_service);
        auto mockSessions = std::make_unique<MockSessionsCollection>(_sessions);
        _cache = std::make_unique<LogicalSessionCacheImpl>(
            std::move(mockService),
            std::move(mockSessions),
            [](OperationContext*, SessionsCollection&, Date_t) {
                return 0; /* No op*/
            });
    }

    void waitUntilRefreshScheduled() {
        while (service()->jobs() < 2) {
            sleepmillis(10);
        }
    }

    std::unique_ptr<LogicalSessionCache>& cache() {
        return _cache;
    }

    std::shared_ptr<MockServiceLiaisonImpl> service() {
        return _service;
    }

    std::shared_ptr<MockSessionsCollectionImpl> sessions() {
        return _sessions;
    }

    OperationContext* opCtx() {
        return _opCtx.get();
    }

private:
    ServiceContext::UniqueOperationContext _opCtx;

    std::shared_ptr<MockServiceLiaisonImpl> _service;
    std::shared_ptr<MockSessionsCollectionImpl> _sessions;

    std::unique_ptr<LogicalSessionCache> _cache;
};

// Test that promoting from the cache updates the lastUse date of records
TEST_F(LogicalSessionCacheTest, VivifyUpdatesLastUse) {
    auto lsid = makeLogicalSessionIdForTest();

    auto start = service()->now();

    // Insert the record into the sessions collection with 'start'
    ASSERT_OK(cache()->startSession(opCtx(), makeLogicalSessionRecord(lsid, start)));

    // Fast forward time and promote
    service()->fastForward(Milliseconds(500));
    ASSERT_OK(cache()->vivify(opCtx(), lsid));

    // Now that we promoted, lifetime of session should be extended
    service()->fastForward(kSessionTimeout - Milliseconds(500));
    ASSERT_OK(cache()->vivify(opCtx(), lsid));

    // We promoted again, so lifetime extended again
    service()->fastForward(kSessionTimeout - Milliseconds(500));
    ASSERT_OK(cache()->vivify(opCtx(), lsid));

    // Fast forward and promote
    service()->fastForward(kSessionTimeout - Milliseconds(10));
    ASSERT_OK(cache()->vivify(opCtx(), lsid));

    // Lifetime extended again
    service()->fastForward(Milliseconds(11));
    ASSERT_OK(cache()->vivify(opCtx(), lsid));
}

// Test the startSession method
TEST_F(LogicalSessionCacheTest, StartSession) {
    auto record = makeLogicalSessionRecord(makeLogicalSessionIdForTest(), service()->now());
    auto lsid = record.getId();

    // Test starting a new session
    ASSERT_OK(cache()->startSession(opCtx(), record));

    // Record will not be in the collection yet; refresh must happen first.
    ASSERT(!sessions()->has(lsid));

    // Do refresh, cached records should get flushed to collection.
    ASSERT(cache()->refreshNow(opCtx()).isOK());
    ASSERT(sessions()->has(lsid));

    // Try to start the same session again, should succeed.
    ASSERT_OK(cache()->startSession(opCtx(), record));

    // Try to start a session that is already in the sessions collection but
    // is not in our local cache, should succeed.
    auto record2 = makeLogicalSessionRecord(makeLogicalSessionIdForTest(), service()->now());
    sessions()->add(record2);
    ASSERT_OK(cache()->startSession(opCtx(), record2));

    // Try to start a session that has expired from our cache, and is no
    // longer in the sessions collection, should succeed
    service()->fastForward(Milliseconds(kSessionTimeout.count() + 5));
    sessions()->remove(lsid);
    ASSERT(!sessions()->has(lsid));
    ASSERT_OK(cache()->startSession(opCtx(), record));
}

// Test that session cache properly expires lsids after 30 minutes of no use
TEST_F(LogicalSessionCacheTest, BasicSessionExpiration) {
    // Insert a lsid
    auto record = makeLogicalSessionRecordForTest();
    ASSERT_OK(cache()->startSession(opCtx(), record));
    ASSERT_EQ(1UL, cache()->size());

    // Force it to expire
    service()->fastForward(Milliseconds(kSessionTimeout.count() + 5));

    // Check that it is no longer in the cache
    ASSERT_OK(cache()->refreshNow(opCtx()));
    ASSERT_EQ(0UL, cache()->size());
}

// Test large sets of cache-only session lsids
TEST_F(LogicalSessionCacheTest, ManySignedLsidsInCacheRefresh) {
    int count = 10000;
    for (int i = 0; i < count; i++) {
        auto record = makeLogicalSessionRecordForTest();
        ASSERT_OK(cache()->startSession(opCtx(), record));
    }

    // Check that all signedLsids refresh
    sessions()->setRefreshHook([&count](const LogicalSessionRecordSet& sessions) {
        ASSERT_EQ(sessions.size(), size_t(count));
        return Status::OK();
    });

    // Force a refresh
    service()->fastForward(kForceRefresh);
    ASSERT_OK(cache()->refreshNow(opCtx()));
}

//
TEST_F(LogicalSessionCacheTest, RefreshMatrixSessionState) {
    const std::vector<std::vector<std::string>> stateNames = {
        {"active", "inactive"},
        {"running", "not running"},
        {"expired", "unexpired"},
        {"ended", "not ended"},
        {"cursor", "no cursor"},
    };
    struct {
        // results that we test for after the _refresh
        bool inCollection;
        bool killed;
    } testCases[] = {
        // 0, active, running, expired, ended, cursor
        {false, true},
        // 1, inactive, running, expired, ended, cursor
        {false, true},
        // 2, active, not running, expired, ended, cursor
        {false, true},
        // 3, inactive, not running, expired, ended, cursor
        {false, true},
        // 4, active, running, unexpired, ended, cursor
        {false, true},
        // 5, inactive, running, unexpired, ended, cursor
        {false, true},
        // 6, active, not running, unexpired, ended, cursor
        {false, true},
        // 7, inactive, not running, unexpired, ended, cursor
        {false, true},
        // 8, active, running, expired, not ended, cursor
        {true, false},
        // 9, inactive, running, expired, not ended, cursor
        {false, true},
        // 10, active, not running, expired, not ended, cursor
        {true, false},
        // 11, inactive, not running, expired, not ended, cursor
        {false, true},
        // 12, active, running, unexpired, not ended, cursor
        {true, false},
        // 13, inactive, running, unexpired, not ended, cursor
        {true, false},
        // 14, active, not running, unexpired, not ended, cursor
        {true, false},
        // 15, inactive, not running, unexpired, not ended, cursor
        {true, false},
        // 16, active, running, expired, ended, no cursor
        {false, true},
        // 17, inactive, running, expired, ended, no cursor
        {false, true},
        // 18, active, not running, expired, ended, no cursor
        {false, true},
        // 19, inactive, not running, expired, ended, no cursor
        {false, true},
        // 20, active, running, unexpired, ended, no cursor
        {false, true},
        // 21, inactive, running, unexpired, ended, no cursor
        {false, true},
        // 22, active, not running, unexpired, ended, no cursor
        {false, true},
        // 23, inactive, not running, unexpired, ended, no cursor
        {false, true},
        // 24, active, running, expired, not ended, no cursor
        {true, false},
        // 25, inactive, running, expired, not ended, no cursor
        {false, true},
        // 26, active, not running, expired, not ended, no cursor
        {true, false},
        // 27, inactive, not running, expired, not ended, no cursor
        {false, false},
        // 28, active, running, unexpired, not ended, no cursor
        {true, false},
        // 29, inactive, running, unexpired, not ended, no cursor
        {true, false},
        // 30, active, not running, unexpired, not ended, no cursor
        {true, false},
        // 31, inactive, not running, unexpired, not ended, no cursor
        {true, false},
    };

    std::vector<LogicalSessionId> ids;
    for (int i = 0; i < 32; i++) {

        bool active = !(i & 1);
        bool running = !(i & 2);
        bool expired = !(i & 4);
        bool ended = !(i & 8);
        bool cursor = !(i & 16);

        auto lsid = makeLogicalSessionIdForTest();
        ids.push_back(lsid);
        auto lsRecord = makeLogicalSessionRecord(lsid, service()->now() + Milliseconds(500));

        if (running) {
            service()->add(lsid);
        }
        if (active) {
            ASSERT_OK(cache()->startSession(opCtx(), lsRecord));
        }
        if (!expired) {
            sessions()->add(lsRecord);
        }
        if (ended) {
            LogicalSessionIdSet lsidSet;
            lsidSet.emplace(lsid);
            cache()->endSessions(lsidSet);
        }
        if (cursor) {
            service()->addCursorSession(lsid);
        }
    }

    // Force a refresh
    service()->fastForward(kForceRefresh);
    ASSERT_OK(cache()->refreshNow(opCtx()));

    for (int i = 0; i < 32; i++) {
        std::stringstream failText;
        failText << "case " << i << " : ";
        for (int j = 0; j < 4; j++) {
            failText << stateNames[j][i >> j & 1] << " ";
        }
        failText << " session case failed: ";

        ASSERT(sessions()->has(ids[i]) == testCases[i].inCollection)
            << failText.str()
            << (testCases[i].inCollection ? "session wasn't in collection"
                                          : "session was in collection");
        ASSERT((service()->matchKilled(ids[i]) != nullptr) == testCases[i].killed)
            << failText.str()
            << (testCases[i].killed ? "session wasn't killed" : "session was killed");
    }
}


}  // namespace
}  // namespace mongo