summaryrefslogtreecommitdiff
path: root/src/mongo/db/operation_cpu_timer_test.cpp
blob: 57e916151a02ec6bdd0efd981d4606116c6e8609 (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
/**
 *    Copyright (C) 2020-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/db/operation_cpu_timer.h"
#include "mongo/db/service_context_test_fixture.h"
#include "mongo/logv2/log.h"
#include "mongo/platform/atomic_word.h"
#include "mongo/stdx/chrono.h"
#include "mongo/stdx/condition_variable.h"
#include "mongo/stdx/mutex.h"
#include "mongo/stdx/thread.h"
#include "mongo/unittest/barrier.h"
#include "mongo/unittest/death_test.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/duration.h"
#include "mongo/util/time_support.h"

#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kTest


namespace mongo {

class OperationCPUTimerTest : public ServiceContextTest {
public:
    auto makeClient() const {
        return getGlobalServiceContext()->makeClient("AlternativeClient");
    }

    OperationCPUTimers* getTimers() const {
        return OperationCPUTimers::get(_opCtx.get());
    }

    std::unique_ptr<OperationCPUTimer> makeTimer() const {
        return getTimers()->makeTimer();
    }

    void setUp() {
        _opCtx = getGlobalServiceContext()->makeOperationContext(Client::getCurrent());
    }

    void busyWait(Nanoseconds delay) const {
        AtomicWord<bool> mayJoin{false};
        stdx::thread blocker([&] {
            sleepFor(delay);
            mayJoin.store(true);
        });
        while (!mayJoin.load()) {
            // Busy wait for the blocker thread.
        }
        blocker.join();
    }

    void resetOpCtx() {
        _opCtx.reset();
    }

private:
    ServiceContext::UniqueOperationContext _opCtx;
};

#if defined(__linux__)

TEST_F(OperationCPUTimerTest, TestTimer) {
    auto timer = makeTimer();

    timer->start();
    busyWait(Microseconds(1));  // A small delay to make sure the timer advances.
    ASSERT_GT(timer->getElapsed(), Nanoseconds(0));
    timer->stop();

    const auto elapsedAfterStop = timer->getElapsed();
    busyWait(Microseconds(10));  // A relatively longer delay to ensure the timer doesn't proceed.
    const auto elapsedAfterSleep = timer->getElapsed();
    ASSERT_EQ(elapsedAfterStop, elapsedAfterSleep);
}

TEST_F(OperationCPUTimerTest, TestReset) {
    auto timer = makeTimer();

    timer->start();
    busyWait(Milliseconds(2));  // Introducing some delay for the timer to measure.
    timer->stop();
    auto elapsedAfterStop = timer->getElapsed();
    // Due to inconsistencies between the CPU time-based clock used in the timer and the
    // clock used in busyWait, the elapsed CPU time is sometimes observed as being less than the
    // time spent busy waiting. To account for that, only assert that at least 1ms of CPU time has
    // elapsed even though the thread was supposed to have busy-waited for 2ms.
    ASSERT_GTE(elapsedAfterStop, Milliseconds(1));

    timer->start();
    auto elapsedAfterReset = timer->getElapsed();
    ASSERT_LT(elapsedAfterReset, elapsedAfterStop);
}

TEST_F(OperationCPUTimerTest, TestTimerDetachAndAttachHandlers) {
    unittest::Barrier failPointsReady{2};
    stdx::thread observer([&] {
        FailPointEnableBlock fpAttach("hangCPUTimerAfterOnThreadAttach");
        {
            FailPointEnableBlock fpDetach("hangCPUTimerAfterOnThreadDetach");
            failPointsReady.countDownAndWait();
            fpDetach->waitForTimesEntered(fpDetach.initialTimesEntered() + 1);
        }
        fpAttach->waitForTimesEntered(fpAttach.initialTimesEntered() + 1);
    });

    auto timer1 = makeTimer();
    timer1->start();

    auto timer2 = makeTimer();
    timer2->start();

    failPointsReady.countDownAndWait();
    {
        auto client = makeClient();
        AlternativeClientRegion acr(client);
    }

    busyWait(Microseconds(1));  // A small delay to make sure the timers advance.

    timer1->stop();
    timer2->stop();
    observer.join();

    ASSERT_GT(timer1->getElapsed(), Nanoseconds(0));
    ASSERT_GT(timer2->getElapsed(), Nanoseconds(0));
}

TEST_F(OperationCPUTimerTest, MultipleTimers) {
    auto timer1 = makeTimer();
    timer1->start();

    {
        auto timer2 = makeTimer();
        timer2->start();

        busyWait(Microseconds(1));  // A small delay to make sure the timers advance.
        ASSERT_GT(timer1->getElapsed(), Nanoseconds(0));
        ASSERT_GT(timer2->getElapsed(), Nanoseconds(0));

        ASSERT_EQ(2, getTimers()->count());
    }

    ASSERT_EQ(1, getTimers()->count());

    timer1->stop();

    auto elapsedAfterStop = timer1->getElapsed();
    busyWait(Milliseconds(10));  // A small delay to make sure the timer could advance.
    auto elapsedAfterSleep = timer1->getElapsed();
    ASSERT_EQ(elapsedAfterSleep, elapsedAfterStop);
}

TEST_F(OperationCPUTimerTest, MultipleTimersOutOfOrder) {
    auto timer1 = makeTimer();
    timer1->start();

    auto timer2 = makeTimer();
    timer2->start();

    busyWait(Microseconds(1));  // A small delay to make sure the timers advance.
    ASSERT_GT(timer1->getElapsed(), Nanoseconds(0));
    ASSERT_GT(timer2->getElapsed(), Nanoseconds(0));

    // Note that there should be no restriction against stopping the first timer first.
    timer1->stop();

    auto elapsedAfterStop = timer1->getElapsed();
    busyWait(Milliseconds(10));  // A small delay to make sure the timer could advance.
    auto elapsedAfterSleep = timer1->getElapsed();
    ASSERT_EQ(elapsedAfterSleep, elapsedAfterStop);

    timer2->stop();
    ASSERT_GT(timer2->getElapsed(), elapsedAfterStop);
    elapsedAfterStop = timer2->getElapsed();
    busyWait(Milliseconds(10));  // A small delay to make sure the timer could advance.
    elapsedAfterSleep = timer2->getElapsed();
    ASSERT_EQ(elapsedAfterSleep, elapsedAfterStop);

    ASSERT_EQ(2, getTimers()->count());
}

TEST_F(OperationCPUTimerTest, TestOpCtxDestruction) {
    auto timer = makeTimer();
    timer->start();
    resetOpCtx();
    timer->stop();
}

DEATH_TEST_F(OperationCPUTimerTest, StopTimerBeforeStart, "Timer is not running") {
    auto timer = makeTimer();
    timer->stop();
}

DEATH_TEST_F(OperationCPUTimerTest, StartTimerMultipleTimes, "Timer has already started") {
    auto timer = makeTimer();
    timer->start();
    timer->start();
}

DEATH_TEST_F(OperationCPUTimerTest, OnAttachForAttachedTimer, "Timer has already been attached") {
    auto timer = makeTimer();
    timer->start();
    timer->onThreadAttach();
}

DEATH_TEST_F(OperationCPUTimerTest, OnDetachForDetachedTimer, "Timer is not attached") {
    auto timer = makeTimer();
    timer->start();
    auto client = Client::releaseCurrent();
    timer->onThreadDetach();
}

DEATH_TEST_F(OperationCPUTimerTest, GetElapsedForPausedTimer, "Not attached to current thread") {
    auto timer = makeTimer();
    timer->start();
    auto client = Client::releaseCurrent();
    timer->getElapsed();
}

TEST_F(OperationCPUTimerTest, TimerPausesOnBlockingSleep) {
    // This test checks if the time measured by `OperationCPUTimer` does not include the period of
    // time the operation was blocked (e.g., waiting on a condition variable). The idea is to have
    // the operation block for `kSomeDelay`, ensure the elapsed time observed by the timer is always
    // less than `kSomeDelay`, and repeat the test `kRepeats` times. To account for the sporadic
    // wake ups, the test does not fail unless the number of failures exceeds `kMaxFailures`. This
    // is just a best-effort, and the number of failures is not guaranteed to not exceed the upper
    // bound (i.e., `kMaxFailures`).
    const auto kSomeDelay = Milliseconds(1);
    const auto kRepeats = 1000;
    const auto kMaxFailureRate = 0.1;
    const auto kMaxFailures = kMaxFailureRate * kRepeats;

    auto timer = makeTimer();

    auto checkTimer = [&] {
        auto elapsed = timer->getElapsed();
        if (elapsed < kSomeDelay)
            return true;
        LOGV2_WARNING(5160101,
                      "Elapsed operation time exceeded the upper bound",
                      "elapsed"_attr = elapsed,
                      "delay"_attr = kSomeDelay);
        return false;
    };

    auto failures = 0;
    for (auto i = 0; i < kRepeats; i++) {
        timer->start();
        sleepFor(kSomeDelay);
        if (!checkTimer())
            failures++;
        timer->stop();

        stdx::condition_variable cv;
        auto mutex = MONGO_MAKE_LATCH("TimerPausesOnBlockingSleep");
        timer->start();
        stdx::unique_lock lk(mutex);
        cv.wait_for(lk, kSomeDelay.toSystemDuration(), [] { return false; });
        if (!checkTimer())
            failures++;
        timer->stop();
    }

    ASSERT_LTE(failures, kMaxFailures);
}

#else

TEST_F(OperationCPUTimerTest, TimerNotSetIfNotSupported) {
    auto timer = getTimers();
    ASSERT(timer == nullptr);
}

#endif  // defined(__linux__)

}  // namespace mongo